blob: f3f0a08bee2c25a757a0e91b68e35f424b5cfc55 [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) {
Douglas Gregor074149e2009-01-05 19:45:36 +000096 // Move up the scope chain until we find the nearest enclosing
97 // non-transparent context. The declaration will be introduced into this
98 // scope.
99 while (S->getEntity() &&
100 ((DeclContext *)S->getEntity())->isTransparentContext())
101 S = S->getParent();
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000105 // Add scoped declarations into their context, so that they can be
106 // found later. Declarations without a context won't be inserted
107 // into any context.
108 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
109 CurContext->addDecl(Context, SD);
110
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000111 // C++ [basic.scope]p4:
112 // -- exactly one declaration shall declare a class name or
113 // enumeration name that is not a typedef name and the other
114 // declarations shall all refer to the same object or
115 // enumerator, or all refer to functions and function templates;
116 // in this case the class name or enumeration name is hidden.
117 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000154 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000155 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000176}
177
Steve Naroffb216c882007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000187
Douglas Gregor44b43212008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000190
Douglas Gregor44b43212008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196}
197
Steve Naroffe8043c32008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000204
Steve Naroffb327ce02008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000206}
207
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000219template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000220static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221MaybeConstructOverloadSet(ASTContext &Context,
222 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000223 assert(I != IEnd && "Iterator range cannot be empty");
224 assert(!isa<OverloadedFunctionDecl>(*I) &&
225 "Cannot have an overloaded function");
226
227 if (isa<FunctionDecl>(*I)) {
228 // If we found a function, there might be more functions. If
229 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000230 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000231 OverloadedFunctionDecl *Ovl = 0;
232 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233 if (!Ovl) {
234 // FIXME: We leak this overload set. Eventually, we want to
235 // stop building the declarations for these overload sets, so
236 // there will be nothing to leak.
237 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000238 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000239 (*I)->getDeclName());
240 Ovl->addOverload(cast<FunctionDecl>(*I));
241 }
242 Ovl->addOverload(cast<FunctionDecl>(*Last));
243 }
244
245 // If we had more than one function, we built an overload
246 // set. Return it.
247 if (Ovl)
248 return Ovl;
249 }
250
251 return *I;
252}
253
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000254/// getNonFieldDeclScope - Retrieves the innermost scope, starting
255/// from S, where a non-field would be declared. This routine copes
256/// with the difference between C and C++ scoping rules in structs and
257/// unions. For example, the following code is well-formed in C but
258/// ill-formed in C++:
259/// @code
260/// struct S6 {
261/// enum { BAR } e;
262/// };
263///
264/// void test_S6() {
265/// struct S6 a;
266/// a.e = BAR;
267/// }
268/// @endcode
269/// For the declaration of BAR, this routine will return a different
270/// scope. The scope S will be the scope of the unnamed enumeration
271/// within S6. In C++, this routine will return the scope associated
272/// with S6, because the enumeration's scope is a transparent
273/// context but structures can contain non-field names. In C, this
274/// routine will return the translation unit scope, since the
275/// enumeration's scope is a transparent context and structures cannot
276/// contain non-field names.
277Scope *Sema::getNonFieldDeclScope(Scope *S) {
278 while (((S->getFlags() & Scope::DeclScope) == 0) ||
279 (S->getEntity() &&
280 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
281 (S->isClassScope() && !getLangOptions().CPlusPlus))
282 S = S->getParent();
283 return S;
284}
285
Steve Naroffe8043c32008-04-01 23:04:06 +0000286/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000287/// namespace. NamespaceNameOnly - during lookup only namespace names
288/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
289/// 'When looking up a namespace-name in a using-directive or
290/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000291Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000292 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000293 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000294 bool LookInParent,
295 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000296 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000297 unsigned NS = NSI;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000298
Douglas Gregor72de6672009-01-08 20:45:30 +0000299 // In C++, ordinary and member lookup will always find all
300 // kinds of names.
301 if (getLangOptions().CPlusPlus &&
302 (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Member)))
303 NS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Ordinary;
304
305 if (LookupCtx == 0 && !getLangOptions().CPlusPlus) {
306 // Unqualified name lookup in C/Objective-C is purely lexical, so
307 // search in the declarations attached to the name.
Douglas Gregore267ff32008-12-11 20:41:00 +0000308 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000309 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregor72de6672009-01-08 20:45:30 +0000310
311 // For the purposes of unqualified name lookup, structs and unions
312 // don't have scopes at all. For example:
313 //
314 // struct X {
315 // struct T { int i; } x;
316 // };
317 //
318 // void f() {
319 // struct T t; // okay: T is defined lexically within X, but
320 // // semantically at global scope
321 // };
322 //
323 // FIXME: Is there a better way to deal with this?
324 DeclContext *SearchCtx = CurContext;
325 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
326 SearchCtx = SearchCtx->getParent();
Douglas Gregore267ff32008-12-11 20:41:00 +0000327 IdentifierResolver::iterator I
Douglas Gregor72de6672009-01-08 20:45:30 +0000328 = IdResolver.begin(Name, SearchCtx, LookInParent);
Douglas Gregore267ff32008-12-11 20:41:00 +0000329
330 // Scan up the scope chain looking for a decl that matches this
331 // identifier that is in the appropriate namespace. This search
332 // should not take long, as shadowing of names is uncommon, and
333 // deep shadowing is extremely uncommon.
334 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000335 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000336 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000337 } else if (LookupCtx) {
Douglas Gregor72de6672009-01-08 20:45:30 +0000338 // If we're performing qualified name lookup (e.g., lookup into a
339 // struct), find fields as part of ordinary name lookup.
340 if (NS & Decl::IDNS_Ordinary)
341 NS |= Decl::IDNS_Member;
342
Douglas Gregor44b43212008-12-11 16:49:14 +0000343 // Perform qualified name lookup into the LookupCtx.
344 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000345 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000346 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000347 if ((*I)->isInIdentifierNamespace(NS)) {
348 // Ignore non-namespace names if we're only looking for namespaces.
349 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
350
351 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000352 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000353 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000354 // Name lookup for ordinary names and tag names in C++ requires
355 // looking into scopes that aren't strictly lexical, and
356 // therefore we walk through the context as well as walking
357 // through the scopes.
358 IdentifierResolver::iterator
359 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
360 IEnd = IdResolver.end();
361 for (; S; S = S->getParent()) {
362 // Check whether the IdResolver has anything in this scope.
363 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000364 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000365 if ((*I)->isInIdentifierNamespace(NS)) {
366 // Ignore non-namespace names if we're only looking for namespaces.
367 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
368 continue;
369
370 // We found something. Look for anything else in our scope
371 // with this same name and in an acceptable identifier
372 // namespace, so that we can construct an overload set if we
373 // need to.
374 IdentifierResolver::iterator LastI = I;
375 for (++LastI; LastI != IEnd; ++LastI) {
376 if (!(*LastI)->isInIdentifierNamespace(NS) ||
377 !S->isDeclScope(*LastI))
378 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000379 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000380 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000381 }
382 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000383
384 // If there is an entity associated with this scope, it's a
385 // DeclContext. We might need to perform qualified lookup into
386 // it.
387 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
388 while (Ctx && Ctx->isFunctionOrMethod())
389 Ctx = Ctx->getParent();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000390 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000391 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000392 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000393 for (llvm::tie(I, E) = Ctx->lookup(Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000394 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000395 if ((*I)->isInIdentifierNamespace(NS)) {
396 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
397 continue;
398 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000399 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000400 }
401
Douglas Gregorbc468ba2009-01-07 21:36:02 +0000402 if (!LookInParent && !Ctx->isTransparentContext())
403 return 0;
404
Douglas Gregor44b43212008-12-11 16:49:14 +0000405 Ctx = Ctx->getParent();
406 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000407 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000408 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // If we didn't find a use of this identifier, and if the identifier
411 // corresponds to a compiler builtin, create the decl object for the builtin
412 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000413 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000414 IdentifierInfo *II = Name.getAsIdentifierInfo();
415 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000416 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000417 // If this is a builtin on this (or all) targets, create the decl.
418 if (unsigned BuiltinID = II->getBuiltinID())
419 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
420 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000421 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000422 // @interface and @compatibility_alias introduce typedef-like names.
423 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000424 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000425 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000426 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
427 if (IDI != ObjCInterfaceDecls.end())
428 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000429 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
430 if (I != ObjCAliasDecls.end())
431 return I->second->getClassInterface();
432 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 }
434 return 0;
435}
436
Chris Lattner95e2c712008-05-05 22:18:14 +0000437void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000438 if (!Context.getBuiltinVaListType().isNull())
439 return;
440
441 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000442 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000443 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000444 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
445}
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
448/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000449ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
450 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 Builtin::ID BID = (Builtin::ID)bid;
452
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000453 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000454 InitBuiltinVaListType();
455
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000456 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000457 FunctionDecl *New = FunctionDecl::Create(Context,
458 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000459 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000460 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461
Chris Lattner95e2c712008-05-05 22:18:14 +0000462 // Create Decl objects for each parameter, adding them to the
463 // FunctionDecl.
464 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
465 llvm::SmallVector<ParmVarDecl*, 16> Params;
466 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
467 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
468 FT->getArgType(i), VarDecl::None, 0,
469 0));
470 New->setParams(&Params[0], Params.size());
471 }
472
473
474
Chris Lattner7f925cc2008-04-11 07:00:53 +0000475 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000476 // FIXME: This is hideous. We need to teach PushOnScopeChains to
477 // relate Scopes to DeclContexts, and probably eliminate CurContext
478 // entirely, but we're not there yet.
479 DeclContext *SavedContext = CurContext;
480 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000481 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000482 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 return New;
484}
485
Sebastian Redlc42e1182008-11-11 11:37:55 +0000486/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
487/// everything from the standard library is defined.
488NamespaceDecl *Sema::GetStdNamespace() {
489 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000490 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000491 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000492 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000493 0, Global, /*enableLazyBuiltinCreation=*/false);
494 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
495 }
496 return StdNamespace;
497}
498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
500/// and scope as a previous declaration 'Old'. Figure out how to resolve this
501/// situation, merging decls or emitting diagnostics as appropriate.
502///
Steve Naroffe8043c32008-04-01 23:04:06 +0000503TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000504 // Allow multiple definitions for ObjC built-in typedefs.
505 // FIXME: Verify the underlying types are equivalent!
506 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000507 const IdentifierInfo *TypeID = New->getIdentifier();
508 switch (TypeID->getLength()) {
509 default: break;
510 case 2:
511 if (!TypeID->isStr("id"))
512 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000513 Context.setObjCIdType(New);
514 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000515 case 5:
516 if (!TypeID->isStr("Class"))
517 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000518 Context.setObjCClassType(New);
519 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000520 case 3:
521 if (!TypeID->isStr("SEL"))
522 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000523 Context.setObjCSelType(New);
524 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000525 case 8:
526 if (!TypeID->isStr("Protocol"))
527 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000528 Context.setObjCProtoType(New->getUnderlyingType());
529 return New;
530 }
531 // Fall through - the typedef name was not a builtin type.
532 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 // Verify the old decl was also a typedef.
534 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
535 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000536 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000537 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000538 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 return New;
540 }
541
Chris Lattner99cb9972008-07-25 18:44:27 +0000542 // If the typedef types are not identical, reject them in all languages and
543 // with any extensions enabled.
544 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
545 Context.getCanonicalType(Old->getUnderlyingType()) !=
546 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000547 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000548 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000549 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000550 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000551 }
552
Eli Friedman54ecfce2008-06-11 06:20:39 +0000553 if (getLangOptions().Microsoft) return New;
554
Douglas Gregorbbe27432008-11-21 16:29:06 +0000555 // C++ [dcl.typedef]p2:
556 // In a given non-class scope, a typedef specifier can be used to
557 // redefine the name of any type declared in that scope to refer
558 // to the type to which it already refers.
559 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
560 return New;
561
562 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000563 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
564 // *either* declaration is in a system header. The code below implements
565 // this adhoc compatibility rule. FIXME: The following code will not
566 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000567 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
568 SourceManager &SrcMgr = Context.getSourceManager();
569 if (SrcMgr.isInSystemHeader(Old->getLocation()))
570 return New;
571 if (SrcMgr.isInSystemHeader(New->getLocation()))
572 return New;
573 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000574
Chris Lattner08631c52008-11-23 21:45:46 +0000575 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000576 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 return New;
578}
579
Chris Lattner6b6b5372008-06-26 18:38:35 +0000580/// DeclhasAttr - returns true if decl Declaration already has the target
581/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000582static bool DeclHasAttr(const Decl *decl, const Attr *target) {
583 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
584 if (attr->getKind() == target->getKind())
585 return true;
586
587 return false;
588}
589
590/// MergeAttributes - append attributes from the Old decl to the New one.
591static void MergeAttributes(Decl *New, Decl *Old) {
592 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
593
Chris Lattnerddee4232008-03-03 03:28:21 +0000594 while (attr) {
595 tmp = attr;
596 attr = attr->getNext();
597
598 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000599 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000600 New->addAttr(tmp);
601 } else {
602 tmp->setNext(0);
603 delete(tmp);
604 }
605 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000606
607 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000608}
609
Chris Lattner04421082008-04-08 04:40:51 +0000610/// MergeFunctionDecl - We just parsed a function 'New' from
611/// declarator D which has the same name and scope as a previous
612/// declaration 'Old'. Figure out how to resolve this situation,
613/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614/// Redeclaration will be set true if this New is a redeclaration OldD.
615///
616/// In C++, New and Old must be declarations that are not
617/// overloaded. Use IsOverload to determine whether New and Old are
618/// overloaded, and to select the Old declaration that New should be
619/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000620FunctionDecl *
621Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000622 assert(!isa<OverloadedFunctionDecl>(OldD) &&
623 "Cannot merge with an overloaded function declaration");
624
Douglas Gregorf0097952008-04-21 02:02:58 +0000625 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 // Verify the old decl was also a function.
627 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
628 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000629 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000630 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000631 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 return New;
633 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000634
635 // Determine whether the previous declaration was a definition,
636 // implicit declaration, or a declaration.
637 diag::kind PrevDiag;
638 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000639 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000640 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000641 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000643 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000644
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000645 QualType OldQType = Context.getCanonicalType(Old->getType());
646 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000647
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000648 if (getLangOptions().CPlusPlus) {
649 // (C++98 13.1p2):
650 // Certain function declarations cannot be overloaded:
651 // -- Function declarations that differ only in the return type
652 // cannot be overloaded.
653 QualType OldReturnType
654 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
655 QualType NewReturnType
656 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
657 if (OldReturnType != NewReturnType) {
658 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
659 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000660 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 return New;
662 }
663
664 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
665 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
666 if (OldMethod && NewMethod) {
667 // -- Member function declarations with the same name and the
668 // same parameter types cannot be overloaded if any of them
669 // is a static member function declaration.
670 if (OldMethod->isStatic() || NewMethod->isStatic()) {
671 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
672 Diag(Old->getLocation(), PrevDiag);
673 return New;
674 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000675
676 // C++ [class.mem]p1:
677 // [...] A member shall not be declared twice in the
678 // member-specification, except that a nested class or member
679 // class template can be declared and then later defined.
680 if (OldMethod->getLexicalDeclContext() ==
681 NewMethod->getLexicalDeclContext()) {
682 unsigned NewDiag;
683 if (isa<CXXConstructorDecl>(OldMethod))
684 NewDiag = diag::err_constructor_redeclared;
685 else if (isa<CXXDestructorDecl>(NewMethod))
686 NewDiag = diag::err_destructor_redeclared;
687 else if (isa<CXXConversionDecl>(NewMethod))
688 NewDiag = diag::err_conv_function_redeclared;
689 else
690 NewDiag = diag::err_member_redeclared;
691
692 Diag(New->getLocation(), NewDiag);
693 Diag(Old->getLocation(), PrevDiag);
694 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 }
696
697 // (C++98 8.3.5p3):
698 // All declarations for a function shall agree exactly in both the
699 // return type and the parameter-type-list.
700 if (OldQType == NewQType) {
701 // We have a redeclaration.
702 MergeAttributes(New, Old);
703 Redeclaration = true;
704 return MergeCXXFunctionDecl(New, Old);
705 }
706
707 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000708 }
Chris Lattner04421082008-04-08 04:40:51 +0000709
710 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000711 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000712 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000713 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000714 MergeAttributes(New, Old);
715 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000716 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000717 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000718
Steve Naroff837618c2008-01-16 15:01:34 +0000719 // A function that has already been declared has been redeclared or defined
720 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
723 // TODO: This is totally simplistic. It should handle merging functions
724 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000725 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000726 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 return New;
728}
729
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000730/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000731static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000732 if (VD->isFileVarDecl())
733 return (!VD->getInit() &&
734 (VD->getStorageClass() == VarDecl::None ||
735 VD->getStorageClass() == VarDecl::Static));
736 return false;
737}
738
739/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
740/// when dealing with C "tentative" external object definitions (C99 6.9.2).
741void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
742 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000743 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000744
Douglas Gregore21b9942009-01-07 16:34:42 +0000745 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000746 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000747 for (IdentifierResolver::iterator
748 I = IdResolver.begin(VD->getIdentifier(),
749 VD->getDeclContext(), false/*LookInParentCtx*/),
750 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000751 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000752 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
753
Steve Narofff855e6f2008-08-10 15:20:13 +0000754 // Handle the following case:
755 // int a[10];
756 // int a[]; - the code below makes sure we set the correct type.
757 // int a[11]; - this is an error, size isn't 10.
758 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
759 OldDecl->getType()->isConstantArrayType())
760 VD->setType(OldDecl->getType());
761
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000762 // Check for "tentative" definitions. We can't accomplish this in
763 // MergeVarDecl since the initializer hasn't been attached.
764 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
765 continue;
766
767 // Handle __private_extern__ just like extern.
768 if (OldDecl->getStorageClass() != VarDecl::Extern &&
769 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
770 VD->getStorageClass() != VarDecl::Extern &&
771 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000772 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000773 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000774 }
775 }
776 }
777}
778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779/// MergeVarDecl - We just parsed a variable 'New' which has the same name
780/// and scope as a previous declaration 'Old'. Figure out how to resolve this
781/// situation, merging decls or emitting diagnostics as appropriate.
782///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000783/// Tentative definition rules (C99 6.9.2p2) are checked by
784/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
785/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000786///
Steve Naroffe8043c32008-04-01 23:04:06 +0000787VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 // Verify the old decl was also a variable.
789 VarDecl *Old = dyn_cast<VarDecl>(OldD);
790 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000791 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000792 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000793 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 return New;
795 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000796
797 MergeAttributes(New, Old);
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000800 QualType OldCType = Context.getCanonicalType(Old->getType());
801 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000802 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000803 Diag(New->getLocation(), diag::err_redefinition_different_type)
804 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000805 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 return New;
807 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000808 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
809 if (New->getStorageClass() == VarDecl::Static &&
810 (Old->getStorageClass() == VarDecl::None ||
811 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000812 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000813 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000814 return New;
815 }
816 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
817 if (New->getStorageClass() != VarDecl::Static &&
818 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000819 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000820 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000821 return New;
822 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000823 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
824 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000825 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000826 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 }
828 return New;
829}
830
Chris Lattner04421082008-04-08 04:40:51 +0000831/// CheckParmsForFunctionDef - Check that the parameters of the given
832/// function are appropriate for the definition of a function. This
833/// takes care of any checks that cannot be performed on the
834/// declaration itself, e.g., that the types of each of the function
835/// parameters are complete.
836bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
837 bool HasInvalidParm = false;
838 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
839 ParmVarDecl *Param = FD->getParamDecl(p);
840
841 // C99 6.7.5.3p4: the parameters in a parameter type list in a
842 // function declarator that is part of a function definition of
843 // that function shall not have incomplete type.
844 if (Param->getType()->isIncompleteType() &&
845 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000846 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000847 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000848 Param->setInvalidDecl();
849 HasInvalidParm = true;
850 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000851
852 // C99 6.9.1p5: If the declarator includes a parameter type list, the
853 // declaration of each parameter shall include an identifier.
854 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
855 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000856 }
857
858 return HasInvalidParm;
859}
860
Reid Spencer5f016e22007-07-11 17:01:13 +0000861/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
862/// no declarator (e.g. "struct foo;") is parsed.
863Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000864 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
865 if (!DS.isMissingDeclaratorOk()) {
866 // FIXME: This diagnostic is emitted even when various previous
867 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
868 // DeclSpec has no means of communicating this information, and the
869 // responsible parser functions are quite far apart.
870 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
871 << DS.getSourceRange();
872 return 0;
873 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000874
875 TagDecl *Tag
876 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
877 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
878 if (!Record->getDeclName() && Record->isDefinition() &&
879 !Record->isInvalidDecl())
880 return BuildAnonymousStructOrUnion(S, DS, Record);
881 }
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000882
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000883 return Tag;
884}
885
886/// InjectAnonymousStructOrUnionMembers - Inject the members of the
887/// anonymous struct or union AnonRecord into the owning context Owner
888/// and scope S. This routine will be invoked just after we realize
889/// that an unnamed union or struct is actually an anonymous union or
890/// struct, e.g.,
891///
892/// @code
893/// union {
894/// int i;
895/// float f;
896/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
897/// // f into the surrounding scope.x
898/// @endcode
899///
900/// This routine is recursive, injecting the names of nested anonymous
901/// structs/unions into the owning context and scope as well.
902bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
903 RecordDecl *AnonRecord) {
904 bool Invalid = false;
905 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
906 FEnd = AnonRecord->field_end();
907 F != FEnd; ++F) {
908 if ((*F)->getDeclName()) {
909 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
910 S, Owner, false, false, false);
911 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
912 // C++ [class.union]p2:
913 // The names of the members of an anonymous union shall be
914 // distinct from the names of any other entity in the
915 // scope in which the anonymous union is declared.
916 unsigned diagKind
917 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
918 : diag::err_anonymous_struct_member_redecl;
919 Diag((*F)->getLocation(), diagKind)
920 << (*F)->getDeclName();
921 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
922 Invalid = true;
923 } else {
924 // C++ [class.union]p2:
925 // For the purpose of name lookup, after the anonymous union
926 // definition, the members of the anonymous union are
927 // considered to have been defined in the scope in which the
928 // anonymous union is declared.
929 Owner->insert(Context, *F);
930 S->AddDecl(*F);
931 IdResolver.AddDecl(*F);
932 }
933 } else if (const RecordType *InnerRecordType
934 = (*F)->getType()->getAsRecordType()) {
935 RecordDecl *InnerRecord = InnerRecordType->getDecl();
936 if (InnerRecord->isAnonymousStructOrUnion())
937 Invalid = Invalid ||
938 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
939 }
940 }
941
942 return Invalid;
943}
944
945/// ActOnAnonymousStructOrUnion - Handle the declaration of an
946/// anonymous structure or union. Anonymous unions are a C++ feature
947/// (C++ [class.union]) and a GNU C extension; anonymous structures
948/// are a GNU C and GNU C++ extension.
949Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
950 RecordDecl *Record) {
951 DeclContext *Owner = Record->getDeclContext();
952
953 // Diagnose whether this anonymous struct/union is an extension.
954 if (Record->isUnion() && !getLangOptions().CPlusPlus)
955 Diag(Record->getLocation(), diag::ext_anonymous_union);
956 else if (!Record->isUnion())
957 Diag(Record->getLocation(), diag::ext_anonymous_struct);
958
959 // C and C++ require different kinds of checks for anonymous
960 // structs/unions.
961 bool Invalid = false;
962 if (getLangOptions().CPlusPlus) {
963 const char* PrevSpec = 0;
964 // C++ [class.union]p3:
965 // Anonymous unions declared in a named namespace or in the
966 // global namespace shall be declared static.
967 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
968 (isa<TranslationUnitDecl>(Owner) ||
969 (isa<NamespaceDecl>(Owner) &&
970 cast<NamespaceDecl>(Owner)->getDeclName()))) {
971 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
972 Invalid = true;
973
974 // Recover by adding 'static'.
975 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
976 }
977 // C++ [class.union]p3:
978 // A storage class is not allowed in a declaration of an
979 // anonymous union in a class scope.
980 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
981 isa<RecordDecl>(Owner)) {
982 Diag(DS.getStorageClassSpecLoc(),
983 diag::err_anonymous_union_with_storage_spec);
984 Invalid = true;
985
986 // Recover by removing the storage specifier.
987 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
988 PrevSpec);
989 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000990
991 // C++ [class.union]p2:
992 // The member-specification of an anonymous union shall only
993 // define non-static data members. [Note: nested types and
994 // functions cannot be declared within an anonymous union. ]
995 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
996 MemEnd = Record->decls_end();
997 Mem != MemEnd; ++Mem) {
998 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
999 // C++ [class.union]p3:
1000 // An anonymous union shall not have private or protected
1001 // members (clause 11).
1002 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1003 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1004 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1005 Invalid = true;
1006 }
1007 } else if ((*Mem)->isImplicit()) {
1008 // Any implicit members are fine.
1009 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1010 if (!MemRecord->isAnonymousStructOrUnion() &&
1011 MemRecord->getDeclName()) {
1012 // This is a nested type declaration.
1013 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1014 << (int)Record->isUnion();
1015 Invalid = true;
1016 }
1017 } else {
1018 // We have something that isn't a non-static data
1019 // member. Complain about it.
1020 unsigned DK = diag::err_anonymous_record_bad_member;
1021 if (isa<TypeDecl>(*Mem))
1022 DK = diag::err_anonymous_record_with_type;
1023 else if (isa<FunctionDecl>(*Mem))
1024 DK = diag::err_anonymous_record_with_function;
1025 else if (isa<VarDecl>(*Mem))
1026 DK = diag::err_anonymous_record_with_static;
1027 Diag((*Mem)->getLocation(), DK)
1028 << (int)Record->isUnion();
1029 Invalid = true;
1030 }
1031 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001032 } else {
1033 // FIXME: Check GNU C semantics
1034 }
1035
1036 if (!Record->isUnion() && !Owner->isRecord()) {
1037 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
1038 Invalid = true;
1039 }
1040
1041 // Create a declaration for this anonymous struct/union.
1042 ScopedDecl *Anon = 0;
1043 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1044 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1045 /*IdentifierInfo=*/0,
1046 Context.getTypeDeclType(Record),
1047 /*BitWidth=*/0, /*Mutable=*/false,
1048 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001049 Anon->setAccess(AS_public);
1050 if (getLangOptions().CPlusPlus)
1051 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001052 } else {
1053 VarDecl::StorageClass SC;
1054 switch (DS.getStorageClassSpec()) {
1055 default: assert(0 && "Unknown storage class!");
1056 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1057 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1058 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1059 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1060 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1061 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1062 case DeclSpec::SCS_mutable:
1063 // mutable can only appear on non-static class members, so it's always
1064 // an error here
1065 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1066 Invalid = true;
1067 SC = VarDecl::None;
1068 break;
1069 }
1070
1071 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1072 /*IdentifierInfo=*/0,
1073 Context.getTypeDeclType(Record),
1074 SC, /*FIXME:LastDeclarator=*/0,
1075 DS.getSourceRange().getBegin());
1076 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001077 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001078
1079 // Add the anonymous struct/union object to the current
1080 // context. We'll be referencing this object when we refer to one of
1081 // its members.
1082 Owner->addDecl(Context, Anon);
1083
1084 // Inject the members of the anonymous struct/union into the owning
1085 // context and into the identifier resolver chain for name lookup
1086 // purposes.
1087 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1088
1089 // Mark this as an anonymous struct/union type. Note that we do not
1090 // do this until after we have already checked and injected the
1091 // members of this anonymous struct/union type, because otherwise
1092 // the members could be injected twice: once by DeclContext when it
1093 // builds its lookup table, and once by
1094 // InjectAnonymousStructOrUnionMembers.
1095 Record->setAnonymousStructOrUnion(true);
1096
1097 if (Invalid)
1098 Anon->setInvalidDecl();
1099
1100 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101}
1102
Steve Naroffd0091aa2008-01-10 22:15:12 +00001103bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +00001104 // Get the type before calling CheckSingleAssignmentConstraints(), since
1105 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001106 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001107
1108 if (getLangOptions().CPlusPlus)
1109 return PerformCopyInitialization(Init, DeclType, "initializing");
1110
Chris Lattner5cf216b2008-01-04 18:04:52 +00001111 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1112 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1113 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001114}
1115
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001116bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001117 const ArrayType *AT = Context.getAsArrayType(DeclT);
1118
1119 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001120 // C99 6.7.8p14. We have an array of character type with unknown size
1121 // being initialized to a string literal.
1122 llvm::APSInt ConstVal(32);
1123 ConstVal = strLiteral->getByteLength() + 1;
1124 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001125 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001126 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001127 } else {
1128 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001129 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001130 // FIXME: Avoid truncation for 64-bit length strings.
1131 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001132 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001133 diag::warn_initializer_string_for_char_array_too_long)
1134 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001135 }
1136 // Set type from "char *" to "constant array of char".
1137 strLiteral->setType(DeclT);
1138 // For now, we always return false (meaning success).
1139 return false;
1140}
1141
1142StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001143 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001144 if (AT && AT->getElementType()->isCharType()) {
1145 return dyn_cast<StringLiteral>(Init);
1146 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001147 return 0;
1148}
1149
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001150bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1151 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001152 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001153 if (DeclType->isDependentType() || Init->isTypeDependent())
1154 return false;
1155
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001156 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001157 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001158 // (8.3.2), shall be initialized by an object, or function, of
1159 // type T or by an object that can be converted into a T.
1160 if (DeclType->isReferenceType())
1161 return CheckReferenceInit(Init, DeclType);
1162
Steve Naroffca107302008-01-21 23:53:58 +00001163 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1164 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001165 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001166 return Diag(InitLoc, diag::err_variable_object_no_init)
1167 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001168
Steve Naroff2fdc3742007-12-10 22:44:33 +00001169 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1170 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001171 // FIXME: Handle wide strings
1172 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1173 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001174
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001175 // C++ [dcl.init]p14:
1176 // -- If the destination type is a (possibly cv-qualified) class
1177 // type:
1178 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1179 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1180 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1181
1182 // -- If the initialization is direct-initialization, or if it is
1183 // copy-initialization where the cv-unqualified version of the
1184 // source type is the same class as, or a derived class of, the
1185 // class of the destination, constructors are considered.
1186 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1187 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1188 CXXConstructorDecl *Constructor
1189 = PerformInitializationByConstructor(DeclType, &Init, 1,
1190 InitLoc, Init->getSourceRange(),
1191 InitEntity, IK_Copy);
1192 return Constructor == 0;
1193 }
1194
1195 // -- Otherwise (i.e., for the remaining copy-initialization
1196 // cases), user-defined conversion sequences that can
1197 // convert from the source type to the destination type or
1198 // (when a conversion function is used) to a derived class
1199 // thereof are enumerated as described in 13.3.1.4, and the
1200 // best one is chosen through overload resolution
1201 // (13.3). If the conversion cannot be done or is
1202 // ambiguous, the initialization is ill-formed. The
1203 // function selected is called with the initializer
1204 // expression as its argument; if the function is a
1205 // constructor, the call initializes a temporary of the
1206 // destination type.
1207 // FIXME: We're pretending to do copy elision here; return to
1208 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001209 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001210 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001211
Douglas Gregor61366e92008-12-24 00:01:03 +00001212 if (InitEntity)
1213 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1214 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1215 << Init->getType() << Init->getSourceRange();
1216 else
1217 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1218 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1219 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001220 }
1221
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001222 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001223 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001224 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1225 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001226
Steve Naroffd0091aa2008-01-10 22:15:12 +00001227 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001228 } else if (getLangOptions().CPlusPlus) {
1229 // C++ [dcl.init]p14:
1230 // [...] If the class is an aggregate (8.5.1), and the initializer
1231 // is a brace-enclosed list, see 8.5.1.
1232 //
1233 // Note: 8.5.1 is handled below; here, we diagnose the case where
1234 // we have an initializer list and a destination type that is not
1235 // an aggregate.
1236 // FIXME: In C++0x, this is yet another form of initialization.
1237 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1238 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1239 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001240 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001241 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001242 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001243 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001244
Steve Naroff0cca7492008-05-01 22:18:59 +00001245 InitListChecker CheckInitList(this, InitList, DeclType);
1246 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001247}
1248
Douglas Gregor10bd3682008-11-17 22:58:34 +00001249/// GetNameForDeclarator - Determine the full declaration name for the
1250/// given Declarator.
1251DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1252 switch (D.getKind()) {
1253 case Declarator::DK_Abstract:
1254 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1255 return DeclarationName();
1256
1257 case Declarator::DK_Normal:
1258 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1259 return DeclarationName(D.getIdentifier());
1260
1261 case Declarator::DK_Constructor: {
1262 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1263 Ty = Context.getCanonicalType(Ty);
1264 return Context.DeclarationNames.getCXXConstructorName(Ty);
1265 }
1266
1267 case Declarator::DK_Destructor: {
1268 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1269 Ty = Context.getCanonicalType(Ty);
1270 return Context.DeclarationNames.getCXXDestructorName(Ty);
1271 }
1272
1273 case Declarator::DK_Conversion: {
1274 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1275 Ty = Context.getCanonicalType(Ty);
1276 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1277 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001278
1279 case Declarator::DK_Operator:
1280 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1281 return Context.DeclarationNames.getCXXOperatorName(
1282 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001283 }
1284
1285 assert(false && "Unknown name kind");
1286 return DeclarationName();
1287}
1288
Douglas Gregor584049d2008-12-15 23:53:10 +00001289/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1290/// functions Declaration and Definition are "nearly" matching. This
1291/// heuristic is used to improve diagnostics in the case where an
1292/// out-of-line member function definition doesn't match any
1293/// declaration within the class.
1294static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1295 FunctionDecl *Declaration,
1296 FunctionDecl *Definition) {
1297 if (Declaration->param_size() != Definition->param_size())
1298 return false;
1299 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1300 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1301 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1302
1303 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1304 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1305 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1306 return false;
1307 }
1308
1309 return true;
1310}
1311
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001312Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001313Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1314 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001315 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001316 DeclarationName Name = GetNameForDeclarator(D);
1317
Chris Lattnere80a59c2007-07-25 00:24:17 +00001318 // All of these full declarators require an identifier. If it doesn't have
1319 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001320 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001321 if (!D.getInvalidType()) // Reject this if we think it is valid.
1322 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001323 diag::err_declarator_need_ident)
1324 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001325 return 0;
1326 }
1327
Chris Lattner31e05722007-08-26 06:24:45 +00001328 // The scope passed in may not be a decl scope. Zip up the scope tree until
1329 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001330 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1331 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001332 S = S->getParent();
1333
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001334 DeclContext *DC;
1335 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001336 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001337 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001338
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001339 // See if this is a redefinition of a variable in the same scope.
1340 if (!D.getCXXScopeSpec().isSet()) {
1341 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001342 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001343 } else { // Something like "int foo::x;"
1344 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001345 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001346
1347 // C++ 7.3.1.2p2:
1348 // Members (including explicit specializations of templates) of a named
1349 // namespace can also be defined outside that namespace by explicit
1350 // qualification of the name being defined, provided that the entity being
1351 // defined was already declared in the namespace and the definition appears
1352 // after the point of declaration in a namespace that encloses the
1353 // declarations namespace.
1354 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001355 // Note that we only check the context at this point. We don't yet
1356 // have enough information to make sure that PrevDecl is actually
1357 // the declaration we want to match. For example, given:
1358 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001359 // class X {
1360 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001361 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001362 // };
1363 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001364 // void X::f(int) { } // ill-formed
1365 //
1366 // In this case, PrevDecl will point to the overload set
1367 // containing the two f's declared in X, but neither of them
1368 // matches.
1369 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001370 // The qualifying scope doesn't enclose the original declaration.
1371 // Emit diagnostic based on current scope.
1372 SourceLocation L = D.getIdentifierLoc();
1373 SourceRange R = D.getCXXScopeSpec().getRange();
1374 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001375 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001376 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001377 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001378 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001379 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001380 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001381 }
1382 }
1383
Douglas Gregorf57172b2008-12-08 18:40:42 +00001384 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001385 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001386 InvalidDecl = InvalidDecl
1387 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001388 // Just pretend that we didn't see the previous declaration.
1389 PrevDecl = 0;
1390 }
1391
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001392 // In C++, the previous declaration we find might be a tag type
1393 // (class or enum). In this case, the new declaration will hide the
1394 // tag type.
1395 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1396 PrevDecl = 0;
1397
Chris Lattner41af0932007-11-14 06:34:38 +00001398 QualType R = GetTypeForDeclarator(D, S);
1399 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1400
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001402 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1403 if (D.getCXXScopeSpec().isSet()) {
1404 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1405 << D.getCXXScopeSpec().getRange();
1406 InvalidDecl = true;
1407 // Pretend we didn't see the scope specifier.
1408 DC = 0;
1409 }
1410
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
Chris Lattner41af0932007-11-14 06:34:38 +00001415 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 if (!NewTD) return 0;
1417
1418 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001419 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001420 // Merge the decl with the existing one if appropriate. If the decl is
1421 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001422 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1424 if (NewTD == 0) return 0;
1425 }
1426 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001427 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1429 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001430 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001431 if (NewTD->getUnderlyingType()->isVariableArrayType())
1432 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1433 else
1434 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1435
Steve Naroffd7444aa2007-08-31 17:20:07 +00001436 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 }
1438 }
Chris Lattner41af0932007-11-14 06:34:38 +00001439 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001440 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 switch (D.getDeclSpec().getStorageClassSpec()) {
1442 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001443 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001445 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001446 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001447 InvalidDecl = true;
1448 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1450 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1451 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001452 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 }
1454
Chris Lattnera98e58d2008-03-15 21:24:04 +00001455 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001456 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001457 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1458
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001460 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001461 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001462 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001463 "Constructors can only be declared in a member context");
1464
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001465 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001466
1467 // Create the new declaration
1468 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001469 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001470 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001471 isExplicit, isInline,
1472 /*isImplicitlyDeclared=*/false);
1473
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001474 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001475 NewFD->setInvalidDecl();
1476 } else if (D.getKind() == Declarator::DK_Destructor) {
1477 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001478 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001479 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001480
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001481 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001482 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001483 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001484 isInline,
1485 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001486
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001487 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001488 NewFD->setInvalidDecl();
1489 } else {
1490 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001491
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001492 // Create a FunctionDecl to satisfy the function definition parsing
1493 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001494 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001495 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001496 // FIXME: Move to DeclGroup...
1497 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001498 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001499 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001500 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001501 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001502 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001503 Diag(D.getIdentifierLoc(),
1504 diag::err_conv_function_not_member);
1505 return 0;
1506 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001507 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001508
Douglas Gregor70316a02008-12-26 15:00:45 +00001509 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001510 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001511 isInline, isExplicit);
1512
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001513 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001514 NewFD->setInvalidDecl();
1515 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001516 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001517 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001518 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001519 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001520 (SC == FunctionDecl::Static), isInline,
1521 LastDeclarator);
1522 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001523 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001524 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001525 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001526 // FIXME: Move to DeclGroup...
1527 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001528 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001529
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001530 // Set the lexical context. If the declarator has a C++
1531 // scope specifier, the lexical context will be different
1532 // from the semantic context.
1533 NewFD->setLexicalDeclContext(CurContext);
1534
Daniel Dunbara80f8742008-08-05 01:35:17 +00001535 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001536 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001537 // The parser guarantees this is a string.
1538 StringLiteral *SE = cast<StringLiteral>(E);
1539 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1540 SE->getByteLength())));
1541 }
1542
Chris Lattner04421082008-04-08 04:40:51 +00001543 // Copy the parameter declarations from the declarator D to
1544 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001545 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1547
1548 // Create Decl objects for each parameter, adding them to the
1549 // FunctionDecl.
1550 llvm::SmallVector<ParmVarDecl*, 16> Params;
1551
1552 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1553 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001554 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001555 // We let through "const void" here because Sema::GetTypeForDeclarator
1556 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001557 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1558 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001559 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1560 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001561 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1562
Chris Lattnerdef026a2008-04-10 02:26:16 +00001563 // In C++, the empty parameter-type-list must be spelled "void"; a
1564 // typedef of void is not permitted.
1565 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001566 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001567 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1568 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001569 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001570 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1571 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1572 }
1573
1574 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001575 } else if (R->getAsTypedefType()) {
1576 // When we're declaring a function with a typedef, as in the
1577 // following example, we'll need to synthesize (unnamed)
1578 // parameters for use in the declaration.
1579 //
1580 // @code
1581 // typedef void fn(int);
1582 // fn f;
1583 // @endcode
1584 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1585 if (!FT) {
1586 // This is a typedef of a function with no prototype, so we
1587 // don't need to do anything.
1588 } else if ((FT->getNumArgs() == 0) ||
1589 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1590 FT->getArgType(0)->isVoidType())) {
1591 // This is a zero-argument function. We don't need to do anything.
1592 } else {
1593 // Synthesize a parameter for each argument type.
1594 llvm::SmallVector<ParmVarDecl*, 16> Params;
1595 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1596 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001597 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001598 SourceLocation(), 0,
1599 *ArgType, VarDecl::None,
1600 0, 0));
1601 }
1602
1603 NewFD->setParams(&Params[0], Params.size());
1604 }
Chris Lattner04421082008-04-08 04:40:51 +00001605 }
1606
Douglas Gregor72b505b2008-12-16 21:30:33 +00001607 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1608 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001609 else if (isa<CXXDestructorDecl>(NewFD)) {
1610 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1611 Record->setUserDeclaredDestructor(true);
1612 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1613 // user-defined destructor.
1614 Record->setPOD(false);
1615 } else if (CXXConversionDecl *Conversion =
1616 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001617 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001618
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001619 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1620 if (NewFD->isOverloadedOperator() &&
1621 CheckOverloadedOperatorDeclaration(NewFD))
1622 NewFD->setInvalidDecl();
1623
Steve Naroffffce4d52008-01-09 23:34:55 +00001624 // Merge the decl with the existing one if appropriate. Since C functions
1625 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001626 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001627 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001628 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001629
1630 // If C++, determine whether NewFD is an overload of PrevDecl or
1631 // a declaration that requires merging. If it's an overload,
1632 // there's no more work to do here; we'll just add the new
1633 // function to the scope.
1634 OverloadedFunctionDecl::function_iterator MatchedDecl;
1635 if (!getLangOptions().CPlusPlus ||
1636 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1637 Decl *OldDecl = PrevDecl;
1638
1639 // If PrevDecl was an overloaded function, extract the
1640 // FunctionDecl that matched.
1641 if (isa<OverloadedFunctionDecl>(PrevDecl))
1642 OldDecl = *MatchedDecl;
1643
1644 // NewFD and PrevDecl represent declarations that need to be
1645 // merged.
1646 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1647
1648 if (NewFD == 0) return 0;
1649 if (Redeclaration) {
1650 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1651
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001652 // An out-of-line member function declaration must also be a
1653 // definition (C++ [dcl.meaning]p1).
1654 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1655 !InvalidDecl) {
1656 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1657 << D.getCXXScopeSpec().getRange();
1658 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659 }
1660 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001661 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001662
1663 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1664 // The user tried to provide an out-of-line definition for a
1665 // member function, but there was no such member function
1666 // declared (C++ [class.mfct]p2). For example:
1667 //
1668 // class X {
1669 // void f() const;
1670 // };
1671 //
1672 // void X::f() { } // ill-formed
1673 //
1674 // Complain about this problem, and attempt to suggest close
1675 // matches (e.g., those that differ only in cv-qualifiers and
1676 // whether the parameter types are references).
1677 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1678 << cast<CXXRecordDecl>(DC)->getDeclName()
1679 << D.getCXXScopeSpec().getRange();
1680 InvalidDecl = true;
1681
1682 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1683 if (!PrevDecl) {
1684 // Nothing to suggest.
1685 } else if (OverloadedFunctionDecl *Ovl
1686 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1687 for (OverloadedFunctionDecl::function_iterator
1688 Func = Ovl->function_begin(),
1689 FuncEnd = Ovl->function_end();
1690 Func != FuncEnd; ++Func) {
1691 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1692 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1693
1694 }
1695 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1696 // Suggest this no matter how mismatched it is; it's the only
1697 // thing we have.
1698 unsigned diag;
1699 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1700 diag = diag::note_member_def_close_match;
1701 else if (Method->getBody())
1702 diag = diag::note_previous_definition;
1703 else
1704 diag = diag::note_previous_declaration;
1705 Diag(Method->getLocation(), diag);
1706 }
1707
1708 PrevDecl = 0;
1709 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001711 // Handle attributes. We need to have merged decls when handling attributes
1712 // (for example to check for conflicts, etc).
1713 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001714 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001715
Douglas Gregor584049d2008-12-15 23:53:10 +00001716 if (getLangOptions().CPlusPlus) {
1717 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001718 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001719
1720 // An out-of-line member function declaration must also be a
1721 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001722 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001723 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1724 << D.getCXXScopeSpec().getRange();
1725 InvalidDecl = true;
1726 }
1727 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001729 // Check that there are no default arguments (C++ only).
1730 if (getLangOptions().CPlusPlus)
1731 CheckExtraCXXDefaultArguments(D);
1732
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001733 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001734 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1735 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001736 InvalidDecl = true;
1737 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001738
1739 VarDecl *NewVD;
1740 VarDecl::StorageClass SC;
1741 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001742 default: assert(0 && "Unknown storage class!");
1743 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1744 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1745 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1746 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1747 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1748 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001749 case DeclSpec::SCS_mutable:
1750 // mutable can only appear on non-static class members, so it's always
1751 // an error here
1752 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1753 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001754 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001755 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001756 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001757
1758 IdentifierInfo *II = Name.getAsIdentifierInfo();
1759 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001760 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1761 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001762 return 0;
1763 }
1764
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001765 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001766 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001767 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001768 D.getIdentifierLoc(), II,
1769 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001770 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001771 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001772 if (S->getFnParent() == 0) {
1773 // C99 6.9p2: The storage-class specifiers auto and register shall not
1774 // appear in the declaration specifiers in an external declaration.
1775 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001776 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001777 InvalidDecl = true;
1778 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001779 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001780 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1781 II, R, SC, LastDeclarator,
1782 // FIXME: Move to DeclGroup...
1783 D.getDeclSpec().getSourceRange().getBegin());
1784 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001785 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001787 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001788
Daniel Dunbara735ad82008-08-06 00:03:29 +00001789 // Handle GNU asm-label extension (encoded as an attribute).
1790 if (Expr *E = (Expr*) D.getAsmLabel()) {
1791 // The parser guarantees this is a string.
1792 StringLiteral *SE = cast<StringLiteral>(E);
1793 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1794 SE->getByteLength())));
1795 }
1796
Nate Begemanc8e89a82008-03-14 18:07:10 +00001797 // Emit an error if an address space was applied to decl with local storage.
1798 // This includes arrays of objects with address space qualifiers, but not
1799 // automatic variables that point to other address spaces.
1800 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001801 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1802 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1803 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001804 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001805 // Merge the decl with the existing one if appropriate. If the decl is
1806 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001807 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001808 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1809 // The user tried to define a non-static data member
1810 // out-of-line (C++ [dcl.meaning]p1).
1811 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1812 << D.getCXXScopeSpec().getRange();
1813 NewVD->Destroy(Context);
1814 return 0;
1815 }
1816
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 NewVD = MergeVarDecl(NewVD, PrevDecl);
1818 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001819
1820 if (D.getCXXScopeSpec().isSet()) {
1821 // No previous declaration in the qualifying scope.
1822 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1823 << Name << D.getCXXScopeSpec().getRange();
1824 InvalidDecl = true;
1825 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001826 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001827 New = NewVD;
1828 }
1829
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001830 // Set the lexical context. If the declarator has a C++ scope specifier, the
1831 // lexical context will be different from the semantic context.
1832 New->setLexicalDeclContext(CurContext);
1833
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001835 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001836 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001837 // If any semantic error occurred, mark the decl as invalid.
1838 if (D.getInvalidType() || InvalidDecl)
1839 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001840
1841 return New;
1842}
1843
Steve Naroff6594a702008-10-27 11:34:16 +00001844void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001845 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1846 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001847}
1848
Eli Friedmanc594b322008-05-20 13:48:25 +00001849bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1850 switch (Init->getStmtClass()) {
1851 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001852 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001853 return true;
1854 case Expr::ParenExprClass: {
1855 const ParenExpr* PE = cast<ParenExpr>(Init);
1856 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1857 }
1858 case Expr::CompoundLiteralExprClass:
1859 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001860 case Expr::DeclRefExprClass:
1861 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001862 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001863 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1864 if (VD->hasGlobalStorage())
1865 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001866 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001867 return true;
1868 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001869 if (isa<FunctionDecl>(D))
1870 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001871 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001872 return true;
1873 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001874 case Expr::MemberExprClass: {
1875 const MemberExpr *M = cast<MemberExpr>(Init);
1876 if (M->isArrow())
1877 return CheckAddressConstantExpression(M->getBase());
1878 return CheckAddressConstantExpressionLValue(M->getBase());
1879 }
1880 case Expr::ArraySubscriptExprClass: {
1881 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1882 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1883 return CheckAddressConstantExpression(ASE->getBase()) ||
1884 CheckArithmeticConstantExpression(ASE->getIdx());
1885 }
1886 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001887 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001888 return false;
1889 case Expr::UnaryOperatorClass: {
1890 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1891
1892 // C99 6.6p9
1893 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001894 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001895
Steve Naroff6594a702008-10-27 11:34:16 +00001896 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001897 return true;
1898 }
1899 }
1900}
1901
1902bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1903 switch (Init->getStmtClass()) {
1904 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001905 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001906 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001907 case Expr::ParenExprClass:
1908 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001909 case Expr::StringLiteralClass:
1910 case Expr::ObjCStringLiteralClass:
1911 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001912 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001913 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001914 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1915 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1916 Builtin::BI__builtin___CFStringMakeConstantString)
1917 return false;
1918
Steve Naroff6594a702008-10-27 11:34:16 +00001919 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001920 return true;
1921
Eli Friedmanc594b322008-05-20 13:48:25 +00001922 case Expr::UnaryOperatorClass: {
1923 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1924
1925 // C99 6.6p9
1926 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1927 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1928
1929 if (Exp->getOpcode() == UnaryOperator::Extension)
1930 return CheckAddressConstantExpression(Exp->getSubExpr());
1931
Steve Naroff6594a702008-10-27 11:34:16 +00001932 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001933 return true;
1934 }
1935 case Expr::BinaryOperatorClass: {
1936 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1937 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1938
1939 Expr *PExp = Exp->getLHS();
1940 Expr *IExp = Exp->getRHS();
1941 if (IExp->getType()->isPointerType())
1942 std::swap(PExp, IExp);
1943
1944 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1945 return CheckAddressConstantExpression(PExp) ||
1946 CheckArithmeticConstantExpression(IExp);
1947 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001948 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001949 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001950 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001951 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1952 // Check for implicit promotion
1953 if (SubExpr->getType()->isFunctionType() ||
1954 SubExpr->getType()->isArrayType())
1955 return CheckAddressConstantExpressionLValue(SubExpr);
1956 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001957
1958 // Check for pointer->pointer cast
1959 if (SubExpr->getType()->isPointerType())
1960 return CheckAddressConstantExpression(SubExpr);
1961
Eli Friedmanc3f07642008-08-25 20:46:57 +00001962 if (SubExpr->getType()->isIntegralType()) {
1963 // Check for the special-case of a pointer->int->pointer cast;
1964 // this isn't standard, but some code requires it. See
1965 // PR2720 for an example.
1966 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1967 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1968 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1969 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1970 if (IntWidth >= PointerWidth) {
1971 return CheckAddressConstantExpression(SubCast->getSubExpr());
1972 }
1973 }
1974 }
1975 }
1976 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001977 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001978 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001979
Steve Naroff6594a702008-10-27 11:34:16 +00001980 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001981 return true;
1982 }
1983 case Expr::ConditionalOperatorClass: {
1984 // FIXME: Should we pedwarn here?
1985 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1986 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001987 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001988 return true;
1989 }
1990 if (CheckArithmeticConstantExpression(Exp->getCond()))
1991 return true;
1992 if (Exp->getLHS() &&
1993 CheckAddressConstantExpression(Exp->getLHS()))
1994 return true;
1995 return CheckAddressConstantExpression(Exp->getRHS());
1996 }
1997 case Expr::AddrLabelExprClass:
1998 return false;
1999 }
2000}
2001
Eli Friedman4caf0552008-06-09 05:05:07 +00002002static const Expr* FindExpressionBaseAddress(const Expr* E);
2003
2004static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
2005 switch (E->getStmtClass()) {
2006 default:
2007 return E;
2008 case Expr::ParenExprClass: {
2009 const ParenExpr* PE = cast<ParenExpr>(E);
2010 return FindExpressionBaseAddressLValue(PE->getSubExpr());
2011 }
2012 case Expr::MemberExprClass: {
2013 const MemberExpr *M = cast<MemberExpr>(E);
2014 if (M->isArrow())
2015 return FindExpressionBaseAddress(M->getBase());
2016 return FindExpressionBaseAddressLValue(M->getBase());
2017 }
2018 case Expr::ArraySubscriptExprClass: {
2019 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
2020 return FindExpressionBaseAddress(ASE->getBase());
2021 }
2022 case Expr::UnaryOperatorClass: {
2023 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2024
2025 if (Exp->getOpcode() == UnaryOperator::Deref)
2026 return FindExpressionBaseAddress(Exp->getSubExpr());
2027
2028 return E;
2029 }
2030 }
2031}
2032
2033static const Expr* FindExpressionBaseAddress(const Expr* E) {
2034 switch (E->getStmtClass()) {
2035 default:
2036 return E;
2037 case Expr::ParenExprClass: {
2038 const ParenExpr* PE = cast<ParenExpr>(E);
2039 return FindExpressionBaseAddress(PE->getSubExpr());
2040 }
2041 case Expr::UnaryOperatorClass: {
2042 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2043
2044 // C99 6.6p9
2045 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2046 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2047
2048 if (Exp->getOpcode() == UnaryOperator::Extension)
2049 return FindExpressionBaseAddress(Exp->getSubExpr());
2050
2051 return E;
2052 }
2053 case Expr::BinaryOperatorClass: {
2054 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2055
2056 Expr *PExp = Exp->getLHS();
2057 Expr *IExp = Exp->getRHS();
2058 if (IExp->getType()->isPointerType())
2059 std::swap(PExp, IExp);
2060
2061 return FindExpressionBaseAddress(PExp);
2062 }
2063 case Expr::ImplicitCastExprClass: {
2064 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2065
2066 // Check for implicit promotion
2067 if (SubExpr->getType()->isFunctionType() ||
2068 SubExpr->getType()->isArrayType())
2069 return FindExpressionBaseAddressLValue(SubExpr);
2070
2071 // Check for pointer->pointer cast
2072 if (SubExpr->getType()->isPointerType())
2073 return FindExpressionBaseAddress(SubExpr);
2074
2075 // We assume that we have an arithmetic expression here;
2076 // if we don't, we'll figure it out later
2077 return 0;
2078 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002079 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002080 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2081
2082 // Check for pointer->pointer cast
2083 if (SubExpr->getType()->isPointerType())
2084 return FindExpressionBaseAddress(SubExpr);
2085
2086 // We assume that we have an arithmetic expression here;
2087 // if we don't, we'll figure it out later
2088 return 0;
2089 }
2090 }
2091}
2092
Anders Carlsson51fe9962008-11-22 21:04:56 +00002093bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002094 switch (Init->getStmtClass()) {
2095 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002096 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002097 return true;
2098 case Expr::ParenExprClass: {
2099 const ParenExpr* PE = cast<ParenExpr>(Init);
2100 return CheckArithmeticConstantExpression(PE->getSubExpr());
2101 }
2102 case Expr::FloatingLiteralClass:
2103 case Expr::IntegerLiteralClass:
2104 case Expr::CharacterLiteralClass:
2105 case Expr::ImaginaryLiteralClass:
2106 case Expr::TypesCompatibleExprClass:
2107 case Expr::CXXBoolLiteralExprClass:
2108 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002109 case Expr::CallExprClass:
2110 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002111 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002112
2113 // Allow any constant foldable calls to builtins.
2114 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002115 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002116
Steve Naroff6594a702008-10-27 11:34:16 +00002117 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002118 return true;
2119 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002120 case Expr::DeclRefExprClass:
2121 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002122 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2123 if (isa<EnumConstantDecl>(D))
2124 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002125 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002126 return true;
2127 }
2128 case Expr::CompoundLiteralExprClass:
2129 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2130 // but vectors are allowed to be magic.
2131 if (Init->getType()->isVectorType())
2132 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002133 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002134 return true;
2135 case Expr::UnaryOperatorClass: {
2136 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2137
2138 switch (Exp->getOpcode()) {
2139 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2140 // See C99 6.6p3.
2141 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002142 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002143 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002144 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002145 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2146 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002147 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002148 return true;
2149 case UnaryOperator::Extension:
2150 case UnaryOperator::LNot:
2151 case UnaryOperator::Plus:
2152 case UnaryOperator::Minus:
2153 case UnaryOperator::Not:
2154 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2155 }
2156 }
Sebastian Redl05189992008-11-11 17:56:53 +00002157 case Expr::SizeOfAlignOfExprClass: {
2158 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002159 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002160 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002161 return false;
2162 // alignof always evaluates to a constant.
2163 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002164 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002165 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002166 return true;
2167 }
2168 return false;
2169 }
2170 case Expr::BinaryOperatorClass: {
2171 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2172
2173 if (Exp->getLHS()->getType()->isArithmeticType() &&
2174 Exp->getRHS()->getType()->isArithmeticType()) {
2175 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2176 CheckArithmeticConstantExpression(Exp->getRHS());
2177 }
2178
Eli Friedman4caf0552008-06-09 05:05:07 +00002179 if (Exp->getLHS()->getType()->isPointerType() &&
2180 Exp->getRHS()->getType()->isPointerType()) {
2181 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2182 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2183
2184 // Only allow a null (constant integer) base; we could
2185 // allow some additional cases if necessary, but this
2186 // is sufficient to cover offsetof-like constructs.
2187 if (!LHSBase && !RHSBase) {
2188 return CheckAddressConstantExpression(Exp->getLHS()) ||
2189 CheckAddressConstantExpression(Exp->getRHS());
2190 }
2191 }
2192
Steve Naroff6594a702008-10-27 11:34:16 +00002193 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002194 return true;
2195 }
2196 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002197 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002198 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002199 if (SubExpr->getType()->isArithmeticType())
2200 return CheckArithmeticConstantExpression(SubExpr);
2201
Eli Friedmanb529d832008-09-02 09:37:00 +00002202 if (SubExpr->getType()->isPointerType()) {
2203 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2204 // If the pointer has a null base, this is an offsetof-like construct
2205 if (!Base)
2206 return CheckAddressConstantExpression(SubExpr);
2207 }
2208
Steve Naroff6594a702008-10-27 11:34:16 +00002209 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002210 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002211 }
2212 case Expr::ConditionalOperatorClass: {
2213 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002214
2215 // If GNU extensions are disabled, we require all operands to be arithmetic
2216 // constant expressions.
2217 if (getLangOptions().NoExtensions) {
2218 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2219 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2220 CheckArithmeticConstantExpression(Exp->getRHS());
2221 }
2222
2223 // Otherwise, we have to emulate some of the behavior of fold here.
2224 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2225 // because it can constant fold things away. To retain compatibility with
2226 // GCC code, we see if we can fold the condition to a constant (which we
2227 // should always be able to do in theory). If so, we only require the
2228 // specified arm of the conditional to be a constant. This is a horrible
2229 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002230 Expr::EvalResult EvalResult;
2231 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2232 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002233 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002234 // won't be able to either. Use it to emit the diagnostic though.
2235 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002236 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002237 return Res;
2238 }
2239
2240 // Verify that the side following the condition is also a constant.
2241 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002242 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002243 std::swap(TrueSide, FalseSide);
2244
2245 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002246 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002247
2248 // Okay, the evaluated side evaluates to a constant, so we accept this.
2249 // Check to see if the other side is obviously not a constant. If so,
2250 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002251 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002252 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002253 diag::ext_typecheck_expression_not_constant_but_accepted)
2254 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002255 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002256 }
2257 }
2258}
2259
2260bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002261 Expr::EvalResult Result;
2262
Nuno Lopes9a979c32008-07-07 16:46:50 +00002263 Init = Init->IgnoreParens();
2264
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002265 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2266 return false;
2267
Eli Friedmanc594b322008-05-20 13:48:25 +00002268 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2269 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2270 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2271
Nuno Lopes9a979c32008-07-07 16:46:50 +00002272 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2273 return CheckForConstantInitializer(e->getInitializer(), DclT);
2274
Eli Friedmanc594b322008-05-20 13:48:25 +00002275 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2276 unsigned numInits = Exp->getNumInits();
2277 for (unsigned i = 0; i < numInits; i++) {
2278 // FIXME: Need to get the type of the declaration for C++,
2279 // because it could be a reference?
2280 if (CheckForConstantInitializer(Exp->getInit(i),
2281 Exp->getInit(i)->getType()))
2282 return true;
2283 }
2284 return false;
2285 }
2286
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002287 // FIXME: We can probably remove some of this code below, now that
2288 // Expr::Evaluate is doing the heavy lifting for scalars.
2289
Eli Friedmanc594b322008-05-20 13:48:25 +00002290 if (Init->isNullPointerConstant(Context))
2291 return false;
2292 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002293 QualType InitTy = Context.getCanonicalType(Init->getType())
2294 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002295 if (InitTy == Context.BoolTy) {
2296 // Special handling for pointers implicitly cast to bool;
2297 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2298 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2299 Expr* SubE = ICE->getSubExpr();
2300 if (SubE->getType()->isPointerType() ||
2301 SubE->getType()->isArrayType() ||
2302 SubE->getType()->isFunctionType()) {
2303 return CheckAddressConstantExpression(Init);
2304 }
2305 }
2306 } else if (InitTy->isIntegralType()) {
2307 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002308 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002309 SubE = CE->getSubExpr();
2310 // Special check for pointer cast to int; we allow as an extension
2311 // an address constant cast to an integer if the integer
2312 // is of an appropriate width (this sort of code is apparently used
2313 // in some places).
2314 // FIXME: Add pedwarn?
2315 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2316 if (SubE && (SubE->getType()->isPointerType() ||
2317 SubE->getType()->isArrayType() ||
2318 SubE->getType()->isFunctionType())) {
2319 unsigned IntWidth = Context.getTypeSize(Init->getType());
2320 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2321 if (IntWidth >= PointerWidth)
2322 return CheckAddressConstantExpression(Init);
2323 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002324 }
2325
2326 return CheckArithmeticConstantExpression(Init);
2327 }
2328
2329 if (Init->getType()->isPointerType())
2330 return CheckAddressConstantExpression(Init);
2331
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002332 // An array type at the top level that isn't an init-list must
2333 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002334 if (Init->getType()->isArrayType())
2335 return false;
2336
Nuno Lopes73419bf2008-09-01 18:42:41 +00002337 if (Init->getType()->isFunctionType())
2338 return false;
2339
Steve Naroff8af6a452008-10-02 17:12:56 +00002340 // Allow block exprs at top level.
2341 if (Init->getType()->isBlockPointerType())
2342 return false;
2343
Steve Naroff6594a702008-10-27 11:34:16 +00002344 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002345 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002346}
2347
Sebastian Redl798d1192008-12-13 16:23:55 +00002348void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002349 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002350 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002351 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002352
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002353 // If there is no declaration, there was an error parsing it. Just ignore
2354 // the initializer.
2355 if (RealDecl == 0) {
2356 delete Init;
2357 return;
2358 }
Steve Naroffbb204692007-09-12 14:07:44 +00002359
Steve Naroff410e3e22007-09-12 20:13:48 +00002360 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2361 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002362 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2363 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002364 RealDecl->setInvalidDecl();
2365 return;
2366 }
Steve Naroffbb204692007-09-12 14:07:44 +00002367 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002368 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002369 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002370 if (VDecl->isBlockVarDecl()) {
2371 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002372 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002373 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002374 VDecl->setInvalidDecl();
2375 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002376 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002377 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002378 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002379
2380 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2381 if (!getLangOptions().CPlusPlus) {
2382 if (SC == VarDecl::Static) // C99 6.7.8p4.
2383 CheckForConstantInitializer(Init, DclT);
2384 }
Steve Naroffbb204692007-09-12 14:07:44 +00002385 }
Steve Naroff248a7532008-04-15 22:42:06 +00002386 } else if (VDecl->isFileVarDecl()) {
2387 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002388 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002389 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002390 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002391 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002392 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002393
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002394 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2395 if (!getLangOptions().CPlusPlus) {
2396 // C99 6.7.8p4. All file scoped initializers need to be constant.
2397 CheckForConstantInitializer(Init, DclT);
2398 }
Steve Naroffbb204692007-09-12 14:07:44 +00002399 }
2400 // If the type changed, it means we had an incomplete type that was
2401 // completed by the initializer. For example:
2402 // int ary[] = { 1, 3, 5 };
2403 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002404 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002405 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002406 Init->setType(DclT);
2407 }
Steve Naroffbb204692007-09-12 14:07:44 +00002408
2409 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002410 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002411 return;
2412}
2413
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002414void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2415 Decl *RealDecl = static_cast<Decl *>(dcl);
2416
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002417 // If there is no declaration, there was an error parsing it. Just ignore it.
2418 if (RealDecl == 0)
2419 return;
2420
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002421 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2422 QualType Type = Var->getType();
2423 // C++ [dcl.init.ref]p3:
2424 // The initializer can be omitted for a reference only in a
2425 // parameter declaration (8.3.5), in the declaration of a
2426 // function return type, in the declaration of a class member
2427 // within its class declaration (9.2), and where the extern
2428 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002429 if (Type->isReferenceType() &&
2430 Var->getStorageClass() != VarDecl::Extern &&
2431 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002432 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002433 << Var->getDeclName()
2434 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002435 Var->setInvalidDecl();
2436 return;
2437 }
2438
2439 // C++ [dcl.init]p9:
2440 //
2441 // If no initializer is specified for an object, and the object
2442 // is of (possibly cv-qualified) non-POD class type (or array
2443 // thereof), the object shall be default-initialized; if the
2444 // object is of const-qualified type, the underlying class type
2445 // shall have a user-declared default constructor.
2446 if (getLangOptions().CPlusPlus) {
2447 QualType InitType = Type;
2448 if (const ArrayType *Array = Context.getAsArrayType(Type))
2449 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002450 if (Var->getStorageClass() != VarDecl::Extern &&
2451 Var->getStorageClass() != VarDecl::PrivateExtern &&
2452 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002453 const CXXConstructorDecl *Constructor
2454 = PerformInitializationByConstructor(InitType, 0, 0,
2455 Var->getLocation(),
2456 SourceRange(Var->getLocation(),
2457 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002458 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002459 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002460 if (!Constructor)
2461 Var->setInvalidDecl();
2462 }
2463 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002464
Douglas Gregor818ce482008-10-29 13:50:18 +00002465#if 0
2466 // FIXME: Temporarily disabled because we are not properly parsing
2467 // linkage specifications on declarations, e.g.,
2468 //
2469 // extern "C" const CGPoint CGPointerZero;
2470 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002471 // C++ [dcl.init]p9:
2472 //
2473 // If no initializer is specified for an object, and the
2474 // object is of (possibly cv-qualified) non-POD class type (or
2475 // array thereof), the object shall be default-initialized; if
2476 // the object is of const-qualified type, the underlying class
2477 // type shall have a user-declared default
2478 // constructor. Otherwise, if no initializer is specified for
2479 // an object, the object and its subobjects, if any, have an
2480 // indeterminate initial value; if the object or any of its
2481 // subobjects are of const-qualified type, the program is
2482 // ill-formed.
2483 //
2484 // This isn't technically an error in C, so we don't diagnose it.
2485 //
2486 // FIXME: Actually perform the POD/user-defined default
2487 // constructor check.
2488 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002489 Context.getCanonicalType(Type).isConstQualified() &&
2490 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002491 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2492 << Var->getName()
2493 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002494#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002495 }
2496}
2497
Reid Spencer5f016e22007-07-11 17:01:13 +00002498/// The declarators are chained together backwards, reverse the list.
2499Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2500 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002501 Decl *GroupDecl = static_cast<Decl*>(group);
2502 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002503 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002504
2505 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2506 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002507 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002508 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002509 else { // reverse the list.
2510 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002511 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002512 Group->setNextDeclarator(NewGroup);
2513 NewGroup = Group;
2514 Group = Next;
2515 }
2516 }
2517 // Perform semantic analysis that depends on having fully processed both
2518 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002519 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002520 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2521 if (!IDecl)
2522 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002523 QualType T = IDecl->getType();
2524
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002525 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002526 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002527
2528 // FIXME: This won't give the correct result for
2529 // int a[10][n];
2530 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002531 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002532 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2533 SizeRange;
2534
Eli Friedmanc5773c42008-02-15 18:16:39 +00002535 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002536 } else {
2537 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2538 // static storage duration, it shall not have a variable length array.
2539 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002540 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2541 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002542 IDecl->setInvalidDecl();
2543 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002544 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2545 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002546 IDecl->setInvalidDecl();
2547 }
2548 }
2549 } else if (T->isVariablyModifiedType()) {
2550 if (IDecl->isFileVarDecl()) {
2551 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2552 IDecl->setInvalidDecl();
2553 } else {
2554 if (IDecl->getStorageClass() == VarDecl::Extern) {
2555 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2556 IDecl->setInvalidDecl();
2557 }
Steve Naroffbb204692007-09-12 14:07:44 +00002558 }
2559 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002560
Steve Naroffbb204692007-09-12 14:07:44 +00002561 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2562 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002563 if (IDecl->isBlockVarDecl() &&
2564 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002565 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002566 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002567 IDecl->setInvalidDecl();
2568 }
2569 }
2570 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2571 // object that has file scope without an initializer, and without a
2572 // storage-class specifier or with the storage-class specifier "static",
2573 // constitutes a tentative definition. Note: A tentative definition with
2574 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002575 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002576 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002577 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2578 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002579 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002580 // C99 6.9.2p3: If the declaration of an identifier for an object is
2581 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2582 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002583 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002584 IDecl->setInvalidDecl();
2585 }
2586 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002587 if (IDecl->isFileVarDecl())
2588 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 }
2590 return NewGroup;
2591}
Steve Naroffe1223f72007-08-28 03:03:08 +00002592
Chris Lattner04421082008-04-08 04:40:51 +00002593/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2594/// to introduce parameters into function prototype scope.
2595Sema::DeclTy *
2596Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002597 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002598
Chris Lattner04421082008-04-08 04:40:51 +00002599 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002600 VarDecl::StorageClass StorageClass = VarDecl::None;
2601 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2602 StorageClass = VarDecl::Register;
2603 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002604 Diag(DS.getStorageClassSpecLoc(),
2605 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002606 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002607 }
2608 if (DS.isThreadSpecified()) {
2609 Diag(DS.getThreadSpecLoc(),
2610 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002611 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002612 }
2613
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002614 // Check that there are no default arguments inside the type of this
2615 // parameter (C++ only).
2616 if (getLangOptions().CPlusPlus)
2617 CheckExtraCXXDefaultArguments(D);
2618
Chris Lattner04421082008-04-08 04:40:51 +00002619 // In this context, we *do not* check D.getInvalidType(). If the declarator
2620 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2621 // though it will not reflect the user specified type.
2622 QualType parmDeclType = GetTypeForDeclarator(D, S);
2623
2624 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2625
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2627 // Can this happen for params? We already checked that they don't conflict
2628 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002629 IdentifierInfo *II = D.getIdentifier();
2630 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002631 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002632 // Maybe we will complain about the shadowed template parameter.
2633 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2634 // Just pretend that we didn't see the previous declaration.
2635 PrevDecl = 0;
2636 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002637 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002638
2639 // Recover by removing the name
2640 II = 0;
2641 D.SetIdentifier(0, D.getIdentifierLoc());
2642 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002644
2645 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2646 // Doing the promotion here has a win and a loss. The win is the type for
2647 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2648 // code generator). The loss is the orginal type isn't preserved. For example:
2649 //
2650 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2651 // int blockvardecl[5];
2652 // sizeof(parmvardecl); // size == 4
2653 // sizeof(blockvardecl); // size == 20
2654 // }
2655 //
2656 // For expressions, all implicit conversions are captured using the
2657 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2658 //
2659 // FIXME: If a source translation tool needs to see the original type, then
2660 // we need to consider storing both types (in ParmVarDecl)...
2661 //
Chris Lattnere6327742008-04-02 05:18:44 +00002662 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002663 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002664 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002665 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002666 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002667
Chris Lattner04421082008-04-08 04:40:51 +00002668 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2669 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002670 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002671 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002672
Chris Lattner04421082008-04-08 04:40:51 +00002673 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002674 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002675
Douglas Gregor584049d2008-12-15 23:53:10 +00002676 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2677 if (D.getCXXScopeSpec().isSet()) {
2678 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2679 << D.getCXXScopeSpec().getRange();
2680 New->setInvalidDecl();
2681 }
2682
Douglas Gregor44b43212008-12-11 16:49:14 +00002683 // Add the parameter declaration into this scope.
2684 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002685 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002686 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002687
Chris Lattner3ff30c82008-06-29 00:02:00 +00002688 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002690
Reid Spencer5f016e22007-07-11 17:01:13 +00002691}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002692
Chris Lattnerb652cea2007-10-09 17:14:05 +00002693Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002694 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2696 "Not a function declarator!");
2697 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2700 // for a K&R function.
2701 if (!FTI.hasPrototype) {
2702 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002703 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002704 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2705 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 // Implicitly declare the argument as type 'int' for lack of a better
2707 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002708 DeclSpec DS;
2709 const char* PrevSpec; // unused
2710 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2711 PrevSpec);
2712 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2713 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2714 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002715 }
2716 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002718 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002719 }
2720
Douglas Gregor584049d2008-12-15 23:53:10 +00002721 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002722
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002723 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002724 ActOnDeclarator(ParentScope, D, 0,
2725 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002726}
2727
2728Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2729 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002730 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002731
2732 // See if this is a redefinition.
2733 const FunctionDecl *Definition;
2734 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002735 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002736 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002737 }
2738
Douglas Gregor44b43212008-12-11 16:49:14 +00002739 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002740
Chris Lattner04421082008-04-08 04:40:51 +00002741 // Check the validity of our function parameters
2742 CheckParmsForFunctionDef(FD);
2743
2744 // Introduce our parameters into the function scope
2745 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2746 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002747 Param->setOwningFunction(FD);
2748
Chris Lattner04421082008-04-08 04:40:51 +00002749 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002750 if (Param->getIdentifier())
2751 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002752 }
Chris Lattner04421082008-04-08 04:40:51 +00002753
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002754 // Checking attributes of current function definition
2755 // dllimport attribute.
2756 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2757 // dllimport attribute cannot be applied to definition.
2758 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2759 Diag(FD->getLocation(),
2760 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2761 << "dllimport";
2762 FD->setInvalidDecl();
2763 return FD;
2764 } else {
2765 // If a symbol previously declared dllimport is later defined, the
2766 // attribute is ignored in subsequent references, and a warning is
2767 // emitted.
2768 Diag(FD->getLocation(),
2769 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2770 << FD->getNameAsCString() << "dllimport";
2771 }
2772 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 return FD;
2774}
2775
Sebastian Redl798d1192008-12-13 16:23:55 +00002776Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002777 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002778 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002779 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002780 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002781 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002782 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002783 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002784 } else
2785 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002786 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 // Verify and clean out per-function state.
2788
2789 // Check goto/label use.
2790 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2791 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2792 // Verify that we have no forward references left. If so, there was a goto
2793 // or address of a label taken, but no definition of it. Label fwd
2794 // definitions are indicated with a null substmt.
2795 if (I->second->getSubStmt() == 0) {
2796 LabelStmt *L = I->second;
2797 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002798 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002799
2800 // At this point, we have gotos that use the bogus label. Stitch it into
2801 // the function body so that they aren't leaked and that the AST is well
2802 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002803 if (Body) {
2804 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002805 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002806 } else {
2807 // The whole function wasn't parsed correctly, just delete this.
2808 delete L;
2809 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002810 }
2811 }
2812 LabelMap.clear();
2813
Steve Naroffd6d054d2007-11-11 23:20:51 +00002814 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002815}
2816
Reid Spencer5f016e22007-07-11 17:01:13 +00002817/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2818/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002819ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2820 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002821 // Extension in C99. Legal in C90, but warn about it.
2822 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002823 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002824 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002825 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826
2827 // FIXME: handle stuff like:
2828 // void foo() { extern float X(); }
2829 // void bar() { X(); } <-- implicit decl for X in another scope.
2830
2831 // Set a Declarator for the implicit definition: int foo();
2832 const char *Dummy;
2833 DeclSpec DS;
2834 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2835 Error = Error; // Silence warning.
2836 assert(!Error && "Error setting up implicit decl!");
2837 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002838 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 D.SetIdentifier(&II, Loc);
2840
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002841 // Insert this function into translation-unit scope.
2842
2843 DeclContext *PrevDC = CurContext;
2844 CurContext = Context.getTranslationUnitDecl();
2845
Steve Naroffe2ef8152008-04-04 14:32:09 +00002846 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002847 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002848 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002849
2850 CurContext = PrevDC;
2851
Steve Naroffe2ef8152008-04-04 14:32:09 +00002852 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853}
2854
2855
Chris Lattner41af0932007-11-14 06:34:38 +00002856TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002857 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002859 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002860
2861 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002862 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2863 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002864 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002865 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002866 if (D.getInvalidType())
2867 NewTD->setInvalidDecl();
2868 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002869}
2870
Steve Naroff08d92e42007-09-15 18:49:24 +00002871/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002872/// former case, Name will be non-null. In the later case, Name will be null.
2873/// TagType indicates what kind of tag this is. TK indicates whether this is a
2874/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002875Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002876 SourceLocation KWLoc, const CXXScopeSpec &SS,
2877 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002878 AttributeList *Attr,
2879 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002880 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 assert((Name != 0 || TK == TK_Definition) &&
2882 "Nameless record must be a definition!");
2883
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002884 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 switch (TagType) {
2886 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002887 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2888 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2889 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2890 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002891 }
2892
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002893 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002894 DeclContext *LexicalContext = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002895 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002896
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002897 if (Name && SS.isNotEmpty()) {
2898 // We have a nested-name tag ('struct foo::bar').
2899
2900 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002901 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002902 Name = 0;
2903 goto CreateNewDecl;
2904 }
2905
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002906 DC = static_cast<DeclContext*>(SS.getScopeRep());
2907 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002908 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2909
2910 // A tag 'foo::bar' must already exist.
2911 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002912 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002913 Name = 0;
2914 goto CreateNewDecl;
2915 }
2916 } else {
2917 // If this is a named struct, check to see if there was a previous forward
2918 // declaration or definition.
2919 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2920 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
Douglas Gregor72de6672009-01-08 20:45:30 +00002921
2922 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2923 // FIXME: This makes sure that we ignore the contexts associated
2924 // with C structs, unions, and enums when looking for a matching
2925 // tag declaration or definition. See the similar lookup tweak
2926 // in Sema::LookupDecl; is there a better way to deal with this?
2927 while (isa<RecordDecl>(DC) || isa<EnumDecl>(DC))
2928 DC = DC->getParent();
2929 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002930 }
2931
Douglas Gregorf57172b2008-12-08 18:40:42 +00002932 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002933 // Maybe we will complain about the shadowed template parameter.
2934 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2935 // Just pretend that we didn't see the previous declaration.
2936 PrevDecl = 0;
2937 }
2938
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002939 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002940 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2941 "unexpected Decl type");
2942 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002943 // If this is a use of a previous tag, or if the tag is already declared
2944 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002945 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002946 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002947 // Make sure that this wasn't declared as an enum and now used as a
2948 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002949 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002950 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002951 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002952 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002953 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002954 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002955 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002956 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002957
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002958 // FIXME: In the future, return a variant or some other clue
2959 // for the consumer of this Decl to know it doesn't own it.
2960 // For our current ASTs this shouldn't be a problem, but will
2961 // need to be changed with DeclGroups.
2962 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002963 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002964
2965 // Diagnose attempts to redefine a tag.
2966 if (TK == TK_Definition) {
2967 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2968 Diag(NameLoc, diag::err_redefinition) << Name;
2969 Diag(Def->getLocation(), diag::note_previous_definition);
2970 // If this is a redefinition, recover by making this struct be
2971 // anonymous, which will make any later references get the previous
2972 // definition.
2973 Name = 0;
2974 PrevDecl = 0;
2975 }
2976 // Okay, this is definition of a previously declared or referenced
2977 // tag PrevDecl. We're going to create a new Decl for it.
2978 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002979 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002980 // If we get here we have (another) forward declaration or we
2981 // have a definition. Just create a new decl.
2982 } else {
2983 // If we get here, this is a definition of a new tag type in a nested
2984 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2985 // new decl/type. We set PrevDecl to NULL so that the entities
2986 // have distinct types.
2987 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002988 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002989 // If we get here, we're going to create a new Decl. If PrevDecl
2990 // is non-NULL, it's a definition of the tag declared by
2991 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002992 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002993 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002994 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002995 // The tag name clashes with a namespace name, issue an error and
2996 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002997 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002998 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002999 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003000 PrevDecl = 0;
3001 } else {
3002 // The existing declaration isn't relevant to us; we're in a
3003 // new scope, so clear out the previous declaration.
3004 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003005 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003007 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3008 (Kind != TagDecl::TK_enum)) {
3009 // C++ [basic.scope.pdecl]p5:
3010 // -- for an elaborated-type-specifier of the form
3011 //
3012 // class-key identifier
3013 //
3014 // if the elaborated-type-specifier is used in the
3015 // decl-specifier-seq or parameter-declaration-clause of a
3016 // function defined in namespace scope, the identifier is
3017 // declared as a class-name in the namespace that contains
3018 // the declaration; otherwise, except as a friend
3019 // declaration, the identifier is declared in the smallest
3020 // non-class, non-function-prototype scope that contains the
3021 // declaration.
3022 //
3023 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3024 // C structs and unions.
3025
3026 // Find the context where we'll be declaring the tag.
3027 while (DC->isRecord())
3028 DC = DC->getParent();
3029 LexicalContext = DC;
3030
3031 // Find the scope where we'll be declaring the tag.
3032 while (S->isClassScope() ||
3033 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003034 ((S->getFlags() & Scope::DeclScope) == 0) ||
3035 (S->getEntity() &&
3036 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003037 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003039
Chris Lattnercc98eac2008-12-17 07:13:27 +00003040CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003041
3042 // If there is an identifier, use the location of the identifier as the
3043 // location of the decl, otherwise use the location of the struct/union
3044 // keyword.
3045 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3046
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003047 // Otherwise, create a new declaration. If there is a previous
3048 // declaration of the same entity, the two will be linked via
3049 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003050 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003051
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003052 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003053 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3054 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003055 New = EnumDecl::Create(Context, DC, Loc, Name,
3056 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003057 // If this is an undefined enum, warn.
3058 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003059 } else {
3060 // struct/union/class
3061
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3063 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003064 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003065 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003066 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3067 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003068 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003069 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3070 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003071 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003072
3073 if (Kind != TagDecl::TK_enum) {
3074 // Handle #pragma pack: if the #pragma pack stack has non-default
3075 // alignment, make up a packed attribute for this decl. These
3076 // attributes are checked when the ASTContext lays out the
3077 // structure.
3078 //
3079 // It is important for implementing the correct semantics that this
3080 // happen here (in act on tag decl). The #pragma pack stack is
3081 // maintained as a result of parser callbacks which can occur at
3082 // many points during the parsing of a struct declaration (because
3083 // the #pragma tokens are effectively skipped over during the
3084 // parsing of the struct).
3085 if (unsigned Alignment = PackContext.getAlignment())
3086 New->addAttr(new PackedAttr(Alignment * 8));
3087 }
3088
3089 if (Attr)
3090 ProcessDeclAttributeList(New, Attr);
3091
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003092 // If we're declaring or defining
3093 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3094 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3095
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003096 // Set the lexical context. If the tag has a C++ scope specifier, the
3097 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003098 New->setLexicalDeclContext(LexicalContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00003099
3100 // If this has an identifier, add it to the scope stack.
3101 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003102 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003103
3104 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003105 if (LexicalContext != CurContext) {
3106 // FIXME: PushOnScopeChains should not rely on CurContext!
3107 DeclContext *OldContext = CurContext;
3108 CurContext = LexicalContext;
3109 PushOnScopeChains(New, S);
3110 CurContext = OldContext;
3111 } else
3112 PushOnScopeChains(New, S);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003113 } else if (getLangOptions().CPlusPlus) {
3114 // FIXME: We also want to do this for C, but if this tag is
3115 // defined within a structure CurContext will point to the context
3116 // enclosing the structure, and we would end up inserting the tag
3117 // type into the wrong place.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003118 LexicalContext->addDecl(Context, New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003119 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003120
Reid Spencer5f016e22007-07-11 17:01:13 +00003121 return New;
3122}
3123
Douglas Gregor72de6672009-01-08 20:45:30 +00003124void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3125 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3126
3127 // Enter the tag context.
3128 PushDeclContext(S, Tag);
3129
3130 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3131 FieldCollector->StartClass();
3132
3133 if (Record->getIdentifier()) {
3134 // C++ [class]p2:
3135 // [...] The class-name is also inserted into the scope of the
3136 // class itself; this is known as the injected-class-name. For
3137 // purposes of access checking, the injected-class-name is treated
3138 // as if it were a public member name.
3139 RecordDecl *InjectedClassName
3140 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3141 CurContext, Record->getLocation(),
3142 Record->getIdentifier(), Record);
3143 InjectedClassName->setImplicit();
3144 PushOnScopeChains(InjectedClassName, S);
3145 }
3146 }
3147}
3148
3149void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3150 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3151
3152 if (isa<CXXRecordDecl>(Tag))
3153 FieldCollector->FinishClass();
3154
3155 // Exit this scope of this tag's definition.
3156 PopDeclContext();
3157
3158 // Notify the consumer that we've defined a tag.
3159 Consumer.HandleTagDeclDefinition(Tag);
3160}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003161
Chris Lattner1d353ba2008-11-12 21:17:48 +00003162/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3163/// types into constant array types in certain situations which would otherwise
3164/// be errors (for GCC compatibility).
3165static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3166 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003167 // This method tries to turn a variable array into a constant
3168 // array even when the size isn't an ICE. This is necessary
3169 // for compatibility with code that depends on gcc's buggy
3170 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003171 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3172 if (!VLATy) return QualType();
3173
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003174 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003175 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003176 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003177 return QualType();
3178
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003179 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3180 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003181 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3182 return Context.getConstantArrayType(VLATy->getElementType(),
3183 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003184 return QualType();
3185}
3186
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003187bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003188 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003189 // FIXME: 6.7.2.1p4 - verify the field type.
3190
3191 llvm::APSInt Value;
3192 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3193 return true;
3194
Chris Lattnercd087072008-12-12 04:56:04 +00003195 // Zero-width bitfield is ok for anonymous field.
3196 if (Value == 0 && FieldName)
3197 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3198
3199 if (Value.isNegative())
3200 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003201
3202 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3203 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003204 if (TypeSize && Value.getZExtValue() > TypeSize)
3205 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3206 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003207
3208 return false;
3209}
3210
Steve Naroff08d92e42007-09-15 18:49:24 +00003211/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003212/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003213Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003214 SourceLocation DeclStart,
3215 Declarator &D, ExprTy *BitfieldWidth) {
3216 IdentifierInfo *II = D.getIdentifier();
3217 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003219 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003220 if (II) Loc = D.getIdentifierLoc();
3221
3222 // FIXME: Unnamed fields can be handled in various different ways, for
3223 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003224
Reid Spencer5f016e22007-07-11 17:01:13 +00003225 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003226 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3227 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003228
Reid Spencer5f016e22007-07-11 17:01:13 +00003229 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3230 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003231 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003232 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003233 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003234 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003235 T = FixedTy;
3236 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003237 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003238 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003239 InvalidDecl = true;
3240 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003241 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003242
3243 if (BitWidth) {
3244 if (VerifyBitField(Loc, II, T, BitWidth))
3245 InvalidDecl = true;
3246 } else {
3247 // Not a bitfield.
3248
3249 // validate II.
3250
3251 }
3252
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003254 FieldDecl *NewFD;
3255
Douglas Gregor44b43212008-12-11 16:49:14 +00003256 NewFD = FieldDecl::Create(Context, Record,
3257 Loc, II, T, BitWidth,
3258 D.getDeclSpec().getStorageClassSpec() ==
3259 DeclSpec::SCS_mutable,
3260 /*PrevDecl=*/0);
3261
Douglas Gregor72de6672009-01-08 20:45:30 +00003262 if (II) {
3263 Decl *PrevDecl
3264 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3265 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3266 && !isa<TagDecl>(PrevDecl)) {
3267 Diag(Loc, diag::err_duplicate_member) << II;
3268 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3269 NewFD->setInvalidDecl();
3270 Record->setInvalidDecl();
3271 }
3272 }
3273
Sebastian Redl64b45f72009-01-05 20:52:13 +00003274 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003275 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003276 if (!T->isPODType())
3277 cast<CXXRecordDecl>(Record)->setPOD(false);
3278 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003279
Chris Lattner3ff30c82008-06-29 00:02:00 +00003280 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003281
Steve Naroff5912a352007-08-28 20:14:24 +00003282 if (D.getInvalidType() || InvalidDecl)
3283 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003284
Douglas Gregor72de6672009-01-08 20:45:30 +00003285 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003286 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003287 } else
Douglas Gregor44b43212008-12-11 16:49:14 +00003288 Record->addDecl(Context, NewFD);
3289
Steve Naroff5912a352007-08-28 20:14:24 +00003290 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003291}
3292
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003293/// TranslateIvarVisibility - Translate visibility from a token ID to an
3294/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003295static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003296TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003297 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003298 default: assert(0 && "Unknown visitibility kind");
3299 case tok::objc_private: return ObjCIvarDecl::Private;
3300 case tok::objc_public: return ObjCIvarDecl::Public;
3301 case tok::objc_protected: return ObjCIvarDecl::Protected;
3302 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003303 }
3304}
3305
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003306/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3307/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003308Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003309 SourceLocation DeclStart,
3310 Declarator &D, ExprTy *BitfieldWidth,
3311 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003312
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003313 IdentifierInfo *II = D.getIdentifier();
3314 Expr *BitWidth = (Expr*)BitfieldWidth;
3315 SourceLocation Loc = DeclStart;
3316 if (II) Loc = D.getIdentifierLoc();
3317
3318 // FIXME: Unnamed fields can be handled in various different ways, for
3319 // example, unnamed unions inject all members into the struct namespace!
3320
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003321 QualType T = GetTypeForDeclarator(D, S);
3322 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3323 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003324
3325 if (BitWidth) {
3326 // TODO: Validate.
3327 //printf("WARNING: BITFIELDS IGNORED!\n");
3328
3329 // 6.7.2.1p3
3330 // 6.7.2.1p4
3331
3332 } else {
3333 // Not a bitfield.
3334
3335 // validate II.
3336
3337 }
3338
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003339 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3340 // than a variably modified type.
3341 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003342 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003343 InvalidDecl = true;
3344 }
3345
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003346 // Get the visibility (access control) for this ivar.
3347 ObjCIvarDecl::AccessControl ac =
3348 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3349 : ObjCIvarDecl::None;
3350
3351 // Construct the decl.
3352 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003353 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003354
Douglas Gregor72de6672009-01-08 20:45:30 +00003355 if (II) {
3356 Decl *PrevDecl
3357 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3358 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3359 && !isa<TagDecl>(PrevDecl)) {
3360 Diag(Loc, diag::err_duplicate_member) << II;
3361 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3362 NewID->setInvalidDecl();
3363 }
3364 }
3365
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003366 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003367 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003368
3369 if (D.getInvalidType() || InvalidDecl)
3370 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003371
Douglas Gregor72de6672009-01-08 20:45:30 +00003372 if (II) {
3373 // FIXME: When interfaces are DeclContexts, we'll need to add
3374 // these to the interface.
3375 S->AddDecl(NewID);
3376 IdResolver.AddDecl(NewID);
3377 }
3378
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003379 return NewID;
3380}
3381
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003382void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003383 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003384 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003385 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003386 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003387 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3388 assert(EnclosingDecl && "missing record or interface decl");
3389 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3390
Douglas Gregor72de6672009-01-08 20:45:30 +00003391 if (Record) {
3392 QualType RecordType = Context.getTypeDeclType(Record);
3393 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3394 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003395 // Diagnose code like:
3396 // struct S { struct S {} X; };
3397 // We discover this when we complete the outer S. Reject and ignore the
3398 // outer S.
Douglas Gregor72de6672009-01-08 20:45:30 +00003399 Diag(Def->getLocation(), diag::err_nested_redefinition)
3400 << Def->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003401 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003402 Record->setInvalidDecl();
3403 return;
3404 }
Douglas Gregor72de6672009-01-08 20:45:30 +00003405 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003406
Reid Spencer5f016e22007-07-11 17:01:13 +00003407 // Verify that all the fields are okay.
3408 unsigned NumNamedMembers = 0;
3409 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003410
Reid Spencer5f016e22007-07-11 17:01:13 +00003411 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003412 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3413 assert(FD && "missing field decl");
3414
Reid Spencer5f016e22007-07-11 17:01:13 +00003415 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003416 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003417
Douglas Gregor72de6672009-01-08 20:45:30 +00003418 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003419 // Remember all fields written by the user.
3420 RecFields.push_back(FD);
3421 }
Steve Narofff13271f2007-09-14 23:09:53 +00003422
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003424 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003425 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003426 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003427 FD->setInvalidDecl();
3428 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003429 continue;
3430 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003431 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3432 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003433 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003435 FD->setInvalidDecl();
3436 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003437 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003438 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003439 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003440 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003441 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003442 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003443 FD->setInvalidDecl();
3444 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003445 continue;
3446 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003447 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003448 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003449 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003450 FD->setInvalidDecl();
3451 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003452 continue;
3453 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003454 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003455 if (Record)
3456 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003457 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003458 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3459 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003460 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003461 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3462 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003463 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 Record->setHasFlexibleArrayMember(true);
3465 } else {
3466 // If this is a struct/class and this is not the last element, reject
3467 // it. Note that GCC supports variable sized arrays in the middle of
3468 // structures.
3469 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003470 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003471 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003472 FD->setInvalidDecl();
3473 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003474 continue;
3475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003476 // We support flexible arrays at the end of structs in other structs
3477 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003478 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003479 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003480 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003481 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003482 }
3483 }
3484 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003485 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003486 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003487 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003488 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003489 FD->setInvalidDecl();
3490 EnclosingDecl->setInvalidDecl();
3491 continue;
3492 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003493 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003494 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003495 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003496 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003497
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003499 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003500 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003501 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003502 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003503 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003504 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003505 // Must enforce the rule that ivars in the base classes may not be
3506 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003507 if (ID->getSuperClass()) {
3508 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3509 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3510 ObjCIvarDecl* Ivar = (*IVI);
3511 IdentifierInfo *II = Ivar->getIdentifier();
3512 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3513 if (prevIvar) {
3514 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003515 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003516 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003517 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003518 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003519 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003520 else if (ObjCImplementationDecl *IMPDecl =
3521 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003522 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3523 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003524 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003525 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003526 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003527
3528 if (Attr)
3529 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003530}
3531
Steve Naroff08d92e42007-09-15 18:49:24 +00003532Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 DeclTy *lastEnumConst,
3534 SourceLocation IdLoc, IdentifierInfo *Id,
3535 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003536 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 EnumConstantDecl *LastEnumConst =
3538 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3539 Expr *Val = static_cast<Expr*>(val);
3540
Chris Lattner31e05722007-08-26 06:24:45 +00003541 // The scope passed in may not be a decl scope. Zip up the scope tree until
3542 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003543 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003544
Reid Spencer5f016e22007-07-11 17:01:13 +00003545 // Verify that there isn't already something declared with this name in this
3546 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003547 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003548 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003549 // Maybe we will complain about the shadowed template parameter.
3550 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3551 // Just pretend that we didn't see the previous declaration.
3552 PrevDecl = 0;
3553 }
3554
3555 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003556 // When in C++, we may get a TagDecl with the same name; in this case the
3557 // enum constant will 'hide' the tag.
3558 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3559 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003560 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003561 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003562 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003563 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003564 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003565 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003566 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003567 return 0;
3568 }
3569 }
3570
3571 llvm::APSInt EnumVal(32);
3572 QualType EltTy;
3573 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003574 // Make sure to promote the operand type to int.
3575 UsualUnaryConversions(Val);
3576
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3578 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003579 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003580 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003581 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003582 } else {
3583 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003584 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003585 }
3586
3587 if (!Val) {
3588 if (LastEnumConst) {
3589 // Assign the last value + 1.
3590 EnumVal = LastEnumConst->getInitVal();
3591 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003592
3593 // Check for overflow on increment.
3594 if (EnumVal < LastEnumConst->getInitVal())
3595 Diag(IdLoc, diag::warn_enum_value_overflow);
3596
Chris Lattnerb7416f92007-08-27 17:37:24 +00003597 EltTy = LastEnumConst->getType();
3598 } else {
3599 // First value, set to zero.
3600 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003601 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003602 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003603 }
3604
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003605 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003606 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3607 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003608 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003609
3610 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003611 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003612
Reid Spencer5f016e22007-07-11 17:01:13 +00003613 return New;
3614}
3615
Steve Naroff02408c62008-08-07 14:08:16 +00003616// FIXME: For consistency with ActOnFields(), we should have the parser
3617// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003618void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003619 DeclTy **Elements, unsigned NumElements) {
3620 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003621 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003622
Douglas Gregor074149e2009-01-05 19:45:36 +00003623 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3624 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3625 // Diagnose code like:
3626 // enum e0 {
3627 // E0 = sizeof(enum e0 { E1 })
3628 // };
3629 Diag(Def->getLocation(), diag::err_nested_redefinition)
3630 << Enum->getDeclName();
3631 Diag(Enum->getLocation(), diag::note_previous_definition);
3632 Enum->setInvalidDecl();
Douglas Gregor074149e2009-01-05 19:45:36 +00003633 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003634 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003635
Chris Lattnere37f0be2007-08-28 05:10:31 +00003636 // TODO: If the result value doesn't fit in an int, it must be a long or long
3637 // long value. ISO C does not support this, but GCC does as an extension,
3638 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003639 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003640
Chris Lattnerac609682007-08-28 06:15:15 +00003641 // Verify that all the values are okay, compute the size of the values, and
3642 // reverse the list.
3643 unsigned NumNegativeBits = 0;
3644 unsigned NumPositiveBits = 0;
3645
3646 // Keep track of whether all elements have type int.
3647 bool AllElementsInt = true;
3648
Reid Spencer5f016e22007-07-11 17:01:13 +00003649 for (unsigned i = 0; i != NumElements; ++i) {
3650 EnumConstantDecl *ECD =
3651 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3652 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003653
3654 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003655 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003656 assert(InitVal.getBitWidth() >= IntWidth &&
3657 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003658 if (InitVal.getBitWidth() > IntWidth) {
3659 llvm::APSInt V(InitVal);
3660 V.trunc(IntWidth);
3661 V.extend(InitVal.getBitWidth());
3662 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003663 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3664 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003665 }
Chris Lattnerac609682007-08-28 06:15:15 +00003666
3667 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003668 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003669 NumPositiveBits = std::max(NumPositiveBits,
3670 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003671 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003672 NumNegativeBits = std::max(NumNegativeBits,
3673 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003674
Chris Lattnerac609682007-08-28 06:15:15 +00003675 // Keep track of whether every enum element has type int (very commmon).
3676 if (AllElementsInt)
3677 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003678 }
3679
Chris Lattnerac609682007-08-28 06:15:15 +00003680 // Figure out the type that should be used for this enum.
3681 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3682 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003683 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003684
3685 if (NumNegativeBits) {
3686 // If there is a negative value, figure out the smallest integer type (of
3687 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003688 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003689 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003690 BestWidth = IntWidth;
3691 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003692 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003693
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003694 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003695 BestType = Context.LongTy;
3696 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003697 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003698
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003699 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003700 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3701 BestType = Context.LongLongTy;
3702 }
3703 }
3704 } else {
3705 // If there is no negative value, figure out which of uint, ulong, ulonglong
3706 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003707 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003708 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003709 BestWidth = IntWidth;
3710 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003711 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003712 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003713 } else {
3714 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003715 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003716 "How could an initializer get larger than ULL?");
3717 BestType = Context.UnsignedLongLongTy;
3718 }
3719 }
3720
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003721 // Loop over all of the enumerator constants, changing their types to match
3722 // the type of the enum if needed.
3723 for (unsigned i = 0; i != NumElements; ++i) {
3724 EnumConstantDecl *ECD =
3725 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3726 if (!ECD) continue; // Already issued a diagnostic.
3727
3728 // Standard C says the enumerators have int type, but we allow, as an
3729 // extension, the enumerators to be larger than int size. If each
3730 // enumerator value fits in an int, type it as an int, otherwise type it the
3731 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3732 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003733 if (ECD->getType() == Context.IntTy) {
3734 // Make sure the init value is signed.
3735 llvm::APSInt IV = ECD->getInitVal();
3736 IV.setIsSigned(true);
3737 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003738
3739 if (getLangOptions().CPlusPlus)
3740 // C++ [dcl.enum]p4: Following the closing brace of an
3741 // enum-specifier, each enumerator has the type of its
3742 // enumeration.
3743 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003744 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003745 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003746
3747 // Determine whether the value fits into an int.
3748 llvm::APSInt InitVal = ECD->getInitVal();
3749 bool FitsInInt;
3750 if (InitVal.isUnsigned() || !InitVal.isNegative())
3751 FitsInInt = InitVal.getActiveBits() < IntWidth;
3752 else
3753 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3754
3755 // If it fits into an integer type, force it. Otherwise force it to match
3756 // the enum decl type.
3757 QualType NewTy;
3758 unsigned NewWidth;
3759 bool NewSign;
3760 if (FitsInInt) {
3761 NewTy = Context.IntTy;
3762 NewWidth = IntWidth;
3763 NewSign = true;
3764 } else if (ECD->getType() == BestType) {
3765 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003766 if (getLangOptions().CPlusPlus)
3767 // C++ [dcl.enum]p4: Following the closing brace of an
3768 // enum-specifier, each enumerator has the type of its
3769 // enumeration.
3770 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003771 continue;
3772 } else {
3773 NewTy = BestType;
3774 NewWidth = BestWidth;
3775 NewSign = BestType->isSignedIntegerType();
3776 }
3777
3778 // Adjust the APSInt value.
3779 InitVal.extOrTrunc(NewWidth);
3780 InitVal.setIsSigned(NewSign);
3781 ECD->setInitVal(InitVal);
3782
3783 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003784 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3785 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003786 if (getLangOptions().CPlusPlus)
3787 // C++ [dcl.enum]p4: Following the closing brace of an
3788 // enum-specifier, each enumerator has the type of its
3789 // enumeration.
3790 ECD->setType(EnumType);
3791 else
3792 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003793 }
Chris Lattnerac609682007-08-28 06:15:15 +00003794
Douglas Gregor44b43212008-12-11 16:49:14 +00003795 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003796}
3797
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003798Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003799 ExprArg expr) {
3800 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3801
Chris Lattner8e25d862008-03-16 00:16:02 +00003802 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003803}
3804
Douglas Gregorf44515a2008-12-16 22:23:02 +00003805
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003806void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3807 ExprTy *alignment, SourceLocation PragmaLoc,
3808 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3809 Expr *Alignment = static_cast<Expr *>(alignment);
3810
3811 // If specified then alignment must be a "small" power of two.
3812 unsigned AlignmentVal = 0;
3813 if (Alignment) {
3814 llvm::APSInt Val;
3815 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3816 !Val.isPowerOf2() ||
3817 Val.getZExtValue() > 16) {
3818 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3819 delete Alignment;
3820 return; // Ignore
3821 }
3822
3823 AlignmentVal = (unsigned) Val.getZExtValue();
3824 }
3825
3826 switch (Kind) {
3827 case Action::PPK_Default: // pack([n])
3828 PackContext.setAlignment(AlignmentVal);
3829 break;
3830
3831 case Action::PPK_Show: // pack(show)
3832 // Show the current alignment, making sure to show the right value
3833 // for the default.
3834 AlignmentVal = PackContext.getAlignment();
3835 // FIXME: This should come from the target.
3836 if (AlignmentVal == 0)
3837 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003838 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003839 break;
3840
3841 case Action::PPK_Push: // pack(push [, id] [, [n])
3842 PackContext.push(Name);
3843 // Set the new alignment if specified.
3844 if (Alignment)
3845 PackContext.setAlignment(AlignmentVal);
3846 break;
3847
3848 case Action::PPK_Pop: // pack(pop [, id] [, n])
3849 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3850 // "#pragma pack(pop, identifier, n) is undefined"
3851 if (Alignment && Name)
3852 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3853
3854 // Do the pop.
3855 if (!PackContext.pop(Name)) {
3856 // If a name was specified then failure indicates the name
3857 // wasn't found. Otherwise failure indicates the stack was
3858 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003859 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3860 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003861
3862 // FIXME: Warn about popping named records as MSVC does.
3863 } else {
3864 // Pop succeeded, set the new alignment if specified.
3865 if (Alignment)
3866 PackContext.setAlignment(AlignmentVal);
3867 }
3868 break;
3869
3870 default:
3871 assert(0 && "Invalid #pragma pack kind.");
3872 }
3873}
3874
3875bool PragmaPackStack::pop(IdentifierInfo *Name) {
3876 if (Stack.empty())
3877 return false;
3878
3879 // If name is empty just pop top.
3880 if (!Name) {
3881 Alignment = Stack.back().first;
3882 Stack.pop_back();
3883 return true;
3884 }
3885
3886 // Otherwise, find the named record.
3887 for (unsigned i = Stack.size(); i != 0; ) {
3888 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003889 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003890 // Found it, pop up to and including this record.
3891 Alignment = Stack[i].first;
3892 Stack.erase(Stack.begin() + i, Stack.end());
3893 return true;
3894 }
3895 }
3896
3897 return false;
3898}