blob: 875f0f19ad98f1d47c706387ccf1daaca698d371 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000096 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000097
Douglas Gregor6ed40e32008-12-23 21:05:05 +000098 // Add scoped declarations into their context, so that they can be
99 // found later. Declarations without a context won't be inserted
100 // into any context.
101 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
102 CurContext->addDecl(Context, SD);
103
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104 // C++ [basic.scope]p4:
105 // -- exactly one declaration shall declare a class name or
106 // enumeration name that is not a typedef name and the other
107 // declarations shall all refer to the same object or
108 // enumerator, or all refer to functions and function templates;
109 // in this case the class name or enumeration name is hidden.
110 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
111 // We are pushing the name of a tag (enum or class).
Douglas Gregor44b43212008-12-11 16:49:14 +0000112 if (CurContext == TD->getDeclContext()) {
113 // We're pushing the tag into the current context, which might
114 // require some reshuffling in the identifier resolver.
115 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000116 I = IdResolver.begin(TD->getDeclName(), CurContext,
117 false/*LookInParentCtx*/),
118 IEnd = IdResolver.end();
119 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
120 NamedDecl *PrevDecl = *I;
121 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
122 PrevDecl = *I, ++I) {
123 if (TD->declarationReplaces(*I)) {
124 // This is a redeclaration. Remove it from the chain and
125 // break out, so that we'll add in the shadowed
126 // declaration.
127 S->RemoveDecl(*I);
128 if (PrevDecl == *I) {
129 IdResolver.RemoveDecl(*I);
130 IdResolver.AddDecl(TD);
131 return;
132 } else {
133 IdResolver.RemoveDecl(*I);
134 break;
135 }
136 }
137 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000138
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000139 // There is already a declaration with the same name in the same
140 // scope, which is not a tag declaration. It must be found
141 // before we find the new declaration, so insert the new
142 // declaration at the end of the chain.
143 IdResolver.AddShadowedDecl(TD, PrevDecl);
144
145 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000146 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000147 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000148 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 // We are pushing the name of a function, which might be an
150 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000151 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000152 IdentifierResolver::iterator Redecl
153 = std::find_if(IdResolver.begin(FD->getDeclName(), CurContext,
154 false/*LookInParentCtx*/),
155 IdResolver.end(),
156 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
157 FD));
158 if (Redecl != IdResolver.end()) {
159 // There is already a declaration of a function on our
160 // IdResolver chain. Replace it with this declaration.
161 S->RemoveDecl(*Redecl);
162 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000164 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000166 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000167}
168
Steve Naroffb216c882007-10-09 22:01:59 +0000169void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000170 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000171 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
172 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
175 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000176 Decl *TmpD = static_cast<Decl*>(*I);
177 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000178
Douglas Gregor44b43212008-12-11 16:49:14 +0000179 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
180 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000181
Douglas Gregor44b43212008-12-11 16:49:14 +0000182 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000183
Douglas Gregor44b43212008-12-11 16:49:14 +0000184 // Remove this name from our lexical scope.
185 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 }
187}
188
Steve Naroffe8043c32008-04-01 23:04:06 +0000189/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
190/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000191ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000192 // The third "scope" argument is 0 since we aren't enabling lazy built-in
193 // creation from this context.
194 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000195
Steve Naroffb327ce02008-04-02 14:35:35 +0000196 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000197}
198
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000199/// MaybeConstructOverloadSet - Name lookup has determined that the
200/// elements in [I, IEnd) have the name that we are looking for, and
201/// *I is a match for the namespace. This routine returns an
202/// appropriate Decl for name lookup, which may either be *I or an
203/// OverloadeFunctionDecl that represents the overloaded functions in
204/// [I, IEnd).
205///
206/// The existance of this routine is temporary; LookupDecl should
207/// probably be able to return multiple results, to deal with cases of
208/// ambiguity and overloaded functions without needing to create a
209/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000210template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000211static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000212MaybeConstructOverloadSet(ASTContext &Context,
213 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000214 assert(I != IEnd && "Iterator range cannot be empty");
215 assert(!isa<OverloadedFunctionDecl>(*I) &&
216 "Cannot have an overloaded function");
217
218 if (isa<FunctionDecl>(*I)) {
219 // If we found a function, there might be more functions. If
220 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000222 OverloadedFunctionDecl *Ovl = 0;
223 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
224 if (!Ovl) {
225 // FIXME: We leak this overload set. Eventually, we want to
226 // stop building the declarations for these overload sets, so
227 // there will be nothing to leak.
228 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000229 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000230 (*I)->getDeclName());
231 Ovl->addOverload(cast<FunctionDecl>(*I));
232 }
233 Ovl->addOverload(cast<FunctionDecl>(*Last));
234 }
235
236 // If we had more than one function, we built an overload
237 // set. Return it.
238 if (Ovl)
239 return Ovl;
240 }
241
242 return *I;
243}
244
Steve Naroffe8043c32008-04-01 23:04:06 +0000245/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000246/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000247Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000248 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000249 bool enableLazyBuiltinCreation,
Douglas Gregor0a59acb2008-12-16 00:38:16 +0000250 bool LookInParent) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000251 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000252 unsigned NS = NSI;
253 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
254 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000255
Douglas Gregore267ff32008-12-11 20:41:00 +0000256 if (LookupCtx == 0 &&
257 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
258 // Unqualified name lookup in C/Objective-C and name lookup for
259 // labels in C++ is purely lexical, so search in the
260 // declarations attached to the name.
261 assert(!LookupCtx && "Can't perform qualified name lookup here");
262 IdentifierResolver::iterator I
263 = IdResolver.begin(Name, CurContext, LookInParent);
264
265 // Scan up the scope chain looking for a decl that matches this
266 // identifier that is in the appropriate namespace. This search
267 // should not take long, as shadowing of names is uncommon, and
268 // deep shadowing is extremely uncommon.
269 for (; I != IdResolver.end(); ++I)
270 if ((*I)->getIdentifierNamespace() & NS)
271 return *I;
272 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000273 // Perform qualified name lookup into the LookupCtx.
274 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000275 DeclContext::lookup_const_iterator I, E;
276 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
277 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000278 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregore267ff32008-12-11 20:41:00 +0000279 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000280 // Name lookup for ordinary names and tag names in C++ requires
281 // looking into scopes that aren't strictly lexical, and
282 // therefore we walk through the context as well as walking
283 // through the scopes.
284 IdentifierResolver::iterator
285 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
286 IEnd = IdResolver.end();
287 for (; S; S = S->getParent()) {
288 // Check whether the IdResolver has anything in this scope.
289 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000290 for (; I != IEnd && S->isDeclScope(*I); ++I) {
291 if ((*I)->getIdentifierNamespace() & NS) {
292 // We found something. Look for anything else in our scope
293 // with this same name and in an acceptable identifier
294 // namespace, so that we can construct an overload set if we
295 // need to.
296 IdentifierResolver::iterator LastI = I;
297 for (++LastI; LastI != IEnd; ++LastI) {
298 if (((*LastI)->getIdentifierNamespace() & NS) == 0 ||
299 !S->isDeclScope(*LastI))
300 break;
301 }
302 return MaybeConstructOverloadSet(Context, I, LastI);
303 }
304 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000305
306 // If there is an entity associated with this scope, it's a
307 // DeclContext. We might need to perform qualified lookup into
308 // it.
309 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
310 while (Ctx && Ctx->isFunctionOrMethod())
311 Ctx = Ctx->getParent();
312 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
313 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000314 DeclContext::lookup_const_iterator I, E;
315 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000316 // FIXME: Cache this result in the IdResolver
Douglas Gregore267ff32008-12-11 20:41:00 +0000317 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000318 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor44b43212008-12-11 16:49:14 +0000319 }
320
321 Ctx = Ctx->getParent();
322 }
323
324 if (!LookInParent)
325 return 0;
326 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000327 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000328
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 // If we didn't find a use of this identifier, and if the identifier
330 // corresponds to a compiler builtin, create the decl object for the builtin
331 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000332 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000333 IdentifierInfo *II = Name.getAsIdentifierInfo();
334 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000335 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000336 // If this is a builtin on this (or all) targets, create the decl.
337 if (unsigned BuiltinID = II->getBuiltinID())
338 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
339 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000340 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000341 // @interface and @compatibility_alias introduce typedef-like names.
342 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000343 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000344 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000345 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
346 if (IDI != ObjCInterfaceDecls.end())
347 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000348 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
349 if (I != ObjCAliasDecls.end())
350 return I->second->getClassInterface();
351 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 }
353 return 0;
354}
355
Chris Lattner95e2c712008-05-05 22:18:14 +0000356void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000357 if (!Context.getBuiltinVaListType().isNull())
358 return;
359
360 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000361 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000362 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000363 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
364}
365
Reid Spencer5f016e22007-07-11 17:01:13 +0000366/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
367/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000368ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
369 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 Builtin::ID BID = (Builtin::ID)bid;
371
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000372 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000373 InitBuiltinVaListType();
374
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000375 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000376 FunctionDecl *New = FunctionDecl::Create(Context,
377 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000378 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000379 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380
Chris Lattner95e2c712008-05-05 22:18:14 +0000381 // Create Decl objects for each parameter, adding them to the
382 // FunctionDecl.
383 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
384 llvm::SmallVector<ParmVarDecl*, 16> Params;
385 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
386 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
387 FT->getArgType(i), VarDecl::None, 0,
388 0));
389 New->setParams(&Params[0], Params.size());
390 }
391
392
393
Chris Lattner7f925cc2008-04-11 07:00:53 +0000394 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000395 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 return New;
397}
398
Sebastian Redlc42e1182008-11-11 11:37:55 +0000399/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
400/// everything from the standard library is defined.
401NamespaceDecl *Sema::GetStdNamespace() {
402 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000403 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000404 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000405 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000406 0, Global, /*enableLazyBuiltinCreation=*/false);
407 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
408 }
409 return StdNamespace;
410}
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
413/// and scope as a previous declaration 'Old'. Figure out how to resolve this
414/// situation, merging decls or emitting diagnostics as appropriate.
415///
Steve Naroffe8043c32008-04-01 23:04:06 +0000416TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000417 // Allow multiple definitions for ObjC built-in typedefs.
418 // FIXME: Verify the underlying types are equivalent!
419 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000420 const IdentifierInfo *TypeID = New->getIdentifier();
421 switch (TypeID->getLength()) {
422 default: break;
423 case 2:
424 if (!TypeID->isStr("id"))
425 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000426 Context.setObjCIdType(New);
427 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000428 case 5:
429 if (!TypeID->isStr("Class"))
430 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000431 Context.setObjCClassType(New);
432 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000433 case 3:
434 if (!TypeID->isStr("SEL"))
435 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000436 Context.setObjCSelType(New);
437 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000438 case 8:
439 if (!TypeID->isStr("Protocol"))
440 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000441 Context.setObjCProtoType(New->getUnderlyingType());
442 return New;
443 }
444 // Fall through - the typedef name was not a builtin type.
445 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 // Verify the old decl was also a typedef.
447 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
448 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000449 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000450 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000451 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 return New;
453 }
454
Chris Lattner99cb9972008-07-25 18:44:27 +0000455 // If the typedef types are not identical, reject them in all languages and
456 // with any extensions enabled.
457 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
458 Context.getCanonicalType(Old->getUnderlyingType()) !=
459 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000460 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000461 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000462 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000463 return Old;
464 }
465
Eli Friedman54ecfce2008-06-11 06:20:39 +0000466 if (getLangOptions().Microsoft) return New;
467
Douglas Gregorbbe27432008-11-21 16:29:06 +0000468 // C++ [dcl.typedef]p2:
469 // In a given non-class scope, a typedef specifier can be used to
470 // redefine the name of any type declared in that scope to refer
471 // to the type to which it already refers.
472 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
473 return New;
474
475 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000476 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
477 // *either* declaration is in a system header. The code below implements
478 // this adhoc compatibility rule. FIXME: The following code will not
479 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000480 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
481 SourceManager &SrcMgr = Context.getSourceManager();
482 if (SrcMgr.isInSystemHeader(Old->getLocation()))
483 return New;
484 if (SrcMgr.isInSystemHeader(New->getLocation()))
485 return New;
486 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000487
Chris Lattner08631c52008-11-23 21:45:46 +0000488 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000489 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 return New;
491}
492
Chris Lattner6b6b5372008-06-26 18:38:35 +0000493/// DeclhasAttr - returns true if decl Declaration already has the target
494/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000495static bool DeclHasAttr(const Decl *decl, const Attr *target) {
496 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
497 if (attr->getKind() == target->getKind())
498 return true;
499
500 return false;
501}
502
503/// MergeAttributes - append attributes from the Old decl to the New one.
504static void MergeAttributes(Decl *New, Decl *Old) {
505 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
506
Chris Lattnerddee4232008-03-03 03:28:21 +0000507 while (attr) {
508 tmp = attr;
509 attr = attr->getNext();
510
511 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000512 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000513 New->addAttr(tmp);
514 } else {
515 tmp->setNext(0);
516 delete(tmp);
517 }
518 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000519
520 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000521}
522
Chris Lattner04421082008-04-08 04:40:51 +0000523/// MergeFunctionDecl - We just parsed a function 'New' from
524/// declarator D which has the same name and scope as a previous
525/// declaration 'Old'. Figure out how to resolve this situation,
526/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527/// Redeclaration will be set true if this New is a redeclaration OldD.
528///
529/// In C++, New and Old must be declarations that are not
530/// overloaded. Use IsOverload to determine whether New and Old are
531/// overloaded, and to select the Old declaration that New should be
532/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000533FunctionDecl *
534Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535 assert(!isa<OverloadedFunctionDecl>(OldD) &&
536 "Cannot merge with an overloaded function declaration");
537
Douglas Gregorf0097952008-04-21 02:02:58 +0000538 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 // Verify the old decl was also a function.
540 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
541 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000542 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000543 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000544 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 return New;
546 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547
548 // Determine whether the previous declaration was a definition,
549 // implicit declaration, or a declaration.
550 diag::kind PrevDiag;
551 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000552 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000554 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000556 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000557
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000558 QualType OldQType = Context.getCanonicalType(Old->getType());
559 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000560
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 if (getLangOptions().CPlusPlus) {
562 // (C++98 13.1p2):
563 // Certain function declarations cannot be overloaded:
564 // -- Function declarations that differ only in the return type
565 // cannot be overloaded.
566 QualType OldReturnType
567 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
568 QualType NewReturnType
569 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
570 if (OldReturnType != NewReturnType) {
571 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
572 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000573 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 return New;
575 }
576
577 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
578 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
579 if (OldMethod && NewMethod) {
580 // -- Member function declarations with the same name and the
581 // same parameter types cannot be overloaded if any of them
582 // is a static member function declaration.
583 if (OldMethod->isStatic() || NewMethod->isStatic()) {
584 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
585 Diag(Old->getLocation(), PrevDiag);
586 return New;
587 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000588
589 // C++ [class.mem]p1:
590 // [...] A member shall not be declared twice in the
591 // member-specification, except that a nested class or member
592 // class template can be declared and then later defined.
593 if (OldMethod->getLexicalDeclContext() ==
594 NewMethod->getLexicalDeclContext()) {
595 unsigned NewDiag;
596 if (isa<CXXConstructorDecl>(OldMethod))
597 NewDiag = diag::err_constructor_redeclared;
598 else if (isa<CXXDestructorDecl>(NewMethod))
599 NewDiag = diag::err_destructor_redeclared;
600 else if (isa<CXXConversionDecl>(NewMethod))
601 NewDiag = diag::err_conv_function_redeclared;
602 else
603 NewDiag = diag::err_member_redeclared;
604
605 Diag(New->getLocation(), NewDiag);
606 Diag(Old->getLocation(), PrevDiag);
607 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608 }
609
610 // (C++98 8.3.5p3):
611 // All declarations for a function shall agree exactly in both the
612 // return type and the parameter-type-list.
613 if (OldQType == NewQType) {
614 // We have a redeclaration.
615 MergeAttributes(New, Old);
616 Redeclaration = true;
617 return MergeCXXFunctionDecl(New, Old);
618 }
619
620 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000621 }
Chris Lattner04421082008-04-08 04:40:51 +0000622
623 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000624 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000625 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000626 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000627 MergeAttributes(New, Old);
628 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000629 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000630 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000631
Steve Naroff837618c2008-01-16 15:01:34 +0000632 // A function that has already been declared has been redeclared or defined
633 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000634
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
636 // TODO: This is totally simplistic. It should handle merging functions
637 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000638 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000639 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 return New;
641}
642
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000643/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000644static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000645 if (VD->isFileVarDecl())
646 return (!VD->getInit() &&
647 (VD->getStorageClass() == VarDecl::None ||
648 VD->getStorageClass() == VarDecl::Static));
649 return false;
650}
651
652/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
653/// when dealing with C "tentative" external object definitions (C99 6.9.2).
654void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
655 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000656 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000657
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000658 // FIXME: I don't this will actually see all of the
659 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000660 for (IdentifierResolver::iterator
661 I = IdResolver.begin(VD->getIdentifier(),
662 VD->getDeclContext(), false/*LookInParentCtx*/),
663 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000664 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000665 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
666
Steve Narofff855e6f2008-08-10 15:20:13 +0000667 // Handle the following case:
668 // int a[10];
669 // int a[]; - the code below makes sure we set the correct type.
670 // int a[11]; - this is an error, size isn't 10.
671 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
672 OldDecl->getType()->isConstantArrayType())
673 VD->setType(OldDecl->getType());
674
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000675 // Check for "tentative" definitions. We can't accomplish this in
676 // MergeVarDecl since the initializer hasn't been attached.
677 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
678 continue;
679
680 // Handle __private_extern__ just like extern.
681 if (OldDecl->getStorageClass() != VarDecl::Extern &&
682 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
683 VD->getStorageClass() != VarDecl::Extern &&
684 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000685 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000686 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000687 }
688 }
689 }
690}
691
Reid Spencer5f016e22007-07-11 17:01:13 +0000692/// MergeVarDecl - We just parsed a variable 'New' which has the same name
693/// and scope as a previous declaration 'Old'. Figure out how to resolve this
694/// situation, merging decls or emitting diagnostics as appropriate.
695///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000696/// Tentative definition rules (C99 6.9.2p2) are checked by
697/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
698/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000699///
Steve Naroffe8043c32008-04-01 23:04:06 +0000700VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 // Verify the old decl was also a variable.
702 VarDecl *Old = dyn_cast<VarDecl>(OldD);
703 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000704 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000705 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000706 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 return New;
708 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000709
710 MergeAttributes(New, Old);
711
Reid Spencer5f016e22007-07-11 17:01:13 +0000712 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000713 QualType OldCType = Context.getCanonicalType(Old->getType());
714 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000715 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000716 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000717 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 return New;
719 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000720 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
721 if (New->getStorageClass() == VarDecl::Static &&
722 (Old->getStorageClass() == VarDecl::None ||
723 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000724 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000725 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000726 return New;
727 }
728 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
729 if (New->getStorageClass() != VarDecl::Static &&
730 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000731 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000732 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000733 return New;
734 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000735 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
736 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000737 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000738 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 }
740 return New;
741}
742
Chris Lattner04421082008-04-08 04:40:51 +0000743/// CheckParmsForFunctionDef - Check that the parameters of the given
744/// function are appropriate for the definition of a function. This
745/// takes care of any checks that cannot be performed on the
746/// declaration itself, e.g., that the types of each of the function
747/// parameters are complete.
748bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
749 bool HasInvalidParm = false;
750 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
751 ParmVarDecl *Param = FD->getParamDecl(p);
752
753 // C99 6.7.5.3p4: the parameters in a parameter type list in a
754 // function declarator that is part of a function definition of
755 // that function shall not have incomplete type.
756 if (Param->getType()->isIncompleteType() &&
757 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000758 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000759 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000760 Param->setInvalidDecl();
761 HasInvalidParm = true;
762 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000763
764 // C99 6.9.1p5: If the declarator includes a parameter type list, the
765 // declaration of each parameter shall include an identifier.
766 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
767 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000768 }
769
770 return HasInvalidParm;
771}
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
774/// no declarator (e.g. "struct foo;") is parsed.
775Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000776 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
777 if (!DS.isMissingDeclaratorOk()) {
778 // FIXME: This diagnostic is emitted even when various previous
779 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
780 // DeclSpec has no means of communicating this information, and the
781 // responsible parser functions are quite far apart.
782 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
783 << DS.getSourceRange();
784 return 0;
785 }
786
Steve Naroff92199282007-11-17 21:37:36 +0000787 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000788}
789
Steve Naroffd0091aa2008-01-10 22:15:12 +0000790bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000791 // Get the type before calling CheckSingleAssignmentConstraints(), since
792 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000793 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000794
795 if (getLangOptions().CPlusPlus)
796 return PerformCopyInitialization(Init, DeclType, "initializing");
797
Chris Lattner5cf216b2008-01-04 18:04:52 +0000798 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
799 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
800 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000801}
802
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000803bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000804 const ArrayType *AT = Context.getAsArrayType(DeclT);
805
806 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000807 // C99 6.7.8p14. We have an array of character type with unknown size
808 // being initialized to a string literal.
809 llvm::APSInt ConstVal(32);
810 ConstVal = strLiteral->getByteLength() + 1;
811 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000812 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000813 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000814 } else {
815 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000816 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000817 // FIXME: Avoid truncation for 64-bit length strings.
818 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000819 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000820 diag::warn_initializer_string_for_char_array_too_long)
821 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000822 }
823 // Set type from "char *" to "constant array of char".
824 strLiteral->setType(DeclT);
825 // For now, we always return false (meaning success).
826 return false;
827}
828
829StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000830 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000831 if (AT && AT->getElementType()->isCharType()) {
832 return dyn_cast<StringLiteral>(Init);
833 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000834 return 0;
835}
836
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000837bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
838 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000839 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000840 if (DeclType->isDependentType() || Init->isTypeDependent())
841 return false;
842
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000843 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000844 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000845 // (8.3.2), shall be initialized by an object, or function, of
846 // type T or by an object that can be converted into a T.
847 if (DeclType->isReferenceType())
848 return CheckReferenceInit(Init, DeclType);
849
Steve Naroffca107302008-01-21 23:53:58 +0000850 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
851 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000852 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000853 return Diag(InitLoc, diag::err_variable_object_no_init)
854 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000855
Steve Naroff2fdc3742007-12-10 22:44:33 +0000856 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
857 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000858 // FIXME: Handle wide strings
859 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
860 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000861
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000862 // C++ [dcl.init]p14:
863 // -- If the destination type is a (possibly cv-qualified) class
864 // type:
865 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
866 QualType DeclTypeC = Context.getCanonicalType(DeclType);
867 QualType InitTypeC = Context.getCanonicalType(Init->getType());
868
869 // -- If the initialization is direct-initialization, or if it is
870 // copy-initialization where the cv-unqualified version of the
871 // source type is the same class as, or a derived class of, the
872 // class of the destination, constructors are considered.
873 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
874 IsDerivedFrom(InitTypeC, DeclTypeC)) {
875 CXXConstructorDecl *Constructor
876 = PerformInitializationByConstructor(DeclType, &Init, 1,
877 InitLoc, Init->getSourceRange(),
878 InitEntity, IK_Copy);
879 return Constructor == 0;
880 }
881
882 // -- Otherwise (i.e., for the remaining copy-initialization
883 // cases), user-defined conversion sequences that can
884 // convert from the source type to the destination type or
885 // (when a conversion function is used) to a derived class
886 // thereof are enumerated as described in 13.3.1.4, and the
887 // best one is chosen through overload resolution
888 // (13.3). If the conversion cannot be done or is
889 // ambiguous, the initialization is ill-formed. The
890 // function selected is called with the initializer
891 // expression as its argument; if the function is a
892 // constructor, the call initializes a temporary of the
893 // destination type.
894 // FIXME: We're pretending to do copy elision here; return to
895 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000896 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000897 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000898
Douglas Gregor61366e92008-12-24 00:01:03 +0000899 if (InitEntity)
900 return Diag(InitLoc, diag::err_cannot_initialize_decl)
901 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
902 << Init->getType() << Init->getSourceRange();
903 else
904 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
905 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
906 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000907 }
908
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000909 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000910 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000911 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
912 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000913
Steve Naroffd0091aa2008-01-10 22:15:12 +0000914 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000915 } else if (getLangOptions().CPlusPlus) {
916 // C++ [dcl.init]p14:
917 // [...] If the class is an aggregate (8.5.1), and the initializer
918 // is a brace-enclosed list, see 8.5.1.
919 //
920 // Note: 8.5.1 is handled below; here, we diagnose the case where
921 // we have an initializer list and a destination type that is not
922 // an aggregate.
923 // FIXME: In C++0x, this is yet another form of initialization.
924 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
925 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
926 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000927 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000928 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000929 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000930 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000931
Steve Naroff0cca7492008-05-01 22:18:59 +0000932 InitListChecker CheckInitList(this, InitList, DeclType);
933 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000934}
935
Douglas Gregor10bd3682008-11-17 22:58:34 +0000936/// GetNameForDeclarator - Determine the full declaration name for the
937/// given Declarator.
938DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
939 switch (D.getKind()) {
940 case Declarator::DK_Abstract:
941 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
942 return DeclarationName();
943
944 case Declarator::DK_Normal:
945 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
946 return DeclarationName(D.getIdentifier());
947
948 case Declarator::DK_Constructor: {
949 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
950 Ty = Context.getCanonicalType(Ty);
951 return Context.DeclarationNames.getCXXConstructorName(Ty);
952 }
953
954 case Declarator::DK_Destructor: {
955 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
956 Ty = Context.getCanonicalType(Ty);
957 return Context.DeclarationNames.getCXXDestructorName(Ty);
958 }
959
960 case Declarator::DK_Conversion: {
961 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
962 Ty = Context.getCanonicalType(Ty);
963 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
964 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000965
966 case Declarator::DK_Operator:
967 assert(D.getIdentifier() == 0 && "operator names have no identifier");
968 return Context.DeclarationNames.getCXXOperatorName(
969 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000970 }
971
972 assert(false && "Unknown name kind");
973 return DeclarationName();
974}
975
Douglas Gregor584049d2008-12-15 23:53:10 +0000976/// isNearlyMatchingMemberFunction - Determine whether the C++ member
977/// functions Declaration and Definition are "nearly" matching. This
978/// heuristic is used to improve diagnostics in the case where an
979/// out-of-line member function definition doesn't match any
980/// declaration within the class.
981static bool isNearlyMatchingMemberFunction(ASTContext &Context,
982 FunctionDecl *Declaration,
983 FunctionDecl *Definition) {
984 if (Declaration->param_size() != Definition->param_size())
985 return false;
986 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
987 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
988 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
989
990 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
991 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
992 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
993 return false;
994 }
995
996 return true;
997}
998
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000999Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001000Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1001 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001002 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001003 DeclarationName Name = GetNameForDeclarator(D);
1004
Chris Lattnere80a59c2007-07-25 00:24:17 +00001005 // All of these full declarators require an identifier. If it doesn't have
1006 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001007 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001008 if (!D.getInvalidType()) // Reject this if we think it is valid.
1009 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001010 diag::err_declarator_need_ident)
1011 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001012 return 0;
1013 }
1014
Chris Lattner31e05722007-08-26 06:24:45 +00001015 // The scope passed in may not be a decl scope. Zip up the scope tree until
1016 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001017 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1018 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001019 S = S->getParent();
1020
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001021 DeclContext *DC;
1022 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001023 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001024 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001025
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001026 // See if this is a redefinition of a variable in the same scope.
1027 if (!D.getCXXScopeSpec().isSet()) {
1028 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001029 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001030 } else { // Something like "int foo::x;"
1031 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001032 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001033
1034 // C++ 7.3.1.2p2:
1035 // Members (including explicit specializations of templates) of a named
1036 // namespace can also be defined outside that namespace by explicit
1037 // qualification of the name being defined, provided that the entity being
1038 // defined was already declared in the namespace and the definition appears
1039 // after the point of declaration in a namespace that encloses the
1040 // declarations namespace.
1041 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001042 // Note that we only check the context at this point. We don't yet
1043 // have enough information to make sure that PrevDecl is actually
1044 // the declaration we want to match. For example, given:
1045 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001046 // class X {
1047 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001048 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001049 // };
1050 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001051 // void X::f(int) { } // ill-formed
1052 //
1053 // In this case, PrevDecl will point to the overload set
1054 // containing the two f's declared in X, but neither of them
1055 // matches.
1056 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001057 // The qualifying scope doesn't enclose the original declaration.
1058 // Emit diagnostic based on current scope.
1059 SourceLocation L = D.getIdentifierLoc();
1060 SourceRange R = D.getCXXScopeSpec().getRange();
1061 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001062 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001063 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001064 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001065 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001066 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001067 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001068 }
1069 }
1070
Douglas Gregorf57172b2008-12-08 18:40:42 +00001071 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001072 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001073 InvalidDecl = InvalidDecl
1074 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001075 // Just pretend that we didn't see the previous declaration.
1076 PrevDecl = 0;
1077 }
1078
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001079 // In C++, the previous declaration we find might be a tag type
1080 // (class or enum). In this case, the new declaration will hide the
1081 // tag type.
1082 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1083 PrevDecl = 0;
1084
Chris Lattner41af0932007-11-14 06:34:38 +00001085 QualType R = GetTypeForDeclarator(D, S);
1086 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1087
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001089 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1090 if (D.getCXXScopeSpec().isSet()) {
1091 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1092 << D.getCXXScopeSpec().getRange();
1093 InvalidDecl = true;
1094 // Pretend we didn't see the scope specifier.
1095 DC = 0;
1096 }
1097
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001098 // Check that there are no default arguments (C++ only).
1099 if (getLangOptions().CPlusPlus)
1100 CheckExtraCXXDefaultArguments(D);
1101
Chris Lattner41af0932007-11-14 06:34:38 +00001102 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001103 if (!NewTD) return 0;
1104
1105 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001106 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001107 // Merge the decl with the existing one if appropriate. If the decl is
1108 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001109 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1111 if (NewTD == 0) return 0;
1112 }
1113 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001114 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1116 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001117 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001118 if (NewTD->getUnderlyingType()->isVariableArrayType())
1119 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1120 else
1121 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1122
Steve Naroffd7444aa2007-08-31 17:20:07 +00001123 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001124 }
1125 }
Chris Lattner41af0932007-11-14 06:34:38 +00001126 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001127 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001128 switch (D.getDeclSpec().getStorageClassSpec()) {
1129 default: assert(0 && "Unknown storage class!");
1130 case DeclSpec::SCS_auto:
1131 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001132 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001133 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001134 InvalidDecl = true;
1135 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1137 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1138 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001139 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 }
1141
Chris Lattnera98e58d2008-03-15 21:24:04 +00001142 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001143 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001144 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1145
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001146 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001147 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001148 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001149 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001150 "Constructors can only be declared in a member context");
1151
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001152 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001153
1154 // Create the new declaration
1155 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001156 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001157 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001158 isExplicit, isInline,
1159 /*isImplicitlyDeclared=*/false);
1160
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001161 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001162 NewFD->setInvalidDecl();
1163 } else if (D.getKind() == Declarator::DK_Destructor) {
1164 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001165 if (DC->isCXXRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001166 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001167
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001168 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001169 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001170 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001171 isInline,
1172 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001173
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001174 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001175 NewFD->setInvalidDecl();
1176 } else {
1177 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001178
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001179 // Create a FunctionDecl to satisfy the function definition parsing
1180 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001181 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001182 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001183 // FIXME: Move to DeclGroup...
1184 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001185 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001186 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001187 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001188 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001190 Diag(D.getIdentifierLoc(),
1191 diag::err_conv_function_not_member);
1192 return 0;
1193 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001194 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001195
Douglas Gregor70316a02008-12-26 15:00:45 +00001196 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001197 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001198 isInline, isExplicit);
1199
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001200 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001201 NewFD->setInvalidDecl();
1202 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001203 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001204 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001205 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001206 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001207 (SC == FunctionDecl::Static), isInline,
1208 LastDeclarator);
1209 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001210 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001211 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001212 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001213 // FIXME: Move to DeclGroup...
1214 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001215 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001216
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001217 // Set the lexical context. If the declarator has a C++
1218 // scope specifier, the lexical context will be different
1219 // from the semantic context.
1220 NewFD->setLexicalDeclContext(CurContext);
1221
Daniel Dunbara80f8742008-08-05 01:35:17 +00001222 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001223 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001224 // The parser guarantees this is a string.
1225 StringLiteral *SE = cast<StringLiteral>(E);
1226 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1227 SE->getByteLength())));
1228 }
1229
Chris Lattner04421082008-04-08 04:40:51 +00001230 // Copy the parameter declarations from the declarator D to
1231 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001232 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001233 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1234
1235 // Create Decl objects for each parameter, adding them to the
1236 // FunctionDecl.
1237 llvm::SmallVector<ParmVarDecl*, 16> Params;
1238
1239 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1240 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001241 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001242 // We let through "const void" here because Sema::GetTypeForDeclarator
1243 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001244 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1245 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001246 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1247 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001248 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1249
Chris Lattnerdef026a2008-04-10 02:26:16 +00001250 // In C++, the empty parameter-type-list must be spelled "void"; a
1251 // typedef of void is not permitted.
1252 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001253 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001254 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1255 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001256 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001257 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1258 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1259 }
1260
1261 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001262 } else if (R->getAsTypedefType()) {
1263 // When we're declaring a function with a typedef, as in the
1264 // following example, we'll need to synthesize (unnamed)
1265 // parameters for use in the declaration.
1266 //
1267 // @code
1268 // typedef void fn(int);
1269 // fn f;
1270 // @endcode
1271 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1272 if (!FT) {
1273 // This is a typedef of a function with no prototype, so we
1274 // don't need to do anything.
1275 } else if ((FT->getNumArgs() == 0) ||
1276 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1277 FT->getArgType(0)->isVoidType())) {
1278 // This is a zero-argument function. We don't need to do anything.
1279 } else {
1280 // Synthesize a parameter for each argument type.
1281 llvm::SmallVector<ParmVarDecl*, 16> Params;
1282 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1283 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001284 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001285 SourceLocation(), 0,
1286 *ArgType, VarDecl::None,
1287 0, 0));
1288 }
1289
1290 NewFD->setParams(&Params[0], Params.size());
1291 }
Chris Lattner04421082008-04-08 04:40:51 +00001292 }
1293
Douglas Gregor72b505b2008-12-16 21:30:33 +00001294 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1295 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001296 else if (isa<CXXDestructorDecl>(NewFD))
1297 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1298 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001299 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001300
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001301 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1302 if (NewFD->isOverloadedOperator() &&
1303 CheckOverloadedOperatorDeclaration(NewFD))
1304 NewFD->setInvalidDecl();
1305
Steve Naroffffce4d52008-01-09 23:34:55 +00001306 // Merge the decl with the existing one if appropriate. Since C functions
1307 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001308 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001309 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001310 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001311
1312 // If C++, determine whether NewFD is an overload of PrevDecl or
1313 // a declaration that requires merging. If it's an overload,
1314 // there's no more work to do here; we'll just add the new
1315 // function to the scope.
1316 OverloadedFunctionDecl::function_iterator MatchedDecl;
1317 if (!getLangOptions().CPlusPlus ||
1318 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1319 Decl *OldDecl = PrevDecl;
1320
1321 // If PrevDecl was an overloaded function, extract the
1322 // FunctionDecl that matched.
1323 if (isa<OverloadedFunctionDecl>(PrevDecl))
1324 OldDecl = *MatchedDecl;
1325
1326 // NewFD and PrevDecl represent declarations that need to be
1327 // merged.
1328 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1329
1330 if (NewFD == 0) return 0;
1331 if (Redeclaration) {
1332 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1333
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001334 // An out-of-line member function declaration must also be a
1335 // definition (C++ [dcl.meaning]p1).
1336 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1337 !InvalidDecl) {
1338 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1339 << D.getCXXScopeSpec().getRange();
1340 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001341 }
1342 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001343 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001344
1345 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1346 // The user tried to provide an out-of-line definition for a
1347 // member function, but there was no such member function
1348 // declared (C++ [class.mfct]p2). For example:
1349 //
1350 // class X {
1351 // void f() const;
1352 // };
1353 //
1354 // void X::f() { } // ill-formed
1355 //
1356 // Complain about this problem, and attempt to suggest close
1357 // matches (e.g., those that differ only in cv-qualifiers and
1358 // whether the parameter types are references).
1359 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1360 << cast<CXXRecordDecl>(DC)->getDeclName()
1361 << D.getCXXScopeSpec().getRange();
1362 InvalidDecl = true;
1363
1364 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1365 if (!PrevDecl) {
1366 // Nothing to suggest.
1367 } else if (OverloadedFunctionDecl *Ovl
1368 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1369 for (OverloadedFunctionDecl::function_iterator
1370 Func = Ovl->function_begin(),
1371 FuncEnd = Ovl->function_end();
1372 Func != FuncEnd; ++Func) {
1373 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1374 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1375
1376 }
1377 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1378 // Suggest this no matter how mismatched it is; it's the only
1379 // thing we have.
1380 unsigned diag;
1381 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1382 diag = diag::note_member_def_close_match;
1383 else if (Method->getBody())
1384 diag = diag::note_previous_definition;
1385 else
1386 diag = diag::note_previous_declaration;
1387 Diag(Method->getLocation(), diag);
1388 }
1389
1390 PrevDecl = 0;
1391 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001393 // Handle attributes. We need to have merged decls when handling attributes
1394 // (for example to check for conflicts, etc).
1395 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001397
Douglas Gregor584049d2008-12-15 23:53:10 +00001398 if (getLangOptions().CPlusPlus) {
1399 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001400 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001401
1402 // An out-of-line member function declaration must also be a
1403 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001404 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001405 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1406 << D.getCXXScopeSpec().getRange();
1407 InvalidDecl = true;
1408 }
1409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001411 // Check that there are no default arguments (C++ only).
1412 if (getLangOptions().CPlusPlus)
1413 CheckExtraCXXDefaultArguments(D);
1414
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001415 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001416 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1417 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001418 InvalidDecl = true;
1419 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001420
1421 VarDecl *NewVD;
1422 VarDecl::StorageClass SC;
1423 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001424 default: assert(0 && "Unknown storage class!");
1425 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1426 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1427 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1428 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1429 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1430 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001431 case DeclSpec::SCS_mutable:
1432 // mutable can only appear on non-static class members, so it's always
1433 // an error here
1434 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1435 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001436 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001437 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001438 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001439
1440 IdentifierInfo *II = Name.getAsIdentifierInfo();
1441 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001442 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1443 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001444 return 0;
1445 }
1446
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001447 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001448 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001449 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001450 D.getIdentifierLoc(), II,
1451 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001452 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001453 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454 if (S->getFnParent() == 0) {
1455 // C99 6.9p2: The storage-class specifiers auto and register shall not
1456 // appear in the declaration specifiers in an external declaration.
1457 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001458 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459 InvalidDecl = true;
1460 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001462 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1463 II, R, SC, LastDeclarator,
1464 // FIXME: Move to DeclGroup...
1465 D.getDeclSpec().getSourceRange().getBegin());
1466 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001467 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001469 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001470
Daniel Dunbara735ad82008-08-06 00:03:29 +00001471 // Handle GNU asm-label extension (encoded as an attribute).
1472 if (Expr *E = (Expr*) D.getAsmLabel()) {
1473 // The parser guarantees this is a string.
1474 StringLiteral *SE = cast<StringLiteral>(E);
1475 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1476 SE->getByteLength())));
1477 }
1478
Nate Begemanc8e89a82008-03-14 18:07:10 +00001479 // Emit an error if an address space was applied to decl with local storage.
1480 // This includes arrays of objects with address space qualifiers, but not
1481 // automatic variables that point to other address spaces.
1482 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001483 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1484 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1485 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001486 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001487 // Merge the decl with the existing one if appropriate. If the decl is
1488 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001489 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001490 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1491 // The user tried to define a non-static data member
1492 // out-of-line (C++ [dcl.meaning]p1).
1493 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1494 << D.getCXXScopeSpec().getRange();
1495 NewVD->Destroy(Context);
1496 return 0;
1497 }
1498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 NewVD = MergeVarDecl(NewVD, PrevDecl);
1500 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001501
1502 if (D.getCXXScopeSpec().isSet()) {
1503 // No previous declaration in the qualifying scope.
1504 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1505 << Name << D.getCXXScopeSpec().getRange();
1506 InvalidDecl = true;
1507 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 New = NewVD;
1510 }
1511
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001512 // Set the lexical context. If the declarator has a C++ scope specifier, the
1513 // lexical context will be different from the semantic context.
1514 New->setLexicalDeclContext(CurContext);
1515
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001517 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001518 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001519 // If any semantic error occurred, mark the decl as invalid.
1520 if (D.getInvalidType() || InvalidDecl)
1521 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001522
1523 return New;
1524}
1525
Steve Naroff6594a702008-10-27 11:34:16 +00001526void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001527 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1528 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001529}
1530
Eli Friedmanc594b322008-05-20 13:48:25 +00001531bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1532 switch (Init->getStmtClass()) {
1533 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001534 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001535 return true;
1536 case Expr::ParenExprClass: {
1537 const ParenExpr* PE = cast<ParenExpr>(Init);
1538 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1539 }
1540 case Expr::CompoundLiteralExprClass:
1541 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1542 case Expr::DeclRefExprClass: {
1543 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001544 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1545 if (VD->hasGlobalStorage())
1546 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001547 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001548 return true;
1549 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001550 if (isa<FunctionDecl>(D))
1551 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001552 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001553 return true;
1554 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001555 case Expr::MemberExprClass: {
1556 const MemberExpr *M = cast<MemberExpr>(Init);
1557 if (M->isArrow())
1558 return CheckAddressConstantExpression(M->getBase());
1559 return CheckAddressConstantExpressionLValue(M->getBase());
1560 }
1561 case Expr::ArraySubscriptExprClass: {
1562 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1563 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1564 return CheckAddressConstantExpression(ASE->getBase()) ||
1565 CheckArithmeticConstantExpression(ASE->getIdx());
1566 }
1567 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001568 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001569 return false;
1570 case Expr::UnaryOperatorClass: {
1571 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1572
1573 // C99 6.6p9
1574 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001575 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001576
Steve Naroff6594a702008-10-27 11:34:16 +00001577 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001578 return true;
1579 }
1580 }
1581}
1582
1583bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1584 switch (Init->getStmtClass()) {
1585 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001586 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001587 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001588 case Expr::ParenExprClass:
1589 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001590 case Expr::StringLiteralClass:
1591 case Expr::ObjCStringLiteralClass:
1592 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001593 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001594 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001595 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1596 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1597 Builtin::BI__builtin___CFStringMakeConstantString)
1598 return false;
1599
Steve Naroff6594a702008-10-27 11:34:16 +00001600 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001601 return true;
1602
Eli Friedmanc594b322008-05-20 13:48:25 +00001603 case Expr::UnaryOperatorClass: {
1604 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1605
1606 // C99 6.6p9
1607 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1608 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1609
1610 if (Exp->getOpcode() == UnaryOperator::Extension)
1611 return CheckAddressConstantExpression(Exp->getSubExpr());
1612
Steve Naroff6594a702008-10-27 11:34:16 +00001613 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001614 return true;
1615 }
1616 case Expr::BinaryOperatorClass: {
1617 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1618 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1619
1620 Expr *PExp = Exp->getLHS();
1621 Expr *IExp = Exp->getRHS();
1622 if (IExp->getType()->isPointerType())
1623 std::swap(PExp, IExp);
1624
1625 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1626 return CheckAddressConstantExpression(PExp) ||
1627 CheckArithmeticConstantExpression(IExp);
1628 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001629 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001630 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001631 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001632 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1633 // Check for implicit promotion
1634 if (SubExpr->getType()->isFunctionType() ||
1635 SubExpr->getType()->isArrayType())
1636 return CheckAddressConstantExpressionLValue(SubExpr);
1637 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001638
1639 // Check for pointer->pointer cast
1640 if (SubExpr->getType()->isPointerType())
1641 return CheckAddressConstantExpression(SubExpr);
1642
Eli Friedmanc3f07642008-08-25 20:46:57 +00001643 if (SubExpr->getType()->isIntegralType()) {
1644 // Check for the special-case of a pointer->int->pointer cast;
1645 // this isn't standard, but some code requires it. See
1646 // PR2720 for an example.
1647 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1648 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1649 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1650 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1651 if (IntWidth >= PointerWidth) {
1652 return CheckAddressConstantExpression(SubCast->getSubExpr());
1653 }
1654 }
1655 }
1656 }
1657 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001658 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001659 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001660
Steve Naroff6594a702008-10-27 11:34:16 +00001661 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001662 return true;
1663 }
1664 case Expr::ConditionalOperatorClass: {
1665 // FIXME: Should we pedwarn here?
1666 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1667 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001668 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001669 return true;
1670 }
1671 if (CheckArithmeticConstantExpression(Exp->getCond()))
1672 return true;
1673 if (Exp->getLHS() &&
1674 CheckAddressConstantExpression(Exp->getLHS()))
1675 return true;
1676 return CheckAddressConstantExpression(Exp->getRHS());
1677 }
1678 case Expr::AddrLabelExprClass:
1679 return false;
1680 }
1681}
1682
Eli Friedman4caf0552008-06-09 05:05:07 +00001683static const Expr* FindExpressionBaseAddress(const Expr* E);
1684
1685static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1686 switch (E->getStmtClass()) {
1687 default:
1688 return E;
1689 case Expr::ParenExprClass: {
1690 const ParenExpr* PE = cast<ParenExpr>(E);
1691 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1692 }
1693 case Expr::MemberExprClass: {
1694 const MemberExpr *M = cast<MemberExpr>(E);
1695 if (M->isArrow())
1696 return FindExpressionBaseAddress(M->getBase());
1697 return FindExpressionBaseAddressLValue(M->getBase());
1698 }
1699 case Expr::ArraySubscriptExprClass: {
1700 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1701 return FindExpressionBaseAddress(ASE->getBase());
1702 }
1703 case Expr::UnaryOperatorClass: {
1704 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1705
1706 if (Exp->getOpcode() == UnaryOperator::Deref)
1707 return FindExpressionBaseAddress(Exp->getSubExpr());
1708
1709 return E;
1710 }
1711 }
1712}
1713
1714static const Expr* FindExpressionBaseAddress(const Expr* E) {
1715 switch (E->getStmtClass()) {
1716 default:
1717 return E;
1718 case Expr::ParenExprClass: {
1719 const ParenExpr* PE = cast<ParenExpr>(E);
1720 return FindExpressionBaseAddress(PE->getSubExpr());
1721 }
1722 case Expr::UnaryOperatorClass: {
1723 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1724
1725 // C99 6.6p9
1726 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1727 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1728
1729 if (Exp->getOpcode() == UnaryOperator::Extension)
1730 return FindExpressionBaseAddress(Exp->getSubExpr());
1731
1732 return E;
1733 }
1734 case Expr::BinaryOperatorClass: {
1735 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1736
1737 Expr *PExp = Exp->getLHS();
1738 Expr *IExp = Exp->getRHS();
1739 if (IExp->getType()->isPointerType())
1740 std::swap(PExp, IExp);
1741
1742 return FindExpressionBaseAddress(PExp);
1743 }
1744 case Expr::ImplicitCastExprClass: {
1745 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1746
1747 // Check for implicit promotion
1748 if (SubExpr->getType()->isFunctionType() ||
1749 SubExpr->getType()->isArrayType())
1750 return FindExpressionBaseAddressLValue(SubExpr);
1751
1752 // Check for pointer->pointer cast
1753 if (SubExpr->getType()->isPointerType())
1754 return FindExpressionBaseAddress(SubExpr);
1755
1756 // We assume that we have an arithmetic expression here;
1757 // if we don't, we'll figure it out later
1758 return 0;
1759 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001760 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001761 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1762
1763 // Check for pointer->pointer cast
1764 if (SubExpr->getType()->isPointerType())
1765 return FindExpressionBaseAddress(SubExpr);
1766
1767 // We assume that we have an arithmetic expression here;
1768 // if we don't, we'll figure it out later
1769 return 0;
1770 }
1771 }
1772}
1773
Anders Carlsson51fe9962008-11-22 21:04:56 +00001774bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001775 switch (Init->getStmtClass()) {
1776 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001777 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001778 return true;
1779 case Expr::ParenExprClass: {
1780 const ParenExpr* PE = cast<ParenExpr>(Init);
1781 return CheckArithmeticConstantExpression(PE->getSubExpr());
1782 }
1783 case Expr::FloatingLiteralClass:
1784 case Expr::IntegerLiteralClass:
1785 case Expr::CharacterLiteralClass:
1786 case Expr::ImaginaryLiteralClass:
1787 case Expr::TypesCompatibleExprClass:
1788 case Expr::CXXBoolLiteralExprClass:
1789 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001790 case Expr::CallExprClass:
1791 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001792 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001793
1794 // Allow any constant foldable calls to builtins.
1795 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001796 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001797
Steve Naroff6594a702008-10-27 11:34:16 +00001798 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001799 return true;
1800 }
1801 case Expr::DeclRefExprClass: {
1802 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1803 if (isa<EnumConstantDecl>(D))
1804 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001805 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001806 return true;
1807 }
1808 case Expr::CompoundLiteralExprClass:
1809 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1810 // but vectors are allowed to be magic.
1811 if (Init->getType()->isVectorType())
1812 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001813 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001814 return true;
1815 case Expr::UnaryOperatorClass: {
1816 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1817
1818 switch (Exp->getOpcode()) {
1819 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1820 // See C99 6.6p3.
1821 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001822 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001823 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001824 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001825 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1826 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001827 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001828 return true;
1829 case UnaryOperator::Extension:
1830 case UnaryOperator::LNot:
1831 case UnaryOperator::Plus:
1832 case UnaryOperator::Minus:
1833 case UnaryOperator::Not:
1834 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1835 }
1836 }
Sebastian Redl05189992008-11-11 17:56:53 +00001837 case Expr::SizeOfAlignOfExprClass: {
1838 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001839 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001840 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001841 return false;
1842 // alignof always evaluates to a constant.
1843 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001844 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001845 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001846 return true;
1847 }
1848 return false;
1849 }
1850 case Expr::BinaryOperatorClass: {
1851 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1852
1853 if (Exp->getLHS()->getType()->isArithmeticType() &&
1854 Exp->getRHS()->getType()->isArithmeticType()) {
1855 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1856 CheckArithmeticConstantExpression(Exp->getRHS());
1857 }
1858
Eli Friedman4caf0552008-06-09 05:05:07 +00001859 if (Exp->getLHS()->getType()->isPointerType() &&
1860 Exp->getRHS()->getType()->isPointerType()) {
1861 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1862 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1863
1864 // Only allow a null (constant integer) base; we could
1865 // allow some additional cases if necessary, but this
1866 // is sufficient to cover offsetof-like constructs.
1867 if (!LHSBase && !RHSBase) {
1868 return CheckAddressConstantExpression(Exp->getLHS()) ||
1869 CheckAddressConstantExpression(Exp->getRHS());
1870 }
1871 }
1872
Steve Naroff6594a702008-10-27 11:34:16 +00001873 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001874 return true;
1875 }
1876 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001877 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001878 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001879 if (SubExpr->getType()->isArithmeticType())
1880 return CheckArithmeticConstantExpression(SubExpr);
1881
Eli Friedmanb529d832008-09-02 09:37:00 +00001882 if (SubExpr->getType()->isPointerType()) {
1883 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1884 // If the pointer has a null base, this is an offsetof-like construct
1885 if (!Base)
1886 return CheckAddressConstantExpression(SubExpr);
1887 }
1888
Steve Naroff6594a702008-10-27 11:34:16 +00001889 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001890 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001891 }
1892 case Expr::ConditionalOperatorClass: {
1893 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001894
1895 // If GNU extensions are disabled, we require all operands to be arithmetic
1896 // constant expressions.
1897 if (getLangOptions().NoExtensions) {
1898 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1899 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1900 CheckArithmeticConstantExpression(Exp->getRHS());
1901 }
1902
1903 // Otherwise, we have to emulate some of the behavior of fold here.
1904 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1905 // because it can constant fold things away. To retain compatibility with
1906 // GCC code, we see if we can fold the condition to a constant (which we
1907 // should always be able to do in theory). If so, we only require the
1908 // specified arm of the conditional to be a constant. This is a horrible
1909 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001910 Expr::EvalResult EvalResult;
1911 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1912 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001913 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001914 // won't be able to either. Use it to emit the diagnostic though.
1915 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001916 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001917 return Res;
1918 }
1919
1920 // Verify that the side following the condition is also a constant.
1921 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001922 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001923 std::swap(TrueSide, FalseSide);
1924
1925 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001926 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001927
1928 // Okay, the evaluated side evaluates to a constant, so we accept this.
1929 // Check to see if the other side is obviously not a constant. If so,
1930 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001931 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001932 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001933 diag::ext_typecheck_expression_not_constant_but_accepted)
1934 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001935 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001936 }
1937 }
1938}
1939
1940bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001941 Expr::EvalResult Result;
1942
Nuno Lopes9a979c32008-07-07 16:46:50 +00001943 Init = Init->IgnoreParens();
1944
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001945 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1946 return false;
1947
Eli Friedmanc594b322008-05-20 13:48:25 +00001948 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1949 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1950 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1951
Nuno Lopes9a979c32008-07-07 16:46:50 +00001952 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1953 return CheckForConstantInitializer(e->getInitializer(), DclT);
1954
Eli Friedmanc594b322008-05-20 13:48:25 +00001955 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1956 unsigned numInits = Exp->getNumInits();
1957 for (unsigned i = 0; i < numInits; i++) {
1958 // FIXME: Need to get the type of the declaration for C++,
1959 // because it could be a reference?
1960 if (CheckForConstantInitializer(Exp->getInit(i),
1961 Exp->getInit(i)->getType()))
1962 return true;
1963 }
1964 return false;
1965 }
1966
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001967 // FIXME: We can probably remove some of this code below, now that
1968 // Expr::Evaluate is doing the heavy lifting for scalars.
1969
Eli Friedmanc594b322008-05-20 13:48:25 +00001970 if (Init->isNullPointerConstant(Context))
1971 return false;
1972 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001973 QualType InitTy = Context.getCanonicalType(Init->getType())
1974 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001975 if (InitTy == Context.BoolTy) {
1976 // Special handling for pointers implicitly cast to bool;
1977 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1978 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1979 Expr* SubE = ICE->getSubExpr();
1980 if (SubE->getType()->isPointerType() ||
1981 SubE->getType()->isArrayType() ||
1982 SubE->getType()->isFunctionType()) {
1983 return CheckAddressConstantExpression(Init);
1984 }
1985 }
1986 } else if (InitTy->isIntegralType()) {
1987 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001988 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001989 SubE = CE->getSubExpr();
1990 // Special check for pointer cast to int; we allow as an extension
1991 // an address constant cast to an integer if the integer
1992 // is of an appropriate width (this sort of code is apparently used
1993 // in some places).
1994 // FIXME: Add pedwarn?
1995 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1996 if (SubE && (SubE->getType()->isPointerType() ||
1997 SubE->getType()->isArrayType() ||
1998 SubE->getType()->isFunctionType())) {
1999 unsigned IntWidth = Context.getTypeSize(Init->getType());
2000 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2001 if (IntWidth >= PointerWidth)
2002 return CheckAddressConstantExpression(Init);
2003 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002004 }
2005
2006 return CheckArithmeticConstantExpression(Init);
2007 }
2008
2009 if (Init->getType()->isPointerType())
2010 return CheckAddressConstantExpression(Init);
2011
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002012 // An array type at the top level that isn't an init-list must
2013 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002014 if (Init->getType()->isArrayType())
2015 return false;
2016
Nuno Lopes73419bf2008-09-01 18:42:41 +00002017 if (Init->getType()->isFunctionType())
2018 return false;
2019
Steve Naroff8af6a452008-10-02 17:12:56 +00002020 // Allow block exprs at top level.
2021 if (Init->getType()->isBlockPointerType())
2022 return false;
2023
Steve Naroff6594a702008-10-27 11:34:16 +00002024 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002025 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002026}
2027
Sebastian Redl798d1192008-12-13 16:23:55 +00002028void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002029 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002030 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002031 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002032
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002033 // If there is no declaration, there was an error parsing it. Just ignore
2034 // the initializer.
2035 if (RealDecl == 0) {
2036 delete Init;
2037 return;
2038 }
Steve Naroffbb204692007-09-12 14:07:44 +00002039
Steve Naroff410e3e22007-09-12 20:13:48 +00002040 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2041 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002042 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2043 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002044 RealDecl->setInvalidDecl();
2045 return;
2046 }
Steve Naroffbb204692007-09-12 14:07:44 +00002047 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002048 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002049 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002050 if (VDecl->isBlockVarDecl()) {
2051 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002052 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002053 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002054 VDecl->setInvalidDecl();
2055 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002056 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002057 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002058 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002059
2060 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2061 if (!getLangOptions().CPlusPlus) {
2062 if (SC == VarDecl::Static) // C99 6.7.8p4.
2063 CheckForConstantInitializer(Init, DclT);
2064 }
Steve Naroffbb204692007-09-12 14:07:44 +00002065 }
Steve Naroff248a7532008-04-15 22:42:06 +00002066 } else if (VDecl->isFileVarDecl()) {
2067 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002068 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002069 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002070 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002071 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002072 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002073
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002074 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2075 if (!getLangOptions().CPlusPlus) {
2076 // C99 6.7.8p4. All file scoped initializers need to be constant.
2077 CheckForConstantInitializer(Init, DclT);
2078 }
Steve Naroffbb204692007-09-12 14:07:44 +00002079 }
2080 // If the type changed, it means we had an incomplete type that was
2081 // completed by the initializer. For example:
2082 // int ary[] = { 1, 3, 5 };
2083 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002084 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002085 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002086 Init->setType(DclT);
2087 }
Steve Naroffbb204692007-09-12 14:07:44 +00002088
2089 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002090 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002091 return;
2092}
2093
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002094void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2095 Decl *RealDecl = static_cast<Decl *>(dcl);
2096
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002097 // If there is no declaration, there was an error parsing it. Just ignore it.
2098 if (RealDecl == 0)
2099 return;
2100
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002101 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2102 QualType Type = Var->getType();
2103 // C++ [dcl.init.ref]p3:
2104 // The initializer can be omitted for a reference only in a
2105 // parameter declaration (8.3.5), in the declaration of a
2106 // function return type, in the declaration of a class member
2107 // within its class declaration (9.2), and where the extern
2108 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002109 if (Type->isReferenceType() &&
2110 Var->getStorageClass() != VarDecl::Extern &&
2111 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002112 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002113 << Var->getDeclName()
2114 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002115 Var->setInvalidDecl();
2116 return;
2117 }
2118
2119 // C++ [dcl.init]p9:
2120 //
2121 // If no initializer is specified for an object, and the object
2122 // is of (possibly cv-qualified) non-POD class type (or array
2123 // thereof), the object shall be default-initialized; if the
2124 // object is of const-qualified type, the underlying class type
2125 // shall have a user-declared default constructor.
2126 if (getLangOptions().CPlusPlus) {
2127 QualType InitType = Type;
2128 if (const ArrayType *Array = Context.getAsArrayType(Type))
2129 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002130 if (Var->getStorageClass() != VarDecl::Extern &&
2131 Var->getStorageClass() != VarDecl::PrivateExtern &&
2132 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002133 const CXXConstructorDecl *Constructor
2134 = PerformInitializationByConstructor(InitType, 0, 0,
2135 Var->getLocation(),
2136 SourceRange(Var->getLocation(),
2137 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002138 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002139 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002140 if (!Constructor)
2141 Var->setInvalidDecl();
2142 }
2143 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002144
Douglas Gregor818ce482008-10-29 13:50:18 +00002145#if 0
2146 // FIXME: Temporarily disabled because we are not properly parsing
2147 // linkage specifications on declarations, e.g.,
2148 //
2149 // extern "C" const CGPoint CGPointerZero;
2150 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002151 // C++ [dcl.init]p9:
2152 //
2153 // If no initializer is specified for an object, and the
2154 // object is of (possibly cv-qualified) non-POD class type (or
2155 // array thereof), the object shall be default-initialized; if
2156 // the object is of const-qualified type, the underlying class
2157 // type shall have a user-declared default
2158 // constructor. Otherwise, if no initializer is specified for
2159 // an object, the object and its subobjects, if any, have an
2160 // indeterminate initial value; if the object or any of its
2161 // subobjects are of const-qualified type, the program is
2162 // ill-formed.
2163 //
2164 // This isn't technically an error in C, so we don't diagnose it.
2165 //
2166 // FIXME: Actually perform the POD/user-defined default
2167 // constructor check.
2168 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002169 Context.getCanonicalType(Type).isConstQualified() &&
2170 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002171 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2172 << Var->getName()
2173 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002174#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002175 }
2176}
2177
Reid Spencer5f016e22007-07-11 17:01:13 +00002178/// The declarators are chained together backwards, reverse the list.
2179Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2180 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002181 Decl *GroupDecl = static_cast<Decl*>(group);
2182 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002183 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002184
2185 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2186 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002187 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002188 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002189 else { // reverse the list.
2190 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002191 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002192 Group->setNextDeclarator(NewGroup);
2193 NewGroup = Group;
2194 Group = Next;
2195 }
2196 }
2197 // Perform semantic analysis that depends on having fully processed both
2198 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002199 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002200 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2201 if (!IDecl)
2202 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002203 QualType T = IDecl->getType();
2204
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002205 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002206 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002207
2208 // FIXME: This won't give the correct result for
2209 // int a[10][n];
2210 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002211 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002212 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2213 SizeRange;
2214
Eli Friedmanc5773c42008-02-15 18:16:39 +00002215 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002216 } else {
2217 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2218 // static storage duration, it shall not have a variable length array.
2219 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002220 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2221 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002222 IDecl->setInvalidDecl();
2223 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002224 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2225 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002226 IDecl->setInvalidDecl();
2227 }
2228 }
2229 } else if (T->isVariablyModifiedType()) {
2230 if (IDecl->isFileVarDecl()) {
2231 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2232 IDecl->setInvalidDecl();
2233 } else {
2234 if (IDecl->getStorageClass() == VarDecl::Extern) {
2235 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2236 IDecl->setInvalidDecl();
2237 }
Steve Naroffbb204692007-09-12 14:07:44 +00002238 }
2239 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002240
Steve Naroffbb204692007-09-12 14:07:44 +00002241 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2242 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002243 if (IDecl->isBlockVarDecl() &&
2244 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002245 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002246 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002247 IDecl->setInvalidDecl();
2248 }
2249 }
2250 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2251 // object that has file scope without an initializer, and without a
2252 // storage-class specifier or with the storage-class specifier "static",
2253 // constitutes a tentative definition. Note: A tentative definition with
2254 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002255 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002256 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002257 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2258 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002259 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002260 // C99 6.9.2p3: If the declaration of an identifier for an object is
2261 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2262 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002263 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002264 IDecl->setInvalidDecl();
2265 }
2266 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002267 if (IDecl->isFileVarDecl())
2268 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 }
2270 return NewGroup;
2271}
Steve Naroffe1223f72007-08-28 03:03:08 +00002272
Chris Lattner04421082008-04-08 04:40:51 +00002273/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2274/// to introduce parameters into function prototype scope.
2275Sema::DeclTy *
2276Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002277 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002278
Chris Lattner04421082008-04-08 04:40:51 +00002279 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002280 VarDecl::StorageClass StorageClass = VarDecl::None;
2281 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2282 StorageClass = VarDecl::Register;
2283 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002284 Diag(DS.getStorageClassSpecLoc(),
2285 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002286 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002287 }
2288 if (DS.isThreadSpecified()) {
2289 Diag(DS.getThreadSpecLoc(),
2290 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002291 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002292 }
2293
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002294 // Check that there are no default arguments inside the type of this
2295 // parameter (C++ only).
2296 if (getLangOptions().CPlusPlus)
2297 CheckExtraCXXDefaultArguments(D);
2298
Chris Lattner04421082008-04-08 04:40:51 +00002299 // In this context, we *do not* check D.getInvalidType(). If the declarator
2300 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2301 // though it will not reflect the user specified type.
2302 QualType parmDeclType = GetTypeForDeclarator(D, S);
2303
2304 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2307 // Can this happen for params? We already checked that they don't conflict
2308 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002309 IdentifierInfo *II = D.getIdentifier();
2310 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002311 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002312 // Maybe we will complain about the shadowed template parameter.
2313 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2314 // Just pretend that we didn't see the previous declaration.
2315 PrevDecl = 0;
2316 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002317 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002318
2319 // Recover by removing the name
2320 II = 0;
2321 D.SetIdentifier(0, D.getIdentifierLoc());
2322 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002323 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002324
2325 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2326 // Doing the promotion here has a win and a loss. The win is the type for
2327 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2328 // code generator). The loss is the orginal type isn't preserved. For example:
2329 //
2330 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2331 // int blockvardecl[5];
2332 // sizeof(parmvardecl); // size == 4
2333 // sizeof(blockvardecl); // size == 20
2334 // }
2335 //
2336 // For expressions, all implicit conversions are captured using the
2337 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2338 //
2339 // FIXME: If a source translation tool needs to see the original type, then
2340 // we need to consider storing both types (in ParmVarDecl)...
2341 //
Chris Lattnere6327742008-04-02 05:18:44 +00002342 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002343 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002344 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002345 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002346 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002347
Chris Lattner04421082008-04-08 04:40:51 +00002348 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2349 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002350 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002351 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002352
Chris Lattner04421082008-04-08 04:40:51 +00002353 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002354 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002355
Douglas Gregor584049d2008-12-15 23:53:10 +00002356 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2357 if (D.getCXXScopeSpec().isSet()) {
2358 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2359 << D.getCXXScopeSpec().getRange();
2360 New->setInvalidDecl();
2361 }
2362
Douglas Gregor44b43212008-12-11 16:49:14 +00002363 // Add the parameter declaration into this scope.
2364 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002365 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002366 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002367
Chris Lattner3ff30c82008-06-29 00:02:00 +00002368 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002369 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002370
Reid Spencer5f016e22007-07-11 17:01:13 +00002371}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002372
Chris Lattnerb652cea2007-10-09 17:14:05 +00002373Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002374 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2376 "Not a function declarator!");
2377 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002378
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2380 // for a K&R function.
2381 if (!FTI.hasPrototype) {
2382 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002383 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002384 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2385 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002386 // Implicitly declare the argument as type 'int' for lack of a better
2387 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002388 DeclSpec DS;
2389 const char* PrevSpec; // unused
2390 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2391 PrevSpec);
2392 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2393 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2394 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 }
2396 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002398 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 }
2400
Douglas Gregor584049d2008-12-15 23:53:10 +00002401 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002402
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002403 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002404 ActOnDeclarator(ParentScope, D, 0,
2405 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002406}
2407
2408Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2409 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002410 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002411
2412 // See if this is a redefinition.
2413 const FunctionDecl *Definition;
2414 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002415 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002416 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002417 }
2418
Douglas Gregor44b43212008-12-11 16:49:14 +00002419 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002420
Chris Lattner04421082008-04-08 04:40:51 +00002421 // Check the validity of our function parameters
2422 CheckParmsForFunctionDef(FD);
2423
2424 // Introduce our parameters into the function scope
2425 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2426 ParmVarDecl *Param = FD->getParamDecl(p);
2427 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002428 if (Param->getIdentifier())
2429 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 }
Chris Lattner04421082008-04-08 04:40:51 +00002431
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002432 // Checking attributes of current function definition
2433 // dllimport attribute.
2434 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2435 // dllimport attribute cannot be applied to definition.
2436 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2437 Diag(FD->getLocation(),
2438 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2439 << "dllimport";
2440 FD->setInvalidDecl();
2441 return FD;
2442 } else {
2443 // If a symbol previously declared dllimport is later defined, the
2444 // attribute is ignored in subsequent references, and a warning is
2445 // emitted.
2446 Diag(FD->getLocation(),
2447 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2448 << FD->getNameAsCString() << "dllimport";
2449 }
2450 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002451 return FD;
2452}
2453
Sebastian Redl798d1192008-12-13 16:23:55 +00002454Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002455 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002456 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002457 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002458 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002459 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002460 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002461 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002462 } else
2463 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002464 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002465 // Verify and clean out per-function state.
2466
2467 // Check goto/label use.
2468 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2469 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2470 // Verify that we have no forward references left. If so, there was a goto
2471 // or address of a label taken, but no definition of it. Label fwd
2472 // definitions are indicated with a null substmt.
2473 if (I->second->getSubStmt() == 0) {
2474 LabelStmt *L = I->second;
2475 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002476 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002477
2478 // At this point, we have gotos that use the bogus label. Stitch it into
2479 // the function body so that they aren't leaked and that the AST is well
2480 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002481 if (Body) {
2482 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002483 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002484 } else {
2485 // The whole function wasn't parsed correctly, just delete this.
2486 delete L;
2487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 }
2489 }
2490 LabelMap.clear();
2491
Steve Naroffd6d054d2007-11-11 23:20:51 +00002492 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002493}
2494
Reid Spencer5f016e22007-07-11 17:01:13 +00002495/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2496/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002497ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2498 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002499 // Extension in C99. Legal in C90, but warn about it.
2500 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002501 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002502 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002503 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002504
2505 // FIXME: handle stuff like:
2506 // void foo() { extern float X(); }
2507 // void bar() { X(); } <-- implicit decl for X in another scope.
2508
2509 // Set a Declarator for the implicit definition: int foo();
2510 const char *Dummy;
2511 DeclSpec DS;
2512 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2513 Error = Error; // Silence warning.
2514 assert(!Error && "Error setting up implicit decl!");
2515 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002516 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 D.SetIdentifier(&II, Loc);
2518
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002519 // Insert this function into translation-unit scope.
2520
2521 DeclContext *PrevDC = CurContext;
2522 CurContext = Context.getTranslationUnitDecl();
2523
Steve Naroffe2ef8152008-04-04 14:32:09 +00002524 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002525 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002526 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002527
2528 CurContext = PrevDC;
2529
Steve Naroffe2ef8152008-04-04 14:32:09 +00002530 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002531}
2532
2533
Chris Lattner41af0932007-11-14 06:34:38 +00002534TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002535 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002536 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002537 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002538
2539 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002540 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2541 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002542 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002543 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002544 if (D.getInvalidType())
2545 NewTD->setInvalidDecl();
2546 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002547}
2548
Steve Naroff08d92e42007-09-15 18:49:24 +00002549/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002550/// former case, Name will be non-null. In the later case, Name will be null.
2551/// TagType indicates what kind of tag this is. TK indicates whether this is a
2552/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002553Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002554 SourceLocation KWLoc, const CXXScopeSpec &SS,
2555 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002556 AttributeList *Attr,
2557 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002558 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002559 assert((Name != 0 || TK == TK_Definition) &&
2560 "Nameless record must be a definition!");
2561
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002562 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 switch (TagType) {
2564 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002565 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2566 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2567 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2568 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 }
2570
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002571 DeclContext *DC = CurContext;
2572 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002573
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002574 if (Name && SS.isNotEmpty()) {
2575 // We have a nested-name tag ('struct foo::bar').
2576
2577 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002578 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002579 Name = 0;
2580 goto CreateNewDecl;
2581 }
2582
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002583 DC = static_cast<DeclContext*>(SS.getScopeRep());
2584 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002585 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2586
2587 // A tag 'foo::bar' must already exist.
2588 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002589 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002590 Name = 0;
2591 goto CreateNewDecl;
2592 }
2593 } else {
2594 // If this is a named struct, check to see if there was a previous forward
2595 // declaration or definition.
2596 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2597 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2598 }
2599
Douglas Gregorf57172b2008-12-08 18:40:42 +00002600 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002601 // Maybe we will complain about the shadowed template parameter.
2602 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2603 // Just pretend that we didn't see the previous declaration.
2604 PrevDecl = 0;
2605 }
2606
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002607 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002608 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2609 "unexpected Decl type");
2610 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002611 // If this is a use of a previous tag, or if the tag is already declared
2612 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002613 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002614 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002615 // Make sure that this wasn't declared as an enum and now used as a
2616 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002617 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002618 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002619 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002620 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002621 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002622 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002623 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002624 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002625
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002626 // FIXME: In the future, return a variant or some other clue
2627 // for the consumer of this Decl to know it doesn't own it.
2628 // For our current ASTs this shouldn't be a problem, but will
2629 // need to be changed with DeclGroups.
2630 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002631 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002632
2633 // Diagnose attempts to redefine a tag.
2634 if (TK == TK_Definition) {
2635 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2636 Diag(NameLoc, diag::err_redefinition) << Name;
2637 Diag(Def->getLocation(), diag::note_previous_definition);
2638 // If this is a redefinition, recover by making this struct be
2639 // anonymous, which will make any later references get the previous
2640 // definition.
2641 Name = 0;
2642 PrevDecl = 0;
2643 }
2644 // Okay, this is definition of a previously declared or referenced
2645 // tag PrevDecl. We're going to create a new Decl for it.
2646 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002647 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002648 // If we get here we have (another) forward declaration or we
2649 // have a definition. Just create a new decl.
2650 } else {
2651 // If we get here, this is a definition of a new tag type in a nested
2652 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2653 // new decl/type. We set PrevDecl to NULL so that the entities
2654 // have distinct types.
2655 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002657 // If we get here, we're going to create a new Decl. If PrevDecl
2658 // is non-NULL, it's a definition of the tag declared by
2659 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002660 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002661 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002662 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002663 // The tag name clashes with a namespace name, issue an error and
2664 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002665 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002666 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002667 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002668 PrevDecl = 0;
2669 } else {
2670 // The existing declaration isn't relevant to us; we're in a
2671 // new scope, so clear out the previous declaration.
2672 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002673 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002676
Chris Lattnercc98eac2008-12-17 07:13:27 +00002677CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002678
2679 // If there is an identifier, use the location of the identifier as the
2680 // location of the decl, otherwise use the location of the struct/union
2681 // keyword.
2682 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2683
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002684 // Otherwise, create a new declaration. If there is a previous
2685 // declaration of the same entity, the two will be linked via
2686 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002688 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2690 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002691 New = EnumDecl::Create(Context, DC, Loc, Name,
2692 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002693 // If this is an undefined enum, warn.
2694 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002695 } else {
2696 // struct/union/class
2697
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2699 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002700 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002701 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002702 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2703 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002704 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002705 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2706 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002707 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002708
2709 if (Kind != TagDecl::TK_enum) {
2710 // Handle #pragma pack: if the #pragma pack stack has non-default
2711 // alignment, make up a packed attribute for this decl. These
2712 // attributes are checked when the ASTContext lays out the
2713 // structure.
2714 //
2715 // It is important for implementing the correct semantics that this
2716 // happen here (in act on tag decl). The #pragma pack stack is
2717 // maintained as a result of parser callbacks which can occur at
2718 // many points during the parsing of a struct declaration (because
2719 // the #pragma tokens are effectively skipped over during the
2720 // parsing of the struct).
2721 if (unsigned Alignment = PackContext.getAlignment())
2722 New->addAttr(new PackedAttr(Alignment * 8));
2723 }
2724
2725 if (Attr)
2726 ProcessDeclAttributeList(New, Attr);
2727
2728 // Set the lexical context. If the tag has a C++ scope specifier, the
2729 // lexical context will be different from the semantic context.
2730 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002731
2732 // If this has an identifier, add it to the scope stack.
2733 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002734 // The scope passed in may not be a decl scope. Zip up the scope tree until
2735 // we find one that is.
2736 while ((S->getFlags() & Scope::DeclScope) == 0)
2737 S = S->getParent();
2738
2739 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002740 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 return New;
2744}
2745
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002746
Chris Lattner1d353ba2008-11-12 21:17:48 +00002747/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2748/// types into constant array types in certain situations which would otherwise
2749/// be errors (for GCC compatibility).
2750static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2751 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002752 // This method tries to turn a variable array into a constant
2753 // array even when the size isn't an ICE. This is necessary
2754 // for compatibility with code that depends on gcc's buggy
2755 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002756 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2757 if (!VLATy) return QualType();
2758
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002759 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002760 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002761 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002762 return QualType();
2763
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002764 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2765 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002766 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2767 return Context.getConstantArrayType(VLATy->getElementType(),
2768 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002769 return QualType();
2770}
2771
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002772bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002773 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002774 // FIXME: 6.7.2.1p4 - verify the field type.
2775
2776 llvm::APSInt Value;
2777 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2778 return true;
2779
Chris Lattnercd087072008-12-12 04:56:04 +00002780 // Zero-width bitfield is ok for anonymous field.
2781 if (Value == 0 && FieldName)
2782 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2783
2784 if (Value.isNegative())
2785 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002786
2787 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2788 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002789 if (TypeSize && Value.getZExtValue() > TypeSize)
2790 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2791 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002792
2793 return false;
2794}
2795
Steve Naroff08d92e42007-09-15 18:49:24 +00002796/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002797/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002798Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 SourceLocation DeclStart,
2800 Declarator &D, ExprTy *BitfieldWidth) {
2801 IdentifierInfo *II = D.getIdentifier();
2802 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002803 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002804 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002805 if (II) Loc = D.getIdentifierLoc();
2806
2807 // FIXME: Unnamed fields can be handled in various different ways, for
2808 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002809
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002811 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2812 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002813
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2815 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002816 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002817 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002818 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002819 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002820 T = FixedTy;
2821 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002822 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002823 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002824 InvalidDecl = true;
2825 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002827
2828 if (BitWidth) {
2829 if (VerifyBitField(Loc, II, T, BitWidth))
2830 InvalidDecl = true;
2831 } else {
2832 // Not a bitfield.
2833
2834 // validate II.
2835
2836 }
2837
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002839 FieldDecl *NewFD;
2840
Douglas Gregor44b43212008-12-11 16:49:14 +00002841 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2842 // other way to determine the current RecordDecl.
2843 NewFD = FieldDecl::Create(Context, Record,
2844 Loc, II, T, BitWidth,
2845 D.getDeclSpec().getStorageClassSpec() ==
2846 DeclSpec::SCS_mutable,
2847 /*PrevDecl=*/0);
2848
Douglas Gregor72b505b2008-12-16 21:30:33 +00002849 if (getLangOptions().CPlusPlus)
2850 CheckExtraCXXDefaultArguments(D);
2851
Chris Lattner3ff30c82008-06-29 00:02:00 +00002852 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002853
Steve Naroff5912a352007-08-28 20:14:24 +00002854 if (D.getInvalidType() || InvalidDecl)
2855 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002856
2857 if (II && getLangOptions().CPlusPlus)
2858 PushOnScopeChains(NewFD, S);
2859 else
2860 Record->addDecl(Context, NewFD);
2861
Steve Naroff5912a352007-08-28 20:14:24 +00002862 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002863}
2864
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002865/// TranslateIvarVisibility - Translate visibility from a token ID to an
2866/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002867static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002868TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002869 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002870 default: assert(0 && "Unknown visitibility kind");
2871 case tok::objc_private: return ObjCIvarDecl::Private;
2872 case tok::objc_public: return ObjCIvarDecl::Public;
2873 case tok::objc_protected: return ObjCIvarDecl::Protected;
2874 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002875 }
2876}
2877
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002878/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2879/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002880Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002881 SourceLocation DeclStart,
2882 Declarator &D, ExprTy *BitfieldWidth,
2883 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002884 IdentifierInfo *II = D.getIdentifier();
2885 Expr *BitWidth = (Expr*)BitfieldWidth;
2886 SourceLocation Loc = DeclStart;
2887 if (II) Loc = D.getIdentifierLoc();
2888
2889 // FIXME: Unnamed fields can be handled in various different ways, for
2890 // example, unnamed unions inject all members into the struct namespace!
2891
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002892 QualType T = GetTypeForDeclarator(D, S);
2893 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2894 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002895
2896 if (BitWidth) {
2897 // TODO: Validate.
2898 //printf("WARNING: BITFIELDS IGNORED!\n");
2899
2900 // 6.7.2.1p3
2901 // 6.7.2.1p4
2902
2903 } else {
2904 // Not a bitfield.
2905
2906 // validate II.
2907
2908 }
2909
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002910 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2911 // than a variably modified type.
2912 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002913 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002914 InvalidDecl = true;
2915 }
2916
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002917 // Get the visibility (access control) for this ivar.
2918 ObjCIvarDecl::AccessControl ac =
2919 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2920 : ObjCIvarDecl::None;
2921
2922 // Construct the decl.
2923 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002924 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002925
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002926 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002927 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002928
2929 if (D.getInvalidType() || InvalidDecl)
2930 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002931
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002932 return NewID;
2933}
2934
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002935void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002936 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002937 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002938 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002939 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002940 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2941 assert(EnclosingDecl && "missing record or interface decl");
2942 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2943
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002944 if (Record)
2945 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2946 // Diagnose code like:
2947 // struct S { struct S {} X; };
2948 // We discover this when we complete the outer S. Reject and ignore the
2949 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002950 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002951 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002952 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002953 Record->setInvalidDecl();
2954 return;
2955 }
2956
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 // Verify that all the fields are okay.
2958 unsigned NumNamedMembers = 0;
2959 llvm::SmallVector<FieldDecl*, 32> RecFields;
2960 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002961
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002963
Steve Naroff74216642007-09-14 22:20:54 +00002964 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2965 assert(FD && "missing field decl");
2966
2967 // Remember all fields.
2968 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002969
2970 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002971 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002972
Reid Spencer5f016e22007-07-11 17:01:13 +00002973 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002974 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002975 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002976 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002977 FD->setInvalidDecl();
2978 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 continue;
2980 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2982 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002983 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002984 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002985 FD->setInvalidDecl();
2986 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002987 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002988 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002990 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002991 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002992 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002993 FD->setInvalidDecl();
2994 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002995 continue;
2996 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002997 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002998 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002999 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003000 FD->setInvalidDecl();
3001 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003002 continue;
3003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003005 if (Record)
3006 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003008 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3009 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003010 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003011 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3012 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003013 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003014 Record->setHasFlexibleArrayMember(true);
3015 } else {
3016 // If this is a struct/class and this is not the last element, reject
3017 // it. Note that GCC supports variable sized arrays in the middle of
3018 // structures.
3019 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003020 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003021 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003022 FD->setInvalidDecl();
3023 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 continue;
3025 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003026 // We support flexible arrays at the end of structs in other structs
3027 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003028 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003029 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003030 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003031 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 }
3033 }
3034 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003035 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003036 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003037 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003038 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003039 FD->setInvalidDecl();
3040 EnclosingDecl->setInvalidDecl();
3041 continue;
3042 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 // Keep track of the number of named members.
3044 if (IdentifierInfo *II = FD->getIdentifier()) {
3045 // Detect duplicate member names.
3046 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003047 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 // Find the previous decl.
3049 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003050 for (unsigned i = 0; ; ++i) {
3051 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003052 if (RecFields[i]->getIdentifier() == II) {
3053 PrevLoc = RecFields[i]->getLocation();
3054 break;
3055 }
3056 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003057 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003058 FD->setInvalidDecl();
3059 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 continue;
3061 }
3062 ++NumNamedMembers;
3063 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003064 }
3065
Reid Spencer5f016e22007-07-11 17:01:13 +00003066 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003067 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003068 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003069 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3070 // Sema::ActOnFinishCXXClassDef.
3071 if (!isa<CXXRecordDecl>(Record))
3072 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003073 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003074 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003075 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003076 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003077 // Must enforce the rule that ivars in the base classes may not be
3078 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003079 if (ID->getSuperClass()) {
3080 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3081 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3082 ObjCIvarDecl* Ivar = (*IVI);
3083 IdentifierInfo *II = Ivar->getIdentifier();
3084 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3085 if (prevIvar) {
3086 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3087 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003088 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003089 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003090 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003091 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003092 else if (ObjCImplementationDecl *IMPDecl =
3093 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003094 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3095 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003096 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003097 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003098 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003099
3100 if (Attr)
3101 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003102}
3103
Steve Naroff08d92e42007-09-15 18:49:24 +00003104Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003105 DeclTy *lastEnumConst,
3106 SourceLocation IdLoc, IdentifierInfo *Id,
3107 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003108 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003109 EnumConstantDecl *LastEnumConst =
3110 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3111 Expr *Val = static_cast<Expr*>(val);
3112
Chris Lattner31e05722007-08-26 06:24:45 +00003113 // The scope passed in may not be a decl scope. Zip up the scope tree until
3114 // we find one that is.
3115 while ((S->getFlags() & Scope::DeclScope) == 0)
3116 S = S->getParent();
3117
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 // Verify that there isn't already something declared with this name in this
3119 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003120 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003121 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003122 // Maybe we will complain about the shadowed template parameter.
3123 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3124 // Just pretend that we didn't see the previous declaration.
3125 PrevDecl = 0;
3126 }
3127
3128 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003129 // When in C++, we may get a TagDecl with the same name; in this case the
3130 // enum constant will 'hide' the tag.
3131 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3132 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003133 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003135 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003136 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003137 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003138 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003139 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003140 return 0;
3141 }
3142 }
3143
3144 llvm::APSInt EnumVal(32);
3145 QualType EltTy;
3146 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003147 // Make sure to promote the operand type to int.
3148 UsualUnaryConversions(Val);
3149
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3151 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003152 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003153 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003154 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003155 } else {
3156 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003157 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003158 }
3159
3160 if (!Val) {
3161 if (LastEnumConst) {
3162 // Assign the last value + 1.
3163 EnumVal = LastEnumConst->getInitVal();
3164 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003165
3166 // Check for overflow on increment.
3167 if (EnumVal < LastEnumConst->getInitVal())
3168 Diag(IdLoc, diag::warn_enum_value_overflow);
3169
Chris Lattnerb7416f92007-08-27 17:37:24 +00003170 EltTy = LastEnumConst->getType();
3171 } else {
3172 // First value, set to zero.
3173 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003174 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003175 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003176 }
3177
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003178 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003179 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3180 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003181 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003182
3183 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003184 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003185
3186 // Add this enumerator into the enum itself.
3187 // FIXME: This means that the enumerator is stored in two
3188 // DeclContexts. This is not a long-term solution.
3189 New->setLexicalDeclContext(TheEnumDecl);
3190 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 return New;
3192}
3193
Steve Naroff02408c62008-08-07 14:08:16 +00003194// FIXME: For consistency with ActOnFields(), we should have the parser
3195// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003196void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003197 DeclTy **Elements, unsigned NumElements) {
3198 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003199
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003200 if (Enum) {
3201 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3202 // Diagnose code like:
3203 // enum e0 {
3204 // E0 = sizeof(enum e0 { E1 })
3205 // };
3206 Diag(Def->getLocation(), diag::err_nested_redefinition)
3207 << Enum->getDeclName();
3208 Diag(Enum->getLocation(), diag::note_previous_definition);
3209 Enum->setInvalidDecl();
3210 return;
3211 }
Steve Naroff02408c62008-08-07 14:08:16 +00003212 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003213 // TODO: If the result value doesn't fit in an int, it must be a long or long
3214 // long value. ISO C does not support this, but GCC does as an extension,
3215 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003216 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003217
Chris Lattnerac609682007-08-28 06:15:15 +00003218 // Verify that all the values are okay, compute the size of the values, and
3219 // reverse the list.
3220 unsigned NumNegativeBits = 0;
3221 unsigned NumPositiveBits = 0;
3222
3223 // Keep track of whether all elements have type int.
3224 bool AllElementsInt = true;
3225
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003226 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003227 EnumConstantDecl *EltList = 0;
3228 for (unsigned i = 0; i != NumElements; ++i) {
3229 EnumConstantDecl *ECD =
3230 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3231 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003232
3233 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003234 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003235 assert(InitVal.getBitWidth() >= IntWidth &&
3236 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003237 if (InitVal.getBitWidth() > IntWidth) {
3238 llvm::APSInt V(InitVal);
3239 V.trunc(IntWidth);
3240 V.extend(InitVal.getBitWidth());
3241 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003242 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3243 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003244 }
Chris Lattnerac609682007-08-28 06:15:15 +00003245
3246 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003247 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003248 NumPositiveBits = std::max(NumPositiveBits,
3249 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003250 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003251 NumNegativeBits = std::max(NumNegativeBits,
3252 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003253
Chris Lattnerac609682007-08-28 06:15:15 +00003254 // Keep track of whether every enum element has type int (very commmon).
3255 if (AllElementsInt)
3256 AllElementsInt = ECD->getType() == Context.IntTy;
3257
Reid Spencer5f016e22007-07-11 17:01:13 +00003258 ECD->setNextDeclarator(EltList);
3259 EltList = ECD;
3260 }
3261
Chris Lattnerac609682007-08-28 06:15:15 +00003262 // Figure out the type that should be used for this enum.
3263 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3264 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003265 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003266
3267 if (NumNegativeBits) {
3268 // If there is a negative value, figure out the smallest integer type (of
3269 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003270 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003271 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003272 BestWidth = IntWidth;
3273 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003274 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003275
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003276 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003277 BestType = Context.LongTy;
3278 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003279 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003280
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003281 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003282 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3283 BestType = Context.LongLongTy;
3284 }
3285 }
3286 } else {
3287 // If there is no negative value, figure out which of uint, ulong, ulonglong
3288 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003289 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003290 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003291 BestWidth = IntWidth;
3292 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003293 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003294 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003295 } else {
3296 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003297 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003298 "How could an initializer get larger than ULL?");
3299 BestType = Context.UnsignedLongLongTy;
3300 }
3301 }
3302
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003303 // Loop over all of the enumerator constants, changing their types to match
3304 // the type of the enum if needed.
3305 for (unsigned i = 0; i != NumElements; ++i) {
3306 EnumConstantDecl *ECD =
3307 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3308 if (!ECD) continue; // Already issued a diagnostic.
3309
3310 // Standard C says the enumerators have int type, but we allow, as an
3311 // extension, the enumerators to be larger than int size. If each
3312 // enumerator value fits in an int, type it as an int, otherwise type it the
3313 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3314 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003315 if (ECD->getType() == Context.IntTy) {
3316 // Make sure the init value is signed.
3317 llvm::APSInt IV = ECD->getInitVal();
3318 IV.setIsSigned(true);
3319 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003320
3321 if (getLangOptions().CPlusPlus)
3322 // C++ [dcl.enum]p4: Following the closing brace of an
3323 // enum-specifier, each enumerator has the type of its
3324 // enumeration.
3325 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003326 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003327 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003328
3329 // Determine whether the value fits into an int.
3330 llvm::APSInt InitVal = ECD->getInitVal();
3331 bool FitsInInt;
3332 if (InitVal.isUnsigned() || !InitVal.isNegative())
3333 FitsInInt = InitVal.getActiveBits() < IntWidth;
3334 else
3335 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3336
3337 // If it fits into an integer type, force it. Otherwise force it to match
3338 // the enum decl type.
3339 QualType NewTy;
3340 unsigned NewWidth;
3341 bool NewSign;
3342 if (FitsInInt) {
3343 NewTy = Context.IntTy;
3344 NewWidth = IntWidth;
3345 NewSign = true;
3346 } else if (ECD->getType() == BestType) {
3347 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003348 if (getLangOptions().CPlusPlus)
3349 // C++ [dcl.enum]p4: Following the closing brace of an
3350 // enum-specifier, each enumerator has the type of its
3351 // enumeration.
3352 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003353 continue;
3354 } else {
3355 NewTy = BestType;
3356 NewWidth = BestWidth;
3357 NewSign = BestType->isSignedIntegerType();
3358 }
3359
3360 // Adjust the APSInt value.
3361 InitVal.extOrTrunc(NewWidth);
3362 InitVal.setIsSigned(NewSign);
3363 ECD->setInitVal(InitVal);
3364
3365 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003366 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3367 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003368 if (getLangOptions().CPlusPlus)
3369 // C++ [dcl.enum]p4: Following the closing brace of an
3370 // enum-specifier, each enumerator has the type of its
3371 // enumeration.
3372 ECD->setType(EnumType);
3373 else
3374 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003375 }
Chris Lattnerac609682007-08-28 06:15:15 +00003376
Douglas Gregor44b43212008-12-11 16:49:14 +00003377 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003378 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003379}
3380
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003381Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003382 ExprArg expr) {
3383 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3384
Chris Lattner8e25d862008-03-16 00:16:02 +00003385 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003386}
3387
Douglas Gregorf44515a2008-12-16 22:23:02 +00003388
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003389void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3390 ExprTy *alignment, SourceLocation PragmaLoc,
3391 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3392 Expr *Alignment = static_cast<Expr *>(alignment);
3393
3394 // If specified then alignment must be a "small" power of two.
3395 unsigned AlignmentVal = 0;
3396 if (Alignment) {
3397 llvm::APSInt Val;
3398 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3399 !Val.isPowerOf2() ||
3400 Val.getZExtValue() > 16) {
3401 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3402 delete Alignment;
3403 return; // Ignore
3404 }
3405
3406 AlignmentVal = (unsigned) Val.getZExtValue();
3407 }
3408
3409 switch (Kind) {
3410 case Action::PPK_Default: // pack([n])
3411 PackContext.setAlignment(AlignmentVal);
3412 break;
3413
3414 case Action::PPK_Show: // pack(show)
3415 // Show the current alignment, making sure to show the right value
3416 // for the default.
3417 AlignmentVal = PackContext.getAlignment();
3418 // FIXME: This should come from the target.
3419 if (AlignmentVal == 0)
3420 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003421 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003422 break;
3423
3424 case Action::PPK_Push: // pack(push [, id] [, [n])
3425 PackContext.push(Name);
3426 // Set the new alignment if specified.
3427 if (Alignment)
3428 PackContext.setAlignment(AlignmentVal);
3429 break;
3430
3431 case Action::PPK_Pop: // pack(pop [, id] [, n])
3432 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3433 // "#pragma pack(pop, identifier, n) is undefined"
3434 if (Alignment && Name)
3435 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3436
3437 // Do the pop.
3438 if (!PackContext.pop(Name)) {
3439 // If a name was specified then failure indicates the name
3440 // wasn't found. Otherwise failure indicates the stack was
3441 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003442 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3443 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003444
3445 // FIXME: Warn about popping named records as MSVC does.
3446 } else {
3447 // Pop succeeded, set the new alignment if specified.
3448 if (Alignment)
3449 PackContext.setAlignment(AlignmentVal);
3450 }
3451 break;
3452
3453 default:
3454 assert(0 && "Invalid #pragma pack kind.");
3455 }
3456}
3457
3458bool PragmaPackStack::pop(IdentifierInfo *Name) {
3459 if (Stack.empty())
3460 return false;
3461
3462 // If name is empty just pop top.
3463 if (!Name) {
3464 Alignment = Stack.back().first;
3465 Stack.pop_back();
3466 return true;
3467 }
3468
3469 // Otherwise, find the named record.
3470 for (unsigned i = Stack.size(); i != 0; ) {
3471 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003472 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003473 // Found it, pop up to and including this record.
3474 Alignment = Stack[i].first;
3475 Stack.erase(Stack.begin() + i, Stack.end());
3476 return true;
3477 }
3478 }
3479
3480 return false;
3481}