blob: 39b9c787cf8cc047c778fb4c4a284478bc7e566a [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
Steve Naroffe8043c32008-04-01 23:04:06 +0000254/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000255/// namespace. NamespaceNameOnly - during lookup only namespace names
256/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
257/// 'When looking up a namespace-name in a using-directive or
258/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000260 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000261 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000262 bool LookInParent,
263 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000264 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000265 unsigned NS = NSI;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000266
Douglas Gregor72de6672009-01-08 20:45:30 +0000267 // In C++, ordinary and member lookup will always find all
268 // kinds of names.
269 if (getLangOptions().CPlusPlus &&
270 (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Member)))
271 NS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Ordinary;
272
273 if (LookupCtx == 0 && !getLangOptions().CPlusPlus) {
274 // Unqualified name lookup in C/Objective-C is purely lexical, so
275 // search in the declarations attached to the name.
Douglas Gregore267ff32008-12-11 20:41:00 +0000276 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000277 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregor72de6672009-01-08 20:45:30 +0000278
279 // For the purposes of unqualified name lookup, structs and unions
280 // don't have scopes at all. For example:
281 //
282 // struct X {
283 // struct T { int i; } x;
284 // };
285 //
286 // void f() {
287 // struct T t; // okay: T is defined lexically within X, but
288 // // semantically at global scope
289 // };
290 //
291 // FIXME: Is there a better way to deal with this?
292 DeclContext *SearchCtx = CurContext;
293 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
294 SearchCtx = SearchCtx->getParent();
Douglas Gregore267ff32008-12-11 20:41:00 +0000295 IdentifierResolver::iterator I
Douglas Gregor72de6672009-01-08 20:45:30 +0000296 = IdResolver.begin(Name, SearchCtx, LookInParent);
Douglas Gregore267ff32008-12-11 20:41:00 +0000297
298 // Scan up the scope chain looking for a decl that matches this
299 // identifier that is in the appropriate namespace. This search
300 // should not take long, as shadowing of names is uncommon, and
301 // deep shadowing is extremely uncommon.
302 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000303 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000304 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000305 } else if (LookupCtx) {
Douglas Gregor72de6672009-01-08 20:45:30 +0000306 // If we're performing qualified name lookup (e.g., lookup into a
307 // struct), find fields as part of ordinary name lookup.
308 if (NS & Decl::IDNS_Ordinary)
309 NS |= Decl::IDNS_Member;
310
Douglas Gregor44b43212008-12-11 16:49:14 +0000311 // Perform qualified name lookup into the LookupCtx.
312 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000313 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000314 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000315 if ((*I)->isInIdentifierNamespace(NS)) {
316 // Ignore non-namespace names if we're only looking for namespaces.
317 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
318
319 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000320 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000321 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000322 // Name lookup for ordinary names and tag names in C++ requires
323 // looking into scopes that aren't strictly lexical, and
324 // therefore we walk through the context as well as walking
325 // through the scopes.
326 IdentifierResolver::iterator
327 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
328 IEnd = IdResolver.end();
329 for (; S; S = S->getParent()) {
330 // Check whether the IdResolver has anything in this scope.
331 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000332 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000333 if ((*I)->isInIdentifierNamespace(NS)) {
334 // Ignore non-namespace names if we're only looking for namespaces.
335 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
336 continue;
337
338 // We found something. Look for anything else in our scope
339 // with this same name and in an acceptable identifier
340 // namespace, so that we can construct an overload set if we
341 // need to.
342 IdentifierResolver::iterator LastI = I;
343 for (++LastI; LastI != IEnd; ++LastI) {
344 if (!(*LastI)->isInIdentifierNamespace(NS) ||
345 !S->isDeclScope(*LastI))
346 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000347 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000348 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000349 }
350 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000351
352 // If there is an entity associated with this scope, it's a
353 // DeclContext. We might need to perform qualified lookup into
354 // it.
355 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
356 while (Ctx && Ctx->isFunctionOrMethod())
357 Ctx = Ctx->getParent();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000358 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000359 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000360 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000361 for (llvm::tie(I, E) = Ctx->lookup(Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000362 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000363 if ((*I)->isInIdentifierNamespace(NS)) {
364 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
365 continue;
366 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000367 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000368 }
369
Douglas Gregorbc468ba2009-01-07 21:36:02 +0000370 if (!LookInParent && !Ctx->isTransparentContext())
371 return 0;
372
Douglas Gregor44b43212008-12-11 16:49:14 +0000373 Ctx = Ctx->getParent();
374 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000375 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000376 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000377
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 // If we didn't find a use of this identifier, and if the identifier
379 // corresponds to a compiler builtin, create the decl object for the builtin
380 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000381 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000382 IdentifierInfo *II = Name.getAsIdentifierInfo();
383 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000384 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000385 // If this is a builtin on this (or all) targets, create the decl.
386 if (unsigned BuiltinID = II->getBuiltinID())
387 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
388 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000389 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000390 // @interface and @compatibility_alias introduce typedef-like names.
391 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000392 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000393 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000394 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
395 if (IDI != ObjCInterfaceDecls.end())
396 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000397 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
398 if (I != ObjCAliasDecls.end())
399 return I->second->getClassInterface();
400 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 }
402 return 0;
403}
404
Chris Lattner95e2c712008-05-05 22:18:14 +0000405void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000406 if (!Context.getBuiltinVaListType().isNull())
407 return;
408
409 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000410 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000411 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000412 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
413}
414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
416/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000417ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
418 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 Builtin::ID BID = (Builtin::ID)bid;
420
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000421 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000422 InitBuiltinVaListType();
423
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000424 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000425 FunctionDecl *New = FunctionDecl::Create(Context,
426 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000427 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000428 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000429
Chris Lattner95e2c712008-05-05 22:18:14 +0000430 // Create Decl objects for each parameter, adding them to the
431 // FunctionDecl.
432 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
433 llvm::SmallVector<ParmVarDecl*, 16> Params;
434 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
435 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
436 FT->getArgType(i), VarDecl::None, 0,
437 0));
438 New->setParams(&Params[0], Params.size());
439 }
440
441
442
Chris Lattner7f925cc2008-04-11 07:00:53 +0000443 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000444 // FIXME: This is hideous. We need to teach PushOnScopeChains to
445 // relate Scopes to DeclContexts, and probably eliminate CurContext
446 // entirely, but we're not there yet.
447 DeclContext *SavedContext = CurContext;
448 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000449 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000450 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 return New;
452}
453
Sebastian Redlc42e1182008-11-11 11:37:55 +0000454/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
455/// everything from the standard library is defined.
456NamespaceDecl *Sema::GetStdNamespace() {
457 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000458 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000459 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000460 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000461 0, Global, /*enableLazyBuiltinCreation=*/false);
462 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
463 }
464 return StdNamespace;
465}
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
468/// and scope as a previous declaration 'Old'. Figure out how to resolve this
469/// situation, merging decls or emitting diagnostics as appropriate.
470///
Steve Naroffe8043c32008-04-01 23:04:06 +0000471TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000472 // Allow multiple definitions for ObjC built-in typedefs.
473 // FIXME: Verify the underlying types are equivalent!
474 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000475 const IdentifierInfo *TypeID = New->getIdentifier();
476 switch (TypeID->getLength()) {
477 default: break;
478 case 2:
479 if (!TypeID->isStr("id"))
480 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000481 Context.setObjCIdType(New);
482 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000483 case 5:
484 if (!TypeID->isStr("Class"))
485 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000486 Context.setObjCClassType(New);
487 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000488 case 3:
489 if (!TypeID->isStr("SEL"))
490 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000491 Context.setObjCSelType(New);
492 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000493 case 8:
494 if (!TypeID->isStr("Protocol"))
495 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000496 Context.setObjCProtoType(New->getUnderlyingType());
497 return New;
498 }
499 // Fall through - the typedef name was not a builtin type.
500 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // Verify the old decl was also a typedef.
502 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
503 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000504 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000505 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000506 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 return New;
508 }
509
Chris Lattner99cb9972008-07-25 18:44:27 +0000510 // If the typedef types are not identical, reject them in all languages and
511 // with any extensions enabled.
512 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
513 Context.getCanonicalType(Old->getUnderlyingType()) !=
514 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000515 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000516 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000517 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000518 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000519 }
520
Eli Friedman54ecfce2008-06-11 06:20:39 +0000521 if (getLangOptions().Microsoft) return New;
522
Douglas Gregorbbe27432008-11-21 16:29:06 +0000523 // C++ [dcl.typedef]p2:
524 // In a given non-class scope, a typedef specifier can be used to
525 // redefine the name of any type declared in that scope to refer
526 // to the type to which it already refers.
527 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
528 return New;
529
530 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000531 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
532 // *either* declaration is in a system header. The code below implements
533 // this adhoc compatibility rule. FIXME: The following code will not
534 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000535 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
536 SourceManager &SrcMgr = Context.getSourceManager();
537 if (SrcMgr.isInSystemHeader(Old->getLocation()))
538 return New;
539 if (SrcMgr.isInSystemHeader(New->getLocation()))
540 return New;
541 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000542
Chris Lattner08631c52008-11-23 21:45:46 +0000543 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000544 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 return New;
546}
547
Chris Lattner6b6b5372008-06-26 18:38:35 +0000548/// DeclhasAttr - returns true if decl Declaration already has the target
549/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000550static bool DeclHasAttr(const Decl *decl, const Attr *target) {
551 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
552 if (attr->getKind() == target->getKind())
553 return true;
554
555 return false;
556}
557
558/// MergeAttributes - append attributes from the Old decl to the New one.
559static void MergeAttributes(Decl *New, Decl *Old) {
560 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
561
Chris Lattnerddee4232008-03-03 03:28:21 +0000562 while (attr) {
563 tmp = attr;
564 attr = attr->getNext();
565
566 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000567 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000568 New->addAttr(tmp);
569 } else {
570 tmp->setNext(0);
571 delete(tmp);
572 }
573 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000574
575 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000576}
577
Chris Lattner04421082008-04-08 04:40:51 +0000578/// MergeFunctionDecl - We just parsed a function 'New' from
579/// declarator D which has the same name and scope as a previous
580/// declaration 'Old'. Figure out how to resolve this situation,
581/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582/// Redeclaration will be set true if this New is a redeclaration OldD.
583///
584/// In C++, New and Old must be declarations that are not
585/// overloaded. Use IsOverload to determine whether New and Old are
586/// overloaded, and to select the Old declaration that New should be
587/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000588FunctionDecl *
589Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000590 assert(!isa<OverloadedFunctionDecl>(OldD) &&
591 "Cannot merge with an overloaded function declaration");
592
Douglas Gregorf0097952008-04-21 02:02:58 +0000593 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 // Verify the old decl was also a function.
595 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
596 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000597 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000598 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000599 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 return New;
601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602
603 // Determine whether the previous declaration was a definition,
604 // implicit declaration, or a declaration.
605 diag::kind PrevDiag;
606 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000607 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000609 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000611 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000612
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000613 QualType OldQType = Context.getCanonicalType(Old->getType());
614 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000615
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000616 if (getLangOptions().CPlusPlus) {
617 // (C++98 13.1p2):
618 // Certain function declarations cannot be overloaded:
619 // -- Function declarations that differ only in the return type
620 // cannot be overloaded.
621 QualType OldReturnType
622 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
623 QualType NewReturnType
624 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
625 if (OldReturnType != NewReturnType) {
626 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
627 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000628 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000629 return New;
630 }
631
632 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
633 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
634 if (OldMethod && NewMethod) {
635 // -- Member function declarations with the same name and the
636 // same parameter types cannot be overloaded if any of them
637 // is a static member function declaration.
638 if (OldMethod->isStatic() || NewMethod->isStatic()) {
639 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
640 Diag(Old->getLocation(), PrevDiag);
641 return New;
642 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000643
644 // C++ [class.mem]p1:
645 // [...] A member shall not be declared twice in the
646 // member-specification, except that a nested class or member
647 // class template can be declared and then later defined.
648 if (OldMethod->getLexicalDeclContext() ==
649 NewMethod->getLexicalDeclContext()) {
650 unsigned NewDiag;
651 if (isa<CXXConstructorDecl>(OldMethod))
652 NewDiag = diag::err_constructor_redeclared;
653 else if (isa<CXXDestructorDecl>(NewMethod))
654 NewDiag = diag::err_destructor_redeclared;
655 else if (isa<CXXConversionDecl>(NewMethod))
656 NewDiag = diag::err_conv_function_redeclared;
657 else
658 NewDiag = diag::err_member_redeclared;
659
660 Diag(New->getLocation(), NewDiag);
661 Diag(Old->getLocation(), PrevDiag);
662 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663 }
664
665 // (C++98 8.3.5p3):
666 // All declarations for a function shall agree exactly in both the
667 // return type and the parameter-type-list.
668 if (OldQType == NewQType) {
669 // We have a redeclaration.
670 MergeAttributes(New, Old);
671 Redeclaration = true;
672 return MergeCXXFunctionDecl(New, Old);
673 }
674
675 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000676 }
Chris Lattner04421082008-04-08 04:40:51 +0000677
678 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000679 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000680 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000681 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000682 MergeAttributes(New, Old);
683 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000684 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000685 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000686
Steve Naroff837618c2008-01-16 15:01:34 +0000687 // A function that has already been declared has been redeclared or defined
688 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
691 // TODO: This is totally simplistic. It should handle merging functions
692 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000693 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000694 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 return New;
696}
697
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000698/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000699static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000700 if (VD->isFileVarDecl())
701 return (!VD->getInit() &&
702 (VD->getStorageClass() == VarDecl::None ||
703 VD->getStorageClass() == VarDecl::Static));
704 return false;
705}
706
707/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
708/// when dealing with C "tentative" external object definitions (C99 6.9.2).
709void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
710 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000711 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000712
Douglas Gregore21b9942009-01-07 16:34:42 +0000713 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000714 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000715 for (IdentifierResolver::iterator
716 I = IdResolver.begin(VD->getIdentifier(),
717 VD->getDeclContext(), false/*LookInParentCtx*/),
718 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000719 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000720 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
721
Steve Narofff855e6f2008-08-10 15:20:13 +0000722 // Handle the following case:
723 // int a[10];
724 // int a[]; - the code below makes sure we set the correct type.
725 // int a[11]; - this is an error, size isn't 10.
726 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
727 OldDecl->getType()->isConstantArrayType())
728 VD->setType(OldDecl->getType());
729
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000730 // Check for "tentative" definitions. We can't accomplish this in
731 // MergeVarDecl since the initializer hasn't been attached.
732 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
733 continue;
734
735 // Handle __private_extern__ just like extern.
736 if (OldDecl->getStorageClass() != VarDecl::Extern &&
737 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
738 VD->getStorageClass() != VarDecl::Extern &&
739 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000740 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000741 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000742 }
743 }
744 }
745}
746
Reid Spencer5f016e22007-07-11 17:01:13 +0000747/// MergeVarDecl - We just parsed a variable 'New' which has the same name
748/// and scope as a previous declaration 'Old'. Figure out how to resolve this
749/// situation, merging decls or emitting diagnostics as appropriate.
750///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000751/// Tentative definition rules (C99 6.9.2p2) are checked by
752/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
753/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000754///
Steve Naroffe8043c32008-04-01 23:04:06 +0000755VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 // Verify the old decl was also a variable.
757 VarDecl *Old = dyn_cast<VarDecl>(OldD);
758 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000759 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000760 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000761 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 return New;
763 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000764
765 MergeAttributes(New, Old);
766
Reid Spencer5f016e22007-07-11 17:01:13 +0000767 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000768 QualType OldCType = Context.getCanonicalType(Old->getType());
769 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000770 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000771 Diag(New->getLocation(), diag::err_redefinition_different_type)
772 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000773 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 return New;
775 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000776 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
777 if (New->getStorageClass() == VarDecl::Static &&
778 (Old->getStorageClass() == VarDecl::None ||
779 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000780 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000781 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000782 return New;
783 }
784 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
785 if (New->getStorageClass() != VarDecl::Static &&
786 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000787 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000788 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000789 return New;
790 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000791 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
792 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000793 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000794 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 }
796 return New;
797}
798
Chris Lattner04421082008-04-08 04:40:51 +0000799/// CheckParmsForFunctionDef - Check that the parameters of the given
800/// function are appropriate for the definition of a function. This
801/// takes care of any checks that cannot be performed on the
802/// declaration itself, e.g., that the types of each of the function
803/// parameters are complete.
804bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
805 bool HasInvalidParm = false;
806 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
807 ParmVarDecl *Param = FD->getParamDecl(p);
808
809 // C99 6.7.5.3p4: the parameters in a parameter type list in a
810 // function declarator that is part of a function definition of
811 // that function shall not have incomplete type.
812 if (Param->getType()->isIncompleteType() &&
813 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000814 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000815 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000816 Param->setInvalidDecl();
817 HasInvalidParm = true;
818 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000819
820 // C99 6.9.1p5: If the declarator includes a parameter type list, the
821 // declaration of each parameter shall include an identifier.
822 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
823 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000824 }
825
826 return HasInvalidParm;
827}
828
Reid Spencer5f016e22007-07-11 17:01:13 +0000829/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
830/// no declarator (e.g. "struct foo;") is parsed.
831Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000832 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
833 if (!DS.isMissingDeclaratorOk()) {
834 // FIXME: This diagnostic is emitted even when various previous
835 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
836 // DeclSpec has no means of communicating this information, and the
837 // responsible parser functions are quite far apart.
838 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
839 << DS.getSourceRange();
840 return 0;
841 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000842
843 TagDecl *Tag
844 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
845 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
846 if (!Record->getDeclName() && Record->isDefinition() &&
847 !Record->isInvalidDecl())
848 return BuildAnonymousStructOrUnion(S, DS, Record);
849 }
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000850
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000851 return Tag;
852}
853
854/// InjectAnonymousStructOrUnionMembers - Inject the members of the
855/// anonymous struct or union AnonRecord into the owning context Owner
856/// and scope S. This routine will be invoked just after we realize
857/// that an unnamed union or struct is actually an anonymous union or
858/// struct, e.g.,
859///
860/// @code
861/// union {
862/// int i;
863/// float f;
864/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
865/// // f into the surrounding scope.x
866/// @endcode
867///
868/// This routine is recursive, injecting the names of nested anonymous
869/// structs/unions into the owning context and scope as well.
870bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
871 RecordDecl *AnonRecord) {
872 bool Invalid = false;
873 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
874 FEnd = AnonRecord->field_end();
875 F != FEnd; ++F) {
876 if ((*F)->getDeclName()) {
877 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
878 S, Owner, false, false, false);
879 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
880 // C++ [class.union]p2:
881 // The names of the members of an anonymous union shall be
882 // distinct from the names of any other entity in the
883 // scope in which the anonymous union is declared.
884 unsigned diagKind
885 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
886 : diag::err_anonymous_struct_member_redecl;
887 Diag((*F)->getLocation(), diagKind)
888 << (*F)->getDeclName();
889 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
890 Invalid = true;
891 } else {
892 // C++ [class.union]p2:
893 // For the purpose of name lookup, after the anonymous union
894 // definition, the members of the anonymous union are
895 // considered to have been defined in the scope in which the
896 // anonymous union is declared.
897 Owner->insert(Context, *F);
898 S->AddDecl(*F);
899 IdResolver.AddDecl(*F);
900 }
901 } else if (const RecordType *InnerRecordType
902 = (*F)->getType()->getAsRecordType()) {
903 RecordDecl *InnerRecord = InnerRecordType->getDecl();
904 if (InnerRecord->isAnonymousStructOrUnion())
905 Invalid = Invalid ||
906 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
907 }
908 }
909
910 return Invalid;
911}
912
913/// ActOnAnonymousStructOrUnion - Handle the declaration of an
914/// anonymous structure or union. Anonymous unions are a C++ feature
915/// (C++ [class.union]) and a GNU C extension; anonymous structures
916/// are a GNU C and GNU C++ extension.
917Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
918 RecordDecl *Record) {
919 DeclContext *Owner = Record->getDeclContext();
920
921 // Diagnose whether this anonymous struct/union is an extension.
922 if (Record->isUnion() && !getLangOptions().CPlusPlus)
923 Diag(Record->getLocation(), diag::ext_anonymous_union);
924 else if (!Record->isUnion())
925 Diag(Record->getLocation(), diag::ext_anonymous_struct);
926
927 // C and C++ require different kinds of checks for anonymous
928 // structs/unions.
929 bool Invalid = false;
930 if (getLangOptions().CPlusPlus) {
931 const char* PrevSpec = 0;
932 // C++ [class.union]p3:
933 // Anonymous unions declared in a named namespace or in the
934 // global namespace shall be declared static.
935 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
936 (isa<TranslationUnitDecl>(Owner) ||
937 (isa<NamespaceDecl>(Owner) &&
938 cast<NamespaceDecl>(Owner)->getDeclName()))) {
939 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
940 Invalid = true;
941
942 // Recover by adding 'static'.
943 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
944 }
945 // C++ [class.union]p3:
946 // A storage class is not allowed in a declaration of an
947 // anonymous union in a class scope.
948 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
949 isa<RecordDecl>(Owner)) {
950 Diag(DS.getStorageClassSpecLoc(),
951 diag::err_anonymous_union_with_storage_spec);
952 Invalid = true;
953
954 // Recover by removing the storage specifier.
955 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
956 PrevSpec);
957 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000958
959 // C++ [class.union]p2:
960 // The member-specification of an anonymous union shall only
961 // define non-static data members. [Note: nested types and
962 // functions cannot be declared within an anonymous union. ]
963 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
964 MemEnd = Record->decls_end();
965 Mem != MemEnd; ++Mem) {
966 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
967 // C++ [class.union]p3:
968 // An anonymous union shall not have private or protected
969 // members (clause 11).
970 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
971 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
972 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
973 Invalid = true;
974 }
975 } else if ((*Mem)->isImplicit()) {
976 // Any implicit members are fine.
977 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
978 if (!MemRecord->isAnonymousStructOrUnion() &&
979 MemRecord->getDeclName()) {
980 // This is a nested type declaration.
981 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
982 << (int)Record->isUnion();
983 Invalid = true;
984 }
985 } else {
986 // We have something that isn't a non-static data
987 // member. Complain about it.
988 unsigned DK = diag::err_anonymous_record_bad_member;
989 if (isa<TypeDecl>(*Mem))
990 DK = diag::err_anonymous_record_with_type;
991 else if (isa<FunctionDecl>(*Mem))
992 DK = diag::err_anonymous_record_with_function;
993 else if (isa<VarDecl>(*Mem))
994 DK = diag::err_anonymous_record_with_static;
995 Diag((*Mem)->getLocation(), DK)
996 << (int)Record->isUnion();
997 Invalid = true;
998 }
999 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001000 } else {
1001 // FIXME: Check GNU C semantics
1002 }
1003
1004 if (!Record->isUnion() && !Owner->isRecord()) {
1005 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
1006 Invalid = true;
1007 }
1008
1009 // Create a declaration for this anonymous struct/union.
1010 ScopedDecl *Anon = 0;
1011 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1012 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1013 /*IdentifierInfo=*/0,
1014 Context.getTypeDeclType(Record),
1015 /*BitWidth=*/0, /*Mutable=*/false,
1016 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001017 Anon->setAccess(AS_public);
1018 if (getLangOptions().CPlusPlus)
1019 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001020 } else {
1021 VarDecl::StorageClass SC;
1022 switch (DS.getStorageClassSpec()) {
1023 default: assert(0 && "Unknown storage class!");
1024 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1025 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1026 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1027 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1028 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1029 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1030 case DeclSpec::SCS_mutable:
1031 // mutable can only appear on non-static class members, so it's always
1032 // an error here
1033 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1034 Invalid = true;
1035 SC = VarDecl::None;
1036 break;
1037 }
1038
1039 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1040 /*IdentifierInfo=*/0,
1041 Context.getTypeDeclType(Record),
1042 SC, /*FIXME:LastDeclarator=*/0,
1043 DS.getSourceRange().getBegin());
1044 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001045 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001046
1047 // Add the anonymous struct/union object to the current
1048 // context. We'll be referencing this object when we refer to one of
1049 // its members.
1050 Owner->addDecl(Context, Anon);
1051
1052 // Inject the members of the anonymous struct/union into the owning
1053 // context and into the identifier resolver chain for name lookup
1054 // purposes.
1055 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1056
1057 // Mark this as an anonymous struct/union type. Note that we do not
1058 // do this until after we have already checked and injected the
1059 // members of this anonymous struct/union type, because otherwise
1060 // the members could be injected twice: once by DeclContext when it
1061 // builds its lookup table, and once by
1062 // InjectAnonymousStructOrUnionMembers.
1063 Record->setAnonymousStructOrUnion(true);
1064
1065 if (Invalid)
1066 Anon->setInvalidDecl();
1067
1068 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001069}
1070
Steve Naroffd0091aa2008-01-10 22:15:12 +00001071bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +00001072 // Get the type before calling CheckSingleAssignmentConstraints(), since
1073 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001074 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001075
1076 if (getLangOptions().CPlusPlus)
1077 return PerformCopyInitialization(Init, DeclType, "initializing");
1078
Chris Lattner5cf216b2008-01-04 18:04:52 +00001079 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1080 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1081 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001082}
1083
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001084bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001085 const ArrayType *AT = Context.getAsArrayType(DeclT);
1086
1087 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001088 // C99 6.7.8p14. We have an array of character type with unknown size
1089 // being initialized to a string literal.
1090 llvm::APSInt ConstVal(32);
1091 ConstVal = strLiteral->getByteLength() + 1;
1092 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001093 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001094 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001095 } else {
1096 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001097 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001098 // FIXME: Avoid truncation for 64-bit length strings.
1099 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001100 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001101 diag::warn_initializer_string_for_char_array_too_long)
1102 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001103 }
1104 // Set type from "char *" to "constant array of char".
1105 strLiteral->setType(DeclT);
1106 // For now, we always return false (meaning success).
1107 return false;
1108}
1109
1110StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001111 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001112 if (AT && AT->getElementType()->isCharType()) {
1113 return dyn_cast<StringLiteral>(Init);
1114 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001115 return 0;
1116}
1117
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001118bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1119 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001121 if (DeclType->isDependentType() || Init->isTypeDependent())
1122 return false;
1123
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001124 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001125 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001126 // (8.3.2), shall be initialized by an object, or function, of
1127 // type T or by an object that can be converted into a T.
1128 if (DeclType->isReferenceType())
1129 return CheckReferenceInit(Init, DeclType);
1130
Steve Naroffca107302008-01-21 23:53:58 +00001131 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1132 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001133 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001134 return Diag(InitLoc, diag::err_variable_object_no_init)
1135 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001136
Steve Naroff2fdc3742007-12-10 22:44:33 +00001137 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1138 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001139 // FIXME: Handle wide strings
1140 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1141 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001142
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001143 // C++ [dcl.init]p14:
1144 // -- If the destination type is a (possibly cv-qualified) class
1145 // type:
1146 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1147 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1148 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1149
1150 // -- If the initialization is direct-initialization, or if it is
1151 // copy-initialization where the cv-unqualified version of the
1152 // source type is the same class as, or a derived class of, the
1153 // class of the destination, constructors are considered.
1154 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1155 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1156 CXXConstructorDecl *Constructor
1157 = PerformInitializationByConstructor(DeclType, &Init, 1,
1158 InitLoc, Init->getSourceRange(),
1159 InitEntity, IK_Copy);
1160 return Constructor == 0;
1161 }
1162
1163 // -- Otherwise (i.e., for the remaining copy-initialization
1164 // cases), user-defined conversion sequences that can
1165 // convert from the source type to the destination type or
1166 // (when a conversion function is used) to a derived class
1167 // thereof are enumerated as described in 13.3.1.4, and the
1168 // best one is chosen through overload resolution
1169 // (13.3). If the conversion cannot be done or is
1170 // ambiguous, the initialization is ill-formed. The
1171 // function selected is called with the initializer
1172 // expression as its argument; if the function is a
1173 // constructor, the call initializes a temporary of the
1174 // destination type.
1175 // FIXME: We're pretending to do copy elision here; return to
1176 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001177 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001178 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001179
Douglas Gregor61366e92008-12-24 00:01:03 +00001180 if (InitEntity)
1181 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1182 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1183 << Init->getType() << Init->getSourceRange();
1184 else
1185 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1186 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1187 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001188 }
1189
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001190 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001191 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001192 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1193 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001194
Steve Naroffd0091aa2008-01-10 22:15:12 +00001195 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001196 } else if (getLangOptions().CPlusPlus) {
1197 // C++ [dcl.init]p14:
1198 // [...] If the class is an aggregate (8.5.1), and the initializer
1199 // is a brace-enclosed list, see 8.5.1.
1200 //
1201 // Note: 8.5.1 is handled below; here, we diagnose the case where
1202 // we have an initializer list and a destination type that is not
1203 // an aggregate.
1204 // FIXME: In C++0x, this is yet another form of initialization.
1205 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1206 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1207 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001208 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001209 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001210 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001211 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001212
Steve Naroff0cca7492008-05-01 22:18:59 +00001213 InitListChecker CheckInitList(this, InitList, DeclType);
1214 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001215}
1216
Douglas Gregor10bd3682008-11-17 22:58:34 +00001217/// GetNameForDeclarator - Determine the full declaration name for the
1218/// given Declarator.
1219DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1220 switch (D.getKind()) {
1221 case Declarator::DK_Abstract:
1222 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1223 return DeclarationName();
1224
1225 case Declarator::DK_Normal:
1226 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1227 return DeclarationName(D.getIdentifier());
1228
1229 case Declarator::DK_Constructor: {
1230 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1231 Ty = Context.getCanonicalType(Ty);
1232 return Context.DeclarationNames.getCXXConstructorName(Ty);
1233 }
1234
1235 case Declarator::DK_Destructor: {
1236 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1237 Ty = Context.getCanonicalType(Ty);
1238 return Context.DeclarationNames.getCXXDestructorName(Ty);
1239 }
1240
1241 case Declarator::DK_Conversion: {
1242 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1243 Ty = Context.getCanonicalType(Ty);
1244 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1245 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001246
1247 case Declarator::DK_Operator:
1248 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1249 return Context.DeclarationNames.getCXXOperatorName(
1250 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001251 }
1252
1253 assert(false && "Unknown name kind");
1254 return DeclarationName();
1255}
1256
Douglas Gregor584049d2008-12-15 23:53:10 +00001257/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1258/// functions Declaration and Definition are "nearly" matching. This
1259/// heuristic is used to improve diagnostics in the case where an
1260/// out-of-line member function definition doesn't match any
1261/// declaration within the class.
1262static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1263 FunctionDecl *Declaration,
1264 FunctionDecl *Definition) {
1265 if (Declaration->param_size() != Definition->param_size())
1266 return false;
1267 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1268 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1269 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1270
1271 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1272 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1273 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1274 return false;
1275 }
1276
1277 return true;
1278}
1279
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001280Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001281Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1282 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001283 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001284 DeclarationName Name = GetNameForDeclarator(D);
1285
Chris Lattnere80a59c2007-07-25 00:24:17 +00001286 // All of these full declarators require an identifier. If it doesn't have
1287 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001288 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001289 if (!D.getInvalidType()) // Reject this if we think it is valid.
1290 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001291 diag::err_declarator_need_ident)
1292 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001293 return 0;
1294 }
1295
Chris Lattner31e05722007-08-26 06:24:45 +00001296 // The scope passed in may not be a decl scope. Zip up the scope tree until
1297 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001298 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1299 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001300 S = S->getParent();
1301
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001302 DeclContext *DC;
1303 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001304 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001305 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001306
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001307 // See if this is a redefinition of a variable in the same scope.
1308 if (!D.getCXXScopeSpec().isSet()) {
1309 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001310 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001311 } else { // Something like "int foo::x;"
1312 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001313 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001314
1315 // C++ 7.3.1.2p2:
1316 // Members (including explicit specializations of templates) of a named
1317 // namespace can also be defined outside that namespace by explicit
1318 // qualification of the name being defined, provided that the entity being
1319 // defined was already declared in the namespace and the definition appears
1320 // after the point of declaration in a namespace that encloses the
1321 // declarations namespace.
1322 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001323 // Note that we only check the context at this point. We don't yet
1324 // have enough information to make sure that PrevDecl is actually
1325 // the declaration we want to match. For example, given:
1326 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001327 // class X {
1328 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001329 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001330 // };
1331 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001332 // void X::f(int) { } // ill-formed
1333 //
1334 // In this case, PrevDecl will point to the overload set
1335 // containing the two f's declared in X, but neither of them
1336 // matches.
1337 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001338 // The qualifying scope doesn't enclose the original declaration.
1339 // Emit diagnostic based on current scope.
1340 SourceLocation L = D.getIdentifierLoc();
1341 SourceRange R = D.getCXXScopeSpec().getRange();
1342 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001343 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001344 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001345 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001346 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001347 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001348 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001349 }
1350 }
1351
Douglas Gregorf57172b2008-12-08 18:40:42 +00001352 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001353 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001354 InvalidDecl = InvalidDecl
1355 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001356 // Just pretend that we didn't see the previous declaration.
1357 PrevDecl = 0;
1358 }
1359
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001360 // In C++, the previous declaration we find might be a tag type
1361 // (class or enum). In this case, the new declaration will hide the
1362 // tag type.
1363 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1364 PrevDecl = 0;
1365
Chris Lattner41af0932007-11-14 06:34:38 +00001366 QualType R = GetTypeForDeclarator(D, S);
1367 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001370 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1371 if (D.getCXXScopeSpec().isSet()) {
1372 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1373 << D.getCXXScopeSpec().getRange();
1374 InvalidDecl = true;
1375 // Pretend we didn't see the scope specifier.
1376 DC = 0;
1377 }
1378
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001379 // Check that there are no default arguments (C++ only).
1380 if (getLangOptions().CPlusPlus)
1381 CheckExtraCXXDefaultArguments(D);
1382
Chris Lattner41af0932007-11-14 06:34:38 +00001383 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 if (!NewTD) return 0;
1385
1386 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001387 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001388 // Merge the decl with the existing one if appropriate. If the decl is
1389 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001390 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1392 if (NewTD == 0) return 0;
1393 }
1394 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001395 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1397 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001398 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001399 if (NewTD->getUnderlyingType()->isVariableArrayType())
1400 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1401 else
1402 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1403
Steve Naroffd7444aa2007-08-31 17:20:07 +00001404 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 }
1406 }
Chris Lattner41af0932007-11-14 06:34:38 +00001407 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001408 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 switch (D.getDeclSpec().getStorageClassSpec()) {
1410 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001411 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001413 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001414 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001415 InvalidDecl = true;
1416 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1418 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1419 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001420 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 }
1422
Chris Lattnera98e58d2008-03-15 21:24:04 +00001423 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001424 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001425 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1426
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001427 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001428 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001429 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001430 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001431 "Constructors can only be declared in a member context");
1432
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001433 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001434
1435 // Create the new declaration
1436 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001437 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001438 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001439 isExplicit, isInline,
1440 /*isImplicitlyDeclared=*/false);
1441
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001442 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001443 NewFD->setInvalidDecl();
1444 } else if (D.getKind() == Declarator::DK_Destructor) {
1445 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001446 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001447 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001448
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001449 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001450 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001451 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001452 isInline,
1453 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001454
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001455 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001456 NewFD->setInvalidDecl();
1457 } else {
1458 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001459
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001460 // Create a FunctionDecl to satisfy the function definition parsing
1461 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001462 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001463 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001464 // FIXME: Move to DeclGroup...
1465 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001466 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001467 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001468 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001469 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001470 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001471 Diag(D.getIdentifierLoc(),
1472 diag::err_conv_function_not_member);
1473 return 0;
1474 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001475 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001476
Douglas Gregor70316a02008-12-26 15:00:45 +00001477 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001478 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001479 isInline, isExplicit);
1480
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001481 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001482 NewFD->setInvalidDecl();
1483 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001484 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001485 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001486 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001487 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001488 (SC == FunctionDecl::Static), isInline,
1489 LastDeclarator);
1490 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001491 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001493 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001494 // FIXME: Move to DeclGroup...
1495 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001496 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001497
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001498 // Set the lexical context. If the declarator has a C++
1499 // scope specifier, the lexical context will be different
1500 // from the semantic context.
1501 NewFD->setLexicalDeclContext(CurContext);
1502
Daniel Dunbara80f8742008-08-05 01:35:17 +00001503 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001504 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001505 // The parser guarantees this is a string.
1506 StringLiteral *SE = cast<StringLiteral>(E);
1507 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1508 SE->getByteLength())));
1509 }
1510
Chris Lattner04421082008-04-08 04:40:51 +00001511 // Copy the parameter declarations from the declarator D to
1512 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001513 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001514 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1515
1516 // Create Decl objects for each parameter, adding them to the
1517 // FunctionDecl.
1518 llvm::SmallVector<ParmVarDecl*, 16> Params;
1519
1520 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1521 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001522 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001523 // We let through "const void" here because Sema::GetTypeForDeclarator
1524 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001525 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1526 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001527 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1528 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001529 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1530
Chris Lattnerdef026a2008-04-10 02:26:16 +00001531 // In C++, the empty parameter-type-list must be spelled "void"; a
1532 // typedef of void is not permitted.
1533 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001534 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001535 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1536 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001537 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001538 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1539 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1540 }
1541
1542 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001543 } else if (R->getAsTypedefType()) {
1544 // When we're declaring a function with a typedef, as in the
1545 // following example, we'll need to synthesize (unnamed)
1546 // parameters for use in the declaration.
1547 //
1548 // @code
1549 // typedef void fn(int);
1550 // fn f;
1551 // @endcode
1552 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1553 if (!FT) {
1554 // This is a typedef of a function with no prototype, so we
1555 // don't need to do anything.
1556 } else if ((FT->getNumArgs() == 0) ||
1557 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1558 FT->getArgType(0)->isVoidType())) {
1559 // This is a zero-argument function. We don't need to do anything.
1560 } else {
1561 // Synthesize a parameter for each argument type.
1562 llvm::SmallVector<ParmVarDecl*, 16> Params;
1563 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1564 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001565 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001566 SourceLocation(), 0,
1567 *ArgType, VarDecl::None,
1568 0, 0));
1569 }
1570
1571 NewFD->setParams(&Params[0], Params.size());
1572 }
Chris Lattner04421082008-04-08 04:40:51 +00001573 }
1574
Douglas Gregor72b505b2008-12-16 21:30:33 +00001575 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1576 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001577 else if (isa<CXXDestructorDecl>(NewFD)) {
1578 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1579 Record->setUserDeclaredDestructor(true);
1580 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1581 // user-defined destructor.
1582 Record->setPOD(false);
1583 } else if (CXXConversionDecl *Conversion =
1584 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001585 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001586
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001587 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1588 if (NewFD->isOverloadedOperator() &&
1589 CheckOverloadedOperatorDeclaration(NewFD))
1590 NewFD->setInvalidDecl();
1591
Steve Naroffffce4d52008-01-09 23:34:55 +00001592 // Merge the decl with the existing one if appropriate. Since C functions
1593 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001594 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001595 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001596 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001597
1598 // If C++, determine whether NewFD is an overload of PrevDecl or
1599 // a declaration that requires merging. If it's an overload,
1600 // there's no more work to do here; we'll just add the new
1601 // function to the scope.
1602 OverloadedFunctionDecl::function_iterator MatchedDecl;
1603 if (!getLangOptions().CPlusPlus ||
1604 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1605 Decl *OldDecl = PrevDecl;
1606
1607 // If PrevDecl was an overloaded function, extract the
1608 // FunctionDecl that matched.
1609 if (isa<OverloadedFunctionDecl>(PrevDecl))
1610 OldDecl = *MatchedDecl;
1611
1612 // NewFD and PrevDecl represent declarations that need to be
1613 // merged.
1614 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1615
1616 if (NewFD == 0) return 0;
1617 if (Redeclaration) {
1618 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1619
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001620 // An out-of-line member function declaration must also be a
1621 // definition (C++ [dcl.meaning]p1).
1622 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1623 !InvalidDecl) {
1624 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1625 << D.getCXXScopeSpec().getRange();
1626 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001627 }
1628 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001629 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001630
1631 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1632 // The user tried to provide an out-of-line definition for a
1633 // member function, but there was no such member function
1634 // declared (C++ [class.mfct]p2). For example:
1635 //
1636 // class X {
1637 // void f() const;
1638 // };
1639 //
1640 // void X::f() { } // ill-formed
1641 //
1642 // Complain about this problem, and attempt to suggest close
1643 // matches (e.g., those that differ only in cv-qualifiers and
1644 // whether the parameter types are references).
1645 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1646 << cast<CXXRecordDecl>(DC)->getDeclName()
1647 << D.getCXXScopeSpec().getRange();
1648 InvalidDecl = true;
1649
1650 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1651 if (!PrevDecl) {
1652 // Nothing to suggest.
1653 } else if (OverloadedFunctionDecl *Ovl
1654 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1655 for (OverloadedFunctionDecl::function_iterator
1656 Func = Ovl->function_begin(),
1657 FuncEnd = Ovl->function_end();
1658 Func != FuncEnd; ++Func) {
1659 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1660 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1661
1662 }
1663 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1664 // Suggest this no matter how mismatched it is; it's the only
1665 // thing we have.
1666 unsigned diag;
1667 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1668 diag = diag::note_member_def_close_match;
1669 else if (Method->getBody())
1670 diag = diag::note_previous_definition;
1671 else
1672 diag = diag::note_previous_declaration;
1673 Diag(Method->getLocation(), diag);
1674 }
1675
1676 PrevDecl = 0;
1677 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001679 // Handle attributes. We need to have merged decls when handling attributes
1680 // (for example to check for conflicts, etc).
1681 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001683
Douglas Gregor584049d2008-12-15 23:53:10 +00001684 if (getLangOptions().CPlusPlus) {
1685 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001686 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001687
1688 // An out-of-line member function declaration must also be a
1689 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001690 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001691 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1692 << D.getCXXScopeSpec().getRange();
1693 InvalidDecl = true;
1694 }
1695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001697 // Check that there are no default arguments (C++ only).
1698 if (getLangOptions().CPlusPlus)
1699 CheckExtraCXXDefaultArguments(D);
1700
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001701 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001702 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1703 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001704 InvalidDecl = true;
1705 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001706
1707 VarDecl *NewVD;
1708 VarDecl::StorageClass SC;
1709 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001710 default: assert(0 && "Unknown storage class!");
1711 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1712 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1713 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1714 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1715 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1716 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001717 case DeclSpec::SCS_mutable:
1718 // mutable can only appear on non-static class members, so it's always
1719 // an error here
1720 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1721 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001722 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001723 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001724 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001725
1726 IdentifierInfo *II = Name.getAsIdentifierInfo();
1727 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001728 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1729 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001730 return 0;
1731 }
1732
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001733 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001734 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001735 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001736 D.getIdentifierLoc(), II,
1737 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001738 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001739 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001740 if (S->getFnParent() == 0) {
1741 // C99 6.9p2: The storage-class specifiers auto and register shall not
1742 // appear in the declaration specifiers in an external declaration.
1743 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001744 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001745 InvalidDecl = true;
1746 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001747 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001748 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1749 II, R, SC, LastDeclarator,
1750 // FIXME: Move to DeclGroup...
1751 D.getDeclSpec().getSourceRange().getBegin());
1752 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001753 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001755 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001756
Daniel Dunbara735ad82008-08-06 00:03:29 +00001757 // Handle GNU asm-label extension (encoded as an attribute).
1758 if (Expr *E = (Expr*) D.getAsmLabel()) {
1759 // The parser guarantees this is a string.
1760 StringLiteral *SE = cast<StringLiteral>(E);
1761 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1762 SE->getByteLength())));
1763 }
1764
Nate Begemanc8e89a82008-03-14 18:07:10 +00001765 // Emit an error if an address space was applied to decl with local storage.
1766 // This includes arrays of objects with address space qualifiers, but not
1767 // automatic variables that point to other address spaces.
1768 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001769 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1770 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1771 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001772 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001773 // Merge the decl with the existing one if appropriate. If the decl is
1774 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001775 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001776 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1777 // The user tried to define a non-static data member
1778 // out-of-line (C++ [dcl.meaning]p1).
1779 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1780 << D.getCXXScopeSpec().getRange();
1781 NewVD->Destroy(Context);
1782 return 0;
1783 }
1784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 NewVD = MergeVarDecl(NewVD, PrevDecl);
1786 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001787
1788 if (D.getCXXScopeSpec().isSet()) {
1789 // No previous declaration in the qualifying scope.
1790 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1791 << Name << D.getCXXScopeSpec().getRange();
1792 InvalidDecl = true;
1793 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001795 New = NewVD;
1796 }
1797
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001798 // Set the lexical context. If the declarator has a C++ scope specifier, the
1799 // lexical context will be different from the semantic context.
1800 New->setLexicalDeclContext(CurContext);
1801
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001803 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001804 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001805 // If any semantic error occurred, mark the decl as invalid.
1806 if (D.getInvalidType() || InvalidDecl)
1807 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001808
1809 return New;
1810}
1811
Steve Naroff6594a702008-10-27 11:34:16 +00001812void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001813 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1814 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001815}
1816
Eli Friedmanc594b322008-05-20 13:48:25 +00001817bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1818 switch (Init->getStmtClass()) {
1819 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001820 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001821 return true;
1822 case Expr::ParenExprClass: {
1823 const ParenExpr* PE = cast<ParenExpr>(Init);
1824 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1825 }
1826 case Expr::CompoundLiteralExprClass:
1827 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001828 case Expr::DeclRefExprClass:
1829 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001830 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001831 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1832 if (VD->hasGlobalStorage())
1833 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001834 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001835 return true;
1836 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001837 if (isa<FunctionDecl>(D))
1838 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001839 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001840 return true;
1841 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001842 case Expr::MemberExprClass: {
1843 const MemberExpr *M = cast<MemberExpr>(Init);
1844 if (M->isArrow())
1845 return CheckAddressConstantExpression(M->getBase());
1846 return CheckAddressConstantExpressionLValue(M->getBase());
1847 }
1848 case Expr::ArraySubscriptExprClass: {
1849 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1850 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1851 return CheckAddressConstantExpression(ASE->getBase()) ||
1852 CheckArithmeticConstantExpression(ASE->getIdx());
1853 }
1854 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001855 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001856 return false;
1857 case Expr::UnaryOperatorClass: {
1858 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1859
1860 // C99 6.6p9
1861 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001862 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001863
Steve Naroff6594a702008-10-27 11:34:16 +00001864 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001865 return true;
1866 }
1867 }
1868}
1869
1870bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1871 switch (Init->getStmtClass()) {
1872 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001873 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001874 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001875 case Expr::ParenExprClass:
1876 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001877 case Expr::StringLiteralClass:
1878 case Expr::ObjCStringLiteralClass:
1879 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001880 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001881 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001882 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1883 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1884 Builtin::BI__builtin___CFStringMakeConstantString)
1885 return false;
1886
Steve Naroff6594a702008-10-27 11:34:16 +00001887 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001888 return true;
1889
Eli Friedmanc594b322008-05-20 13:48:25 +00001890 case Expr::UnaryOperatorClass: {
1891 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1892
1893 // C99 6.6p9
1894 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1895 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1896
1897 if (Exp->getOpcode() == UnaryOperator::Extension)
1898 return CheckAddressConstantExpression(Exp->getSubExpr());
1899
Steve Naroff6594a702008-10-27 11:34:16 +00001900 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001901 return true;
1902 }
1903 case Expr::BinaryOperatorClass: {
1904 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1905 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1906
1907 Expr *PExp = Exp->getLHS();
1908 Expr *IExp = Exp->getRHS();
1909 if (IExp->getType()->isPointerType())
1910 std::swap(PExp, IExp);
1911
1912 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1913 return CheckAddressConstantExpression(PExp) ||
1914 CheckArithmeticConstantExpression(IExp);
1915 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001916 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001917 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001918 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001919 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1920 // Check for implicit promotion
1921 if (SubExpr->getType()->isFunctionType() ||
1922 SubExpr->getType()->isArrayType())
1923 return CheckAddressConstantExpressionLValue(SubExpr);
1924 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001925
1926 // Check for pointer->pointer cast
1927 if (SubExpr->getType()->isPointerType())
1928 return CheckAddressConstantExpression(SubExpr);
1929
Eli Friedmanc3f07642008-08-25 20:46:57 +00001930 if (SubExpr->getType()->isIntegralType()) {
1931 // Check for the special-case of a pointer->int->pointer cast;
1932 // this isn't standard, but some code requires it. See
1933 // PR2720 for an example.
1934 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1935 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1936 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1937 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1938 if (IntWidth >= PointerWidth) {
1939 return CheckAddressConstantExpression(SubCast->getSubExpr());
1940 }
1941 }
1942 }
1943 }
1944 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001945 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001946 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001947
Steve Naroff6594a702008-10-27 11:34:16 +00001948 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001949 return true;
1950 }
1951 case Expr::ConditionalOperatorClass: {
1952 // FIXME: Should we pedwarn here?
1953 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1954 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001955 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001956 return true;
1957 }
1958 if (CheckArithmeticConstantExpression(Exp->getCond()))
1959 return true;
1960 if (Exp->getLHS() &&
1961 CheckAddressConstantExpression(Exp->getLHS()))
1962 return true;
1963 return CheckAddressConstantExpression(Exp->getRHS());
1964 }
1965 case Expr::AddrLabelExprClass:
1966 return false;
1967 }
1968}
1969
Eli Friedman4caf0552008-06-09 05:05:07 +00001970static const Expr* FindExpressionBaseAddress(const Expr* E);
1971
1972static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1973 switch (E->getStmtClass()) {
1974 default:
1975 return E;
1976 case Expr::ParenExprClass: {
1977 const ParenExpr* PE = cast<ParenExpr>(E);
1978 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1979 }
1980 case Expr::MemberExprClass: {
1981 const MemberExpr *M = cast<MemberExpr>(E);
1982 if (M->isArrow())
1983 return FindExpressionBaseAddress(M->getBase());
1984 return FindExpressionBaseAddressLValue(M->getBase());
1985 }
1986 case Expr::ArraySubscriptExprClass: {
1987 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1988 return FindExpressionBaseAddress(ASE->getBase());
1989 }
1990 case Expr::UnaryOperatorClass: {
1991 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1992
1993 if (Exp->getOpcode() == UnaryOperator::Deref)
1994 return FindExpressionBaseAddress(Exp->getSubExpr());
1995
1996 return E;
1997 }
1998 }
1999}
2000
2001static const Expr* FindExpressionBaseAddress(const Expr* E) {
2002 switch (E->getStmtClass()) {
2003 default:
2004 return E;
2005 case Expr::ParenExprClass: {
2006 const ParenExpr* PE = cast<ParenExpr>(E);
2007 return FindExpressionBaseAddress(PE->getSubExpr());
2008 }
2009 case Expr::UnaryOperatorClass: {
2010 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2011
2012 // C99 6.6p9
2013 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2014 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2015
2016 if (Exp->getOpcode() == UnaryOperator::Extension)
2017 return FindExpressionBaseAddress(Exp->getSubExpr());
2018
2019 return E;
2020 }
2021 case Expr::BinaryOperatorClass: {
2022 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2023
2024 Expr *PExp = Exp->getLHS();
2025 Expr *IExp = Exp->getRHS();
2026 if (IExp->getType()->isPointerType())
2027 std::swap(PExp, IExp);
2028
2029 return FindExpressionBaseAddress(PExp);
2030 }
2031 case Expr::ImplicitCastExprClass: {
2032 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2033
2034 // Check for implicit promotion
2035 if (SubExpr->getType()->isFunctionType() ||
2036 SubExpr->getType()->isArrayType())
2037 return FindExpressionBaseAddressLValue(SubExpr);
2038
2039 // Check for pointer->pointer cast
2040 if (SubExpr->getType()->isPointerType())
2041 return FindExpressionBaseAddress(SubExpr);
2042
2043 // We assume that we have an arithmetic expression here;
2044 // if we don't, we'll figure it out later
2045 return 0;
2046 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002047 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002048 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2049
2050 // Check for pointer->pointer cast
2051 if (SubExpr->getType()->isPointerType())
2052 return FindExpressionBaseAddress(SubExpr);
2053
2054 // We assume that we have an arithmetic expression here;
2055 // if we don't, we'll figure it out later
2056 return 0;
2057 }
2058 }
2059}
2060
Anders Carlsson51fe9962008-11-22 21:04:56 +00002061bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002062 switch (Init->getStmtClass()) {
2063 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002064 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002065 return true;
2066 case Expr::ParenExprClass: {
2067 const ParenExpr* PE = cast<ParenExpr>(Init);
2068 return CheckArithmeticConstantExpression(PE->getSubExpr());
2069 }
2070 case Expr::FloatingLiteralClass:
2071 case Expr::IntegerLiteralClass:
2072 case Expr::CharacterLiteralClass:
2073 case Expr::ImaginaryLiteralClass:
2074 case Expr::TypesCompatibleExprClass:
2075 case Expr::CXXBoolLiteralExprClass:
2076 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002077 case Expr::CallExprClass:
2078 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002079 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002080
2081 // Allow any constant foldable calls to builtins.
2082 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002083 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002084
Steve Naroff6594a702008-10-27 11:34:16 +00002085 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002086 return true;
2087 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002088 case Expr::DeclRefExprClass:
2089 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002090 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2091 if (isa<EnumConstantDecl>(D))
2092 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002093 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002094 return true;
2095 }
2096 case Expr::CompoundLiteralExprClass:
2097 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2098 // but vectors are allowed to be magic.
2099 if (Init->getType()->isVectorType())
2100 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002101 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002102 return true;
2103 case Expr::UnaryOperatorClass: {
2104 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2105
2106 switch (Exp->getOpcode()) {
2107 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2108 // See C99 6.6p3.
2109 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002110 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002111 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002112 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002113 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2114 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002115 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002116 return true;
2117 case UnaryOperator::Extension:
2118 case UnaryOperator::LNot:
2119 case UnaryOperator::Plus:
2120 case UnaryOperator::Minus:
2121 case UnaryOperator::Not:
2122 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2123 }
2124 }
Sebastian Redl05189992008-11-11 17:56:53 +00002125 case Expr::SizeOfAlignOfExprClass: {
2126 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002127 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002128 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002129 return false;
2130 // alignof always evaluates to a constant.
2131 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002132 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002133 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002134 return true;
2135 }
2136 return false;
2137 }
2138 case Expr::BinaryOperatorClass: {
2139 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2140
2141 if (Exp->getLHS()->getType()->isArithmeticType() &&
2142 Exp->getRHS()->getType()->isArithmeticType()) {
2143 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2144 CheckArithmeticConstantExpression(Exp->getRHS());
2145 }
2146
Eli Friedman4caf0552008-06-09 05:05:07 +00002147 if (Exp->getLHS()->getType()->isPointerType() &&
2148 Exp->getRHS()->getType()->isPointerType()) {
2149 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2150 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2151
2152 // Only allow a null (constant integer) base; we could
2153 // allow some additional cases if necessary, but this
2154 // is sufficient to cover offsetof-like constructs.
2155 if (!LHSBase && !RHSBase) {
2156 return CheckAddressConstantExpression(Exp->getLHS()) ||
2157 CheckAddressConstantExpression(Exp->getRHS());
2158 }
2159 }
2160
Steve Naroff6594a702008-10-27 11:34:16 +00002161 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002162 return true;
2163 }
2164 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002165 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002166 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002167 if (SubExpr->getType()->isArithmeticType())
2168 return CheckArithmeticConstantExpression(SubExpr);
2169
Eli Friedmanb529d832008-09-02 09:37:00 +00002170 if (SubExpr->getType()->isPointerType()) {
2171 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2172 // If the pointer has a null base, this is an offsetof-like construct
2173 if (!Base)
2174 return CheckAddressConstantExpression(SubExpr);
2175 }
2176
Steve Naroff6594a702008-10-27 11:34:16 +00002177 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002178 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002179 }
2180 case Expr::ConditionalOperatorClass: {
2181 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002182
2183 // If GNU extensions are disabled, we require all operands to be arithmetic
2184 // constant expressions.
2185 if (getLangOptions().NoExtensions) {
2186 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2187 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2188 CheckArithmeticConstantExpression(Exp->getRHS());
2189 }
2190
2191 // Otherwise, we have to emulate some of the behavior of fold here.
2192 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2193 // because it can constant fold things away. To retain compatibility with
2194 // GCC code, we see if we can fold the condition to a constant (which we
2195 // should always be able to do in theory). If so, we only require the
2196 // specified arm of the conditional to be a constant. This is a horrible
2197 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002198 Expr::EvalResult EvalResult;
2199 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2200 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002201 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002202 // won't be able to either. Use it to emit the diagnostic though.
2203 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002204 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002205 return Res;
2206 }
2207
2208 // Verify that the side following the condition is also a constant.
2209 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002210 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002211 std::swap(TrueSide, FalseSide);
2212
2213 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002214 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002215
2216 // Okay, the evaluated side evaluates to a constant, so we accept this.
2217 // Check to see if the other side is obviously not a constant. If so,
2218 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002219 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002220 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002221 diag::ext_typecheck_expression_not_constant_but_accepted)
2222 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002223 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002224 }
2225 }
2226}
2227
2228bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002229 Expr::EvalResult Result;
2230
Nuno Lopes9a979c32008-07-07 16:46:50 +00002231 Init = Init->IgnoreParens();
2232
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002233 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2234 return false;
2235
Eli Friedmanc594b322008-05-20 13:48:25 +00002236 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2237 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2238 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2239
Nuno Lopes9a979c32008-07-07 16:46:50 +00002240 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2241 return CheckForConstantInitializer(e->getInitializer(), DclT);
2242
Eli Friedmanc594b322008-05-20 13:48:25 +00002243 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2244 unsigned numInits = Exp->getNumInits();
2245 for (unsigned i = 0; i < numInits; i++) {
2246 // FIXME: Need to get the type of the declaration for C++,
2247 // because it could be a reference?
2248 if (CheckForConstantInitializer(Exp->getInit(i),
2249 Exp->getInit(i)->getType()))
2250 return true;
2251 }
2252 return false;
2253 }
2254
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002255 // FIXME: We can probably remove some of this code below, now that
2256 // Expr::Evaluate is doing the heavy lifting for scalars.
2257
Eli Friedmanc594b322008-05-20 13:48:25 +00002258 if (Init->isNullPointerConstant(Context))
2259 return false;
2260 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002261 QualType InitTy = Context.getCanonicalType(Init->getType())
2262 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002263 if (InitTy == Context.BoolTy) {
2264 // Special handling for pointers implicitly cast to bool;
2265 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2266 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2267 Expr* SubE = ICE->getSubExpr();
2268 if (SubE->getType()->isPointerType() ||
2269 SubE->getType()->isArrayType() ||
2270 SubE->getType()->isFunctionType()) {
2271 return CheckAddressConstantExpression(Init);
2272 }
2273 }
2274 } else if (InitTy->isIntegralType()) {
2275 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002276 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002277 SubE = CE->getSubExpr();
2278 // Special check for pointer cast to int; we allow as an extension
2279 // an address constant cast to an integer if the integer
2280 // is of an appropriate width (this sort of code is apparently used
2281 // in some places).
2282 // FIXME: Add pedwarn?
2283 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2284 if (SubE && (SubE->getType()->isPointerType() ||
2285 SubE->getType()->isArrayType() ||
2286 SubE->getType()->isFunctionType())) {
2287 unsigned IntWidth = Context.getTypeSize(Init->getType());
2288 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2289 if (IntWidth >= PointerWidth)
2290 return CheckAddressConstantExpression(Init);
2291 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002292 }
2293
2294 return CheckArithmeticConstantExpression(Init);
2295 }
2296
2297 if (Init->getType()->isPointerType())
2298 return CheckAddressConstantExpression(Init);
2299
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002300 // An array type at the top level that isn't an init-list must
2301 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002302 if (Init->getType()->isArrayType())
2303 return false;
2304
Nuno Lopes73419bf2008-09-01 18:42:41 +00002305 if (Init->getType()->isFunctionType())
2306 return false;
2307
Steve Naroff8af6a452008-10-02 17:12:56 +00002308 // Allow block exprs at top level.
2309 if (Init->getType()->isBlockPointerType())
2310 return false;
2311
Steve Naroff6594a702008-10-27 11:34:16 +00002312 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002313 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002314}
2315
Sebastian Redl798d1192008-12-13 16:23:55 +00002316void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002317 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002318 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002319 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002320
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002321 // If there is no declaration, there was an error parsing it. Just ignore
2322 // the initializer.
2323 if (RealDecl == 0) {
2324 delete Init;
2325 return;
2326 }
Steve Naroffbb204692007-09-12 14:07:44 +00002327
Steve Naroff410e3e22007-09-12 20:13:48 +00002328 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2329 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002330 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2331 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002332 RealDecl->setInvalidDecl();
2333 return;
2334 }
Steve Naroffbb204692007-09-12 14:07:44 +00002335 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002336 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002337 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002338 if (VDecl->isBlockVarDecl()) {
2339 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002340 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002341 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002342 VDecl->setInvalidDecl();
2343 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002344 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002345 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002346 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002347
2348 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2349 if (!getLangOptions().CPlusPlus) {
2350 if (SC == VarDecl::Static) // C99 6.7.8p4.
2351 CheckForConstantInitializer(Init, DclT);
2352 }
Steve Naroffbb204692007-09-12 14:07:44 +00002353 }
Steve Naroff248a7532008-04-15 22:42:06 +00002354 } else if (VDecl->isFileVarDecl()) {
2355 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002356 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002357 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002358 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002359 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002360 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002361
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002362 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2363 if (!getLangOptions().CPlusPlus) {
2364 // C99 6.7.8p4. All file scoped initializers need to be constant.
2365 CheckForConstantInitializer(Init, DclT);
2366 }
Steve Naroffbb204692007-09-12 14:07:44 +00002367 }
2368 // If the type changed, it means we had an incomplete type that was
2369 // completed by the initializer. For example:
2370 // int ary[] = { 1, 3, 5 };
2371 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002372 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002373 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002374 Init->setType(DclT);
2375 }
Steve Naroffbb204692007-09-12 14:07:44 +00002376
2377 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002378 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002379 return;
2380}
2381
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002382void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2383 Decl *RealDecl = static_cast<Decl *>(dcl);
2384
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002385 // If there is no declaration, there was an error parsing it. Just ignore it.
2386 if (RealDecl == 0)
2387 return;
2388
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002389 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2390 QualType Type = Var->getType();
2391 // C++ [dcl.init.ref]p3:
2392 // The initializer can be omitted for a reference only in a
2393 // parameter declaration (8.3.5), in the declaration of a
2394 // function return type, in the declaration of a class member
2395 // within its class declaration (9.2), and where the extern
2396 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002397 if (Type->isReferenceType() &&
2398 Var->getStorageClass() != VarDecl::Extern &&
2399 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002400 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002401 << Var->getDeclName()
2402 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002403 Var->setInvalidDecl();
2404 return;
2405 }
2406
2407 // C++ [dcl.init]p9:
2408 //
2409 // If no initializer is specified for an object, and the object
2410 // is of (possibly cv-qualified) non-POD class type (or array
2411 // thereof), the object shall be default-initialized; if the
2412 // object is of const-qualified type, the underlying class type
2413 // shall have a user-declared default constructor.
2414 if (getLangOptions().CPlusPlus) {
2415 QualType InitType = Type;
2416 if (const ArrayType *Array = Context.getAsArrayType(Type))
2417 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002418 if (Var->getStorageClass() != VarDecl::Extern &&
2419 Var->getStorageClass() != VarDecl::PrivateExtern &&
2420 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002421 const CXXConstructorDecl *Constructor
2422 = PerformInitializationByConstructor(InitType, 0, 0,
2423 Var->getLocation(),
2424 SourceRange(Var->getLocation(),
2425 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002426 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002427 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002428 if (!Constructor)
2429 Var->setInvalidDecl();
2430 }
2431 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002432
Douglas Gregor818ce482008-10-29 13:50:18 +00002433#if 0
2434 // FIXME: Temporarily disabled because we are not properly parsing
2435 // linkage specifications on declarations, e.g.,
2436 //
2437 // extern "C" const CGPoint CGPointerZero;
2438 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002439 // C++ [dcl.init]p9:
2440 //
2441 // If no initializer is specified for an object, and the
2442 // object is of (possibly cv-qualified) non-POD class type (or
2443 // array thereof), the object shall be default-initialized; if
2444 // the object is of const-qualified type, the underlying class
2445 // type shall have a user-declared default
2446 // constructor. Otherwise, if no initializer is specified for
2447 // an object, the object and its subobjects, if any, have an
2448 // indeterminate initial value; if the object or any of its
2449 // subobjects are of const-qualified type, the program is
2450 // ill-formed.
2451 //
2452 // This isn't technically an error in C, so we don't diagnose it.
2453 //
2454 // FIXME: Actually perform the POD/user-defined default
2455 // constructor check.
2456 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002457 Context.getCanonicalType(Type).isConstQualified() &&
2458 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002459 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2460 << Var->getName()
2461 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002462#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002463 }
2464}
2465
Reid Spencer5f016e22007-07-11 17:01:13 +00002466/// The declarators are chained together backwards, reverse the list.
2467Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2468 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002469 Decl *GroupDecl = static_cast<Decl*>(group);
2470 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002471 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002472
2473 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2474 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002475 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002477 else { // reverse the list.
2478 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002479 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002480 Group->setNextDeclarator(NewGroup);
2481 NewGroup = Group;
2482 Group = Next;
2483 }
2484 }
2485 // Perform semantic analysis that depends on having fully processed both
2486 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002487 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002488 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2489 if (!IDecl)
2490 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002491 QualType T = IDecl->getType();
2492
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002493 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002494 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002495
2496 // FIXME: This won't give the correct result for
2497 // int a[10][n];
2498 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002499 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002500 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2501 SizeRange;
2502
Eli Friedmanc5773c42008-02-15 18:16:39 +00002503 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002504 } else {
2505 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2506 // static storage duration, it shall not have a variable length array.
2507 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002508 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2509 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002510 IDecl->setInvalidDecl();
2511 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002512 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2513 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002514 IDecl->setInvalidDecl();
2515 }
2516 }
2517 } else if (T->isVariablyModifiedType()) {
2518 if (IDecl->isFileVarDecl()) {
2519 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2520 IDecl->setInvalidDecl();
2521 } else {
2522 if (IDecl->getStorageClass() == VarDecl::Extern) {
2523 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2524 IDecl->setInvalidDecl();
2525 }
Steve Naroffbb204692007-09-12 14:07:44 +00002526 }
2527 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002528
Steve Naroffbb204692007-09-12 14:07:44 +00002529 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2530 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002531 if (IDecl->isBlockVarDecl() &&
2532 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002533 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002534 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002535 IDecl->setInvalidDecl();
2536 }
2537 }
2538 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2539 // object that has file scope without an initializer, and without a
2540 // storage-class specifier or with the storage-class specifier "static",
2541 // constitutes a tentative definition. Note: A tentative definition with
2542 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002543 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002544 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002545 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2546 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002547 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002548 // C99 6.9.2p3: If the declaration of an identifier for an object is
2549 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2550 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002551 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002552 IDecl->setInvalidDecl();
2553 }
2554 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002555 if (IDecl->isFileVarDecl())
2556 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 }
2558 return NewGroup;
2559}
Steve Naroffe1223f72007-08-28 03:03:08 +00002560
Chris Lattner04421082008-04-08 04:40:51 +00002561/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2562/// to introduce parameters into function prototype scope.
2563Sema::DeclTy *
2564Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002565 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002566
Chris Lattner04421082008-04-08 04:40:51 +00002567 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002568 VarDecl::StorageClass StorageClass = VarDecl::None;
2569 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2570 StorageClass = VarDecl::Register;
2571 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002572 Diag(DS.getStorageClassSpecLoc(),
2573 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002574 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002575 }
2576 if (DS.isThreadSpecified()) {
2577 Diag(DS.getThreadSpecLoc(),
2578 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002579 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002580 }
2581
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002582 // Check that there are no default arguments inside the type of this
2583 // parameter (C++ only).
2584 if (getLangOptions().CPlusPlus)
2585 CheckExtraCXXDefaultArguments(D);
2586
Chris Lattner04421082008-04-08 04:40:51 +00002587 // In this context, we *do not* check D.getInvalidType(). If the declarator
2588 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2589 // though it will not reflect the user specified type.
2590 QualType parmDeclType = GetTypeForDeclarator(D, S);
2591
2592 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2593
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2595 // Can this happen for params? We already checked that they don't conflict
2596 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002597 IdentifierInfo *II = D.getIdentifier();
2598 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002599 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002600 // Maybe we will complain about the shadowed template parameter.
2601 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2602 // Just pretend that we didn't see the previous declaration.
2603 PrevDecl = 0;
2604 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002605 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002606
2607 // Recover by removing the name
2608 II = 0;
2609 D.SetIdentifier(0, D.getIdentifierLoc());
2610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002612
2613 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2614 // Doing the promotion here has a win and a loss. The win is the type for
2615 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2616 // code generator). The loss is the orginal type isn't preserved. For example:
2617 //
2618 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2619 // int blockvardecl[5];
2620 // sizeof(parmvardecl); // size == 4
2621 // sizeof(blockvardecl); // size == 20
2622 // }
2623 //
2624 // For expressions, all implicit conversions are captured using the
2625 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2626 //
2627 // FIXME: If a source translation tool needs to see the original type, then
2628 // we need to consider storing both types (in ParmVarDecl)...
2629 //
Chris Lattnere6327742008-04-02 05:18:44 +00002630 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002631 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002632 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002633 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002634 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002635
Chris Lattner04421082008-04-08 04:40:51 +00002636 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2637 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002638 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002639 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002640
Chris Lattner04421082008-04-08 04:40:51 +00002641 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002642 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002643
Douglas Gregor584049d2008-12-15 23:53:10 +00002644 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2645 if (D.getCXXScopeSpec().isSet()) {
2646 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2647 << D.getCXXScopeSpec().getRange();
2648 New->setInvalidDecl();
2649 }
2650
Douglas Gregor44b43212008-12-11 16:49:14 +00002651 // Add the parameter declaration into this scope.
2652 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002653 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002654 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002655
Chris Lattner3ff30c82008-06-29 00:02:00 +00002656 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002658
Reid Spencer5f016e22007-07-11 17:01:13 +00002659}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002660
Chris Lattnerb652cea2007-10-09 17:14:05 +00002661Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002662 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002663 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2664 "Not a function declarator!");
2665 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002666
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2668 // for a K&R function.
2669 if (!FTI.hasPrototype) {
2670 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002671 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002672 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2673 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 // Implicitly declare the argument as type 'int' for lack of a better
2675 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002676 DeclSpec DS;
2677 const char* PrevSpec; // unused
2678 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2679 PrevSpec);
2680 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2681 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2682 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 }
2684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002686 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 }
2688
Douglas Gregor584049d2008-12-15 23:53:10 +00002689 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002690
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002691 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002692 ActOnDeclarator(ParentScope, D, 0,
2693 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002694}
2695
2696Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2697 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002698 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002699
2700 // See if this is a redefinition.
2701 const FunctionDecl *Definition;
2702 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002703 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002704 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002705 }
2706
Douglas Gregor44b43212008-12-11 16:49:14 +00002707 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002708
Chris Lattner04421082008-04-08 04:40:51 +00002709 // Check the validity of our function parameters
2710 CheckParmsForFunctionDef(FD);
2711
2712 // Introduce our parameters into the function scope
2713 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2714 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002715 Param->setOwningFunction(FD);
2716
Chris Lattner04421082008-04-08 04:40:51 +00002717 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002718 if (Param->getIdentifier())
2719 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 }
Chris Lattner04421082008-04-08 04:40:51 +00002721
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002722 // Checking attributes of current function definition
2723 // dllimport attribute.
2724 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2725 // dllimport attribute cannot be applied to definition.
2726 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2727 Diag(FD->getLocation(),
2728 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2729 << "dllimport";
2730 FD->setInvalidDecl();
2731 return FD;
2732 } else {
2733 // If a symbol previously declared dllimport is later defined, the
2734 // attribute is ignored in subsequent references, and a warning is
2735 // emitted.
2736 Diag(FD->getLocation(),
2737 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2738 << FD->getNameAsCString() << "dllimport";
2739 }
2740 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 return FD;
2742}
2743
Sebastian Redl798d1192008-12-13 16:23:55 +00002744Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002745 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002746 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002747 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002748 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002749 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002750 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002751 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002752 } else
2753 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002754 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 // Verify and clean out per-function state.
2756
2757 // Check goto/label use.
2758 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2759 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2760 // Verify that we have no forward references left. If so, there was a goto
2761 // or address of a label taken, but no definition of it. Label fwd
2762 // definitions are indicated with a null substmt.
2763 if (I->second->getSubStmt() == 0) {
2764 LabelStmt *L = I->second;
2765 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002766 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002767
2768 // At this point, we have gotos that use the bogus label. Stitch it into
2769 // the function body so that they aren't leaked and that the AST is well
2770 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002771 if (Body) {
2772 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002773 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002774 } else {
2775 // The whole function wasn't parsed correctly, just delete this.
2776 delete L;
2777 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 }
2779 }
2780 LabelMap.clear();
2781
Steve Naroffd6d054d2007-11-11 23:20:51 +00002782 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002783}
2784
Reid Spencer5f016e22007-07-11 17:01:13 +00002785/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2786/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002787ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2788 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002789 // Extension in C99. Legal in C90, but warn about it.
2790 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002791 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002792 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002793 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002794
2795 // FIXME: handle stuff like:
2796 // void foo() { extern float X(); }
2797 // void bar() { X(); } <-- implicit decl for X in another scope.
2798
2799 // Set a Declarator for the implicit definition: int foo();
2800 const char *Dummy;
2801 DeclSpec DS;
2802 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2803 Error = Error; // Silence warning.
2804 assert(!Error && "Error setting up implicit decl!");
2805 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002806 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 D.SetIdentifier(&II, Loc);
2808
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002809 // Insert this function into translation-unit scope.
2810
2811 DeclContext *PrevDC = CurContext;
2812 CurContext = Context.getTranslationUnitDecl();
2813
Steve Naroffe2ef8152008-04-04 14:32:09 +00002814 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002815 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002816 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002817
2818 CurContext = PrevDC;
2819
Steve Naroffe2ef8152008-04-04 14:32:09 +00002820 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821}
2822
2823
Chris Lattner41af0932007-11-14 06:34:38 +00002824TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002825 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002827 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002828
2829 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002830 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2831 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002832 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002833 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002834 if (D.getInvalidType())
2835 NewTD->setInvalidDecl();
2836 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002837}
2838
Steve Naroff08d92e42007-09-15 18:49:24 +00002839/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002840/// former case, Name will be non-null. In the later case, Name will be null.
2841/// TagType indicates what kind of tag this is. TK indicates whether this is a
2842/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002843Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002844 SourceLocation KWLoc, const CXXScopeSpec &SS,
2845 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002846 AttributeList *Attr,
2847 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002848 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 assert((Name != 0 || TK == TK_Definition) &&
2850 "Nameless record must be a definition!");
2851
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002852 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002853 switch (TagType) {
2854 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002855 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2856 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2857 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2858 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 }
2860
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002861 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002862 DeclContext *LexicalContext = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002863 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002864
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002865 if (Name && SS.isNotEmpty()) {
2866 // We have a nested-name tag ('struct foo::bar').
2867
2868 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002869 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002870 Name = 0;
2871 goto CreateNewDecl;
2872 }
2873
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002874 DC = static_cast<DeclContext*>(SS.getScopeRep());
2875 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002876 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2877
2878 // A tag 'foo::bar' must already exist.
2879 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002880 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002881 Name = 0;
2882 goto CreateNewDecl;
2883 }
2884 } else {
2885 // If this is a named struct, check to see if there was a previous forward
2886 // declaration or definition.
2887 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2888 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
Douglas Gregor72de6672009-01-08 20:45:30 +00002889
2890 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2891 // FIXME: This makes sure that we ignore the contexts associated
2892 // with C structs, unions, and enums when looking for a matching
2893 // tag declaration or definition. See the similar lookup tweak
2894 // in Sema::LookupDecl; is there a better way to deal with this?
2895 while (isa<RecordDecl>(DC) || isa<EnumDecl>(DC))
2896 DC = DC->getParent();
2897 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002898 }
2899
Douglas Gregorf57172b2008-12-08 18:40:42 +00002900 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002901 // Maybe we will complain about the shadowed template parameter.
2902 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2903 // Just pretend that we didn't see the previous declaration.
2904 PrevDecl = 0;
2905 }
2906
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002907 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002908 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2909 "unexpected Decl type");
2910 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002911 // If this is a use of a previous tag, or if the tag is already declared
2912 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002913 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002914 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002915 // Make sure that this wasn't declared as an enum and now used as a
2916 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002917 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002918 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002919 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002920 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002921 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002922 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002923 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002924 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002925
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002926 // FIXME: In the future, return a variant or some other clue
2927 // for the consumer of this Decl to know it doesn't own it.
2928 // For our current ASTs this shouldn't be a problem, but will
2929 // need to be changed with DeclGroups.
2930 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002931 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002932
2933 // Diagnose attempts to redefine a tag.
2934 if (TK == TK_Definition) {
2935 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2936 Diag(NameLoc, diag::err_redefinition) << Name;
2937 Diag(Def->getLocation(), diag::note_previous_definition);
2938 // If this is a redefinition, recover by making this struct be
2939 // anonymous, which will make any later references get the previous
2940 // definition.
2941 Name = 0;
2942 PrevDecl = 0;
2943 }
2944 // Okay, this is definition of a previously declared or referenced
2945 // tag PrevDecl. We're going to create a new Decl for it.
2946 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002947 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002948 // If we get here we have (another) forward declaration or we
2949 // have a definition. Just create a new decl.
2950 } else {
2951 // If we get here, this is a definition of a new tag type in a nested
2952 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2953 // new decl/type. We set PrevDecl to NULL so that the entities
2954 // have distinct types.
2955 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002957 // If we get here, we're going to create a new Decl. If PrevDecl
2958 // is non-NULL, it's a definition of the tag declared by
2959 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002960 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002961 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002962 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002963 // The tag name clashes with a namespace name, issue an error and
2964 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002965 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002966 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002967 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002968 PrevDecl = 0;
2969 } else {
2970 // The existing declaration isn't relevant to us; we're in a
2971 // new scope, so clear out the previous declaration.
2972 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002973 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002974 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002975 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2976 (Kind != TagDecl::TK_enum)) {
2977 // C++ [basic.scope.pdecl]p5:
2978 // -- for an elaborated-type-specifier of the form
2979 //
2980 // class-key identifier
2981 //
2982 // if the elaborated-type-specifier is used in the
2983 // decl-specifier-seq or parameter-declaration-clause of a
2984 // function defined in namespace scope, the identifier is
2985 // declared as a class-name in the namespace that contains
2986 // the declaration; otherwise, except as a friend
2987 // declaration, the identifier is declared in the smallest
2988 // non-class, non-function-prototype scope that contains the
2989 // declaration.
2990 //
2991 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2992 // C structs and unions.
2993
2994 // Find the context where we'll be declaring the tag.
2995 while (DC->isRecord())
2996 DC = DC->getParent();
2997 LexicalContext = DC;
2998
2999 // Find the scope where we'll be declaring the tag.
3000 while (S->isClassScope() ||
3001 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
3002 (S->getFlags() & Scope::DeclScope == 0))
3003 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003005
Chris Lattnercc98eac2008-12-17 07:13:27 +00003006CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003007
3008 // If there is an identifier, use the location of the identifier as the
3009 // location of the decl, otherwise use the location of the struct/union
3010 // keyword.
3011 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3012
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003013 // Otherwise, create a new declaration. If there is a previous
3014 // declaration of the same entity, the two will be linked via
3015 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003016 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003017
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003018 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003019 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3020 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003021 New = EnumDecl::Create(Context, DC, Loc, Name,
3022 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 // If this is an undefined enum, warn.
3024 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003025 } else {
3026 // struct/union/class
3027
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3029 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003030 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003031 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003032 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3033 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003034 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003035 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3036 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003037 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003038
3039 if (Kind != TagDecl::TK_enum) {
3040 // Handle #pragma pack: if the #pragma pack stack has non-default
3041 // alignment, make up a packed attribute for this decl. These
3042 // attributes are checked when the ASTContext lays out the
3043 // structure.
3044 //
3045 // It is important for implementing the correct semantics that this
3046 // happen here (in act on tag decl). The #pragma pack stack is
3047 // maintained as a result of parser callbacks which can occur at
3048 // many points during the parsing of a struct declaration (because
3049 // the #pragma tokens are effectively skipped over during the
3050 // parsing of the struct).
3051 if (unsigned Alignment = PackContext.getAlignment())
3052 New->addAttr(new PackedAttr(Alignment * 8));
3053 }
3054
3055 if (Attr)
3056 ProcessDeclAttributeList(New, Attr);
3057
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003058 // If we're declaring or defining
3059 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3060 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3061
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003062 // Set the lexical context. If the tag has a C++ scope specifier, the
3063 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003064 New->setLexicalDeclContext(LexicalContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00003065
3066 // If this has an identifier, add it to the scope stack.
3067 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00003068 // The scope passed in may not be a decl scope. Zip up the scope tree until
3069 // we find one that is.
3070 while ((S->getFlags() & Scope::DeclScope) == 0)
3071 S = S->getParent();
3072
3073 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003074 if (LexicalContext != CurContext) {
3075 // FIXME: PushOnScopeChains should not rely on CurContext!
3076 DeclContext *OldContext = CurContext;
3077 CurContext = LexicalContext;
3078 PushOnScopeChains(New, S);
3079 CurContext = OldContext;
3080 } else
3081 PushOnScopeChains(New, S);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003082 } else if (getLangOptions().CPlusPlus) {
3083 // FIXME: We also want to do this for C, but if this tag is
3084 // defined within a structure CurContext will point to the context
3085 // enclosing the structure, and we would end up inserting the tag
3086 // type into the wrong place.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003087 LexicalContext->addDecl(Context, New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003088 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003089
Reid Spencer5f016e22007-07-11 17:01:13 +00003090 return New;
3091}
3092
Douglas Gregor72de6672009-01-08 20:45:30 +00003093void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3094 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3095
3096 // Enter the tag context.
3097 PushDeclContext(S, Tag);
3098
3099 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3100 FieldCollector->StartClass();
3101
3102 if (Record->getIdentifier()) {
3103 // C++ [class]p2:
3104 // [...] The class-name is also inserted into the scope of the
3105 // class itself; this is known as the injected-class-name. For
3106 // purposes of access checking, the injected-class-name is treated
3107 // as if it were a public member name.
3108 RecordDecl *InjectedClassName
3109 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3110 CurContext, Record->getLocation(),
3111 Record->getIdentifier(), Record);
3112 InjectedClassName->setImplicit();
3113 PushOnScopeChains(InjectedClassName, S);
3114 }
3115 }
3116}
3117
3118void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3119 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3120
3121 if (isa<CXXRecordDecl>(Tag))
3122 FieldCollector->FinishClass();
3123
3124 // Exit this scope of this tag's definition.
3125 PopDeclContext();
3126
3127 // Notify the consumer that we've defined a tag.
3128 Consumer.HandleTagDeclDefinition(Tag);
3129}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003130
Chris Lattner1d353ba2008-11-12 21:17:48 +00003131/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3132/// types into constant array types in certain situations which would otherwise
3133/// be errors (for GCC compatibility).
3134static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3135 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003136 // This method tries to turn a variable array into a constant
3137 // array even when the size isn't an ICE. This is necessary
3138 // for compatibility with code that depends on gcc's buggy
3139 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003140 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3141 if (!VLATy) return QualType();
3142
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003143 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003144 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003145 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003146 return QualType();
3147
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003148 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3149 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003150 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3151 return Context.getConstantArrayType(VLATy->getElementType(),
3152 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003153 return QualType();
3154}
3155
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003156bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003157 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003158 // FIXME: 6.7.2.1p4 - verify the field type.
3159
3160 llvm::APSInt Value;
3161 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3162 return true;
3163
Chris Lattnercd087072008-12-12 04:56:04 +00003164 // Zero-width bitfield is ok for anonymous field.
3165 if (Value == 0 && FieldName)
3166 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3167
3168 if (Value.isNegative())
3169 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003170
3171 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3172 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003173 if (TypeSize && Value.getZExtValue() > TypeSize)
3174 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3175 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003176
3177 return false;
3178}
3179
Steve Naroff08d92e42007-09-15 18:49:24 +00003180/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003181/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003182Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003183 SourceLocation DeclStart,
3184 Declarator &D, ExprTy *BitfieldWidth) {
3185 IdentifierInfo *II = D.getIdentifier();
3186 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003187 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003188 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 if (II) Loc = D.getIdentifierLoc();
3190
3191 // FIXME: Unnamed fields can be handled in various different ways, for
3192 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003193
Reid Spencer5f016e22007-07-11 17:01:13 +00003194 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003195 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3196 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003197
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3199 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003200 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003201 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003202 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003203 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003204 T = FixedTy;
3205 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003206 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003207 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003208 InvalidDecl = true;
3209 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003211
3212 if (BitWidth) {
3213 if (VerifyBitField(Loc, II, T, BitWidth))
3214 InvalidDecl = true;
3215 } else {
3216 // Not a bitfield.
3217
3218 // validate II.
3219
3220 }
3221
Reid Spencer5f016e22007-07-11 17:01:13 +00003222 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003223 FieldDecl *NewFD;
3224
Douglas Gregor44b43212008-12-11 16:49:14 +00003225 NewFD = FieldDecl::Create(Context, Record,
3226 Loc, II, T, BitWidth,
3227 D.getDeclSpec().getStorageClassSpec() ==
3228 DeclSpec::SCS_mutable,
3229 /*PrevDecl=*/0);
3230
Douglas Gregor72de6672009-01-08 20:45:30 +00003231 if (II) {
3232 Decl *PrevDecl
3233 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3234 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3235 && !isa<TagDecl>(PrevDecl)) {
3236 Diag(Loc, diag::err_duplicate_member) << II;
3237 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3238 NewFD->setInvalidDecl();
3239 Record->setInvalidDecl();
3240 }
3241 }
3242
Sebastian Redl64b45f72009-01-05 20:52:13 +00003243 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003244 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003245 if (!T->isPODType())
3246 cast<CXXRecordDecl>(Record)->setPOD(false);
3247 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003248
Chris Lattner3ff30c82008-06-29 00:02:00 +00003249 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003250
Steve Naroff5912a352007-08-28 20:14:24 +00003251 if (D.getInvalidType() || InvalidDecl)
3252 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003253
Douglas Gregor72de6672009-01-08 20:45:30 +00003254 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003255 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003256 } else
Douglas Gregor44b43212008-12-11 16:49:14 +00003257 Record->addDecl(Context, NewFD);
3258
Steve Naroff5912a352007-08-28 20:14:24 +00003259 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003260}
3261
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003262/// TranslateIvarVisibility - Translate visibility from a token ID to an
3263/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003264static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003265TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003266 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003267 default: assert(0 && "Unknown visitibility kind");
3268 case tok::objc_private: return ObjCIvarDecl::Private;
3269 case tok::objc_public: return ObjCIvarDecl::Public;
3270 case tok::objc_protected: return ObjCIvarDecl::Protected;
3271 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003272 }
3273}
3274
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003275/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3276/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003277Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003278 SourceLocation DeclStart,
3279 Declarator &D, ExprTy *BitfieldWidth,
3280 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003281
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003282 IdentifierInfo *II = D.getIdentifier();
3283 Expr *BitWidth = (Expr*)BitfieldWidth;
3284 SourceLocation Loc = DeclStart;
3285 if (II) Loc = D.getIdentifierLoc();
3286
3287 // FIXME: Unnamed fields can be handled in various different ways, for
3288 // example, unnamed unions inject all members into the struct namespace!
3289
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003290 QualType T = GetTypeForDeclarator(D, S);
3291 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3292 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003293
3294 if (BitWidth) {
3295 // TODO: Validate.
3296 //printf("WARNING: BITFIELDS IGNORED!\n");
3297
3298 // 6.7.2.1p3
3299 // 6.7.2.1p4
3300
3301 } else {
3302 // Not a bitfield.
3303
3304 // validate II.
3305
3306 }
3307
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003308 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3309 // than a variably modified type.
3310 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003311 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003312 InvalidDecl = true;
3313 }
3314
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003315 // Get the visibility (access control) for this ivar.
3316 ObjCIvarDecl::AccessControl ac =
3317 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3318 : ObjCIvarDecl::None;
3319
3320 // Construct the decl.
3321 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003322 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003323
Douglas Gregor72de6672009-01-08 20:45:30 +00003324 if (II) {
3325 Decl *PrevDecl
3326 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3327 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3328 && !isa<TagDecl>(PrevDecl)) {
3329 Diag(Loc, diag::err_duplicate_member) << II;
3330 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3331 NewID->setInvalidDecl();
3332 }
3333 }
3334
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003335 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003336 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003337
3338 if (D.getInvalidType() || InvalidDecl)
3339 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003340
Douglas Gregor72de6672009-01-08 20:45:30 +00003341 if (II) {
3342 // FIXME: When interfaces are DeclContexts, we'll need to add
3343 // these to the interface.
3344 S->AddDecl(NewID);
3345 IdResolver.AddDecl(NewID);
3346 }
3347
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003348 return NewID;
3349}
3350
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003351void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003352 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003353 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003354 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003355 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003356 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3357 assert(EnclosingDecl && "missing record or interface decl");
3358 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3359
Douglas Gregor72de6672009-01-08 20:45:30 +00003360 if (Record) {
3361 QualType RecordType = Context.getTypeDeclType(Record);
3362 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3363 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003364 // Diagnose code like:
3365 // struct S { struct S {} X; };
3366 // We discover this when we complete the outer S. Reject and ignore the
3367 // outer S.
Douglas Gregor72de6672009-01-08 20:45:30 +00003368 Diag(Def->getLocation(), diag::err_nested_redefinition)
3369 << Def->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003370 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003371 Record->setInvalidDecl();
3372 return;
3373 }
Douglas Gregor72de6672009-01-08 20:45:30 +00003374 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003375
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 // Verify that all the fields are okay.
3377 unsigned NumNamedMembers = 0;
3378 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003379
Reid Spencer5f016e22007-07-11 17:01:13 +00003380 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003381 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3382 assert(FD && "missing field decl");
3383
Reid Spencer5f016e22007-07-11 17:01:13 +00003384 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003385 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003386
Douglas Gregor72de6672009-01-08 20:45:30 +00003387 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003388 // Remember all fields written by the user.
3389 RecFields.push_back(FD);
3390 }
Steve Narofff13271f2007-09-14 23:09:53 +00003391
Reid Spencer5f016e22007-07-11 17:01:13 +00003392 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003393 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003394 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003396 FD->setInvalidDecl();
3397 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 continue;
3399 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003400 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3401 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003402 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003403 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003404 FD->setInvalidDecl();
3405 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003406 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003407 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003409 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003410 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003411 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003412 FD->setInvalidDecl();
3413 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 continue;
3415 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003416 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003417 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003418 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003419 FD->setInvalidDecl();
3420 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 continue;
3422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003424 if (Record)
3425 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3428 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003429 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003430 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3431 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003432 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 Record->setHasFlexibleArrayMember(true);
3434 } else {
3435 // If this is a struct/class and this is not the last element, reject
3436 // it. Note that GCC supports variable sized arrays in the middle of
3437 // structures.
3438 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003439 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003440 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003441 FD->setInvalidDecl();
3442 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003443 continue;
3444 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003445 // We support flexible arrays at the end of structs in other structs
3446 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003447 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003448 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003449 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003450 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003451 }
3452 }
3453 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003454 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003455 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003456 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003457 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003458 FD->setInvalidDecl();
3459 EnclosingDecl->setInvalidDecl();
3460 continue;
3461 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003462 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003463 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003465 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003466
Reid Spencer5f016e22007-07-11 17:01:13 +00003467 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003468 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003469 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003470 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003471 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003472 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003473 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003474 // Must enforce the rule that ivars in the base classes may not be
3475 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003476 if (ID->getSuperClass()) {
3477 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3478 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3479 ObjCIvarDecl* Ivar = (*IVI);
3480 IdentifierInfo *II = Ivar->getIdentifier();
3481 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3482 if (prevIvar) {
3483 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003484 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003485 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003486 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003487 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003488 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003489 else if (ObjCImplementationDecl *IMPDecl =
3490 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003491 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3492 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003493 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003494 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003495 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003496
3497 if (Attr)
3498 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003499}
3500
Steve Naroff08d92e42007-09-15 18:49:24 +00003501Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003502 DeclTy *lastEnumConst,
3503 SourceLocation IdLoc, IdentifierInfo *Id,
3504 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003505 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003506 EnumConstantDecl *LastEnumConst =
3507 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3508 Expr *Val = static_cast<Expr*>(val);
3509
Chris Lattner31e05722007-08-26 06:24:45 +00003510 // The scope passed in may not be a decl scope. Zip up the scope tree until
3511 // we find one that is.
3512 while ((S->getFlags() & Scope::DeclScope) == 0)
3513 S = S->getParent();
3514
Reid Spencer5f016e22007-07-11 17:01:13 +00003515 // Verify that there isn't already something declared with this name in this
3516 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003517 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003518 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003519 // Maybe we will complain about the shadowed template parameter.
3520 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3521 // Just pretend that we didn't see the previous declaration.
3522 PrevDecl = 0;
3523 }
3524
3525 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003526 // When in C++, we may get a TagDecl with the same name; in this case the
3527 // enum constant will 'hide' the tag.
3528 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3529 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003530 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003531 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003532 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003534 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003535 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003536 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 return 0;
3538 }
3539 }
3540
3541 llvm::APSInt EnumVal(32);
3542 QualType EltTy;
3543 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003544 // Make sure to promote the operand type to int.
3545 UsualUnaryConversions(Val);
3546
Reid Spencer5f016e22007-07-11 17:01:13 +00003547 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3548 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003549 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003550 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003551 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003552 } else {
3553 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003554 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003555 }
3556
3557 if (!Val) {
3558 if (LastEnumConst) {
3559 // Assign the last value + 1.
3560 EnumVal = LastEnumConst->getInitVal();
3561 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003562
3563 // Check for overflow on increment.
3564 if (EnumVal < LastEnumConst->getInitVal())
3565 Diag(IdLoc, diag::warn_enum_value_overflow);
3566
Chris Lattnerb7416f92007-08-27 17:37:24 +00003567 EltTy = LastEnumConst->getType();
3568 } else {
3569 // First value, set to zero.
3570 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003571 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003573 }
3574
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003575 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003576 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3577 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003578 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003579
3580 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003581 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003582
Reid Spencer5f016e22007-07-11 17:01:13 +00003583 return New;
3584}
3585
Steve Naroff02408c62008-08-07 14:08:16 +00003586// FIXME: For consistency with ActOnFields(), we should have the parser
3587// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003588void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003589 DeclTy **Elements, unsigned NumElements) {
3590 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003591 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003592
Douglas Gregor074149e2009-01-05 19:45:36 +00003593 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3594 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3595 // Diagnose code like:
3596 // enum e0 {
3597 // E0 = sizeof(enum e0 { E1 })
3598 // };
3599 Diag(Def->getLocation(), diag::err_nested_redefinition)
3600 << Enum->getDeclName();
3601 Diag(Enum->getLocation(), diag::note_previous_definition);
3602 Enum->setInvalidDecl();
Douglas Gregor074149e2009-01-05 19:45:36 +00003603 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003604 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003605
Chris Lattnere37f0be2007-08-28 05:10:31 +00003606 // TODO: If the result value doesn't fit in an int, it must be a long or long
3607 // long value. ISO C does not support this, but GCC does as an extension,
3608 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003609 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003610
Chris Lattnerac609682007-08-28 06:15:15 +00003611 // Verify that all the values are okay, compute the size of the values, and
3612 // reverse the list.
3613 unsigned NumNegativeBits = 0;
3614 unsigned NumPositiveBits = 0;
3615
3616 // Keep track of whether all elements have type int.
3617 bool AllElementsInt = true;
3618
Reid Spencer5f016e22007-07-11 17:01:13 +00003619 EnumConstantDecl *EltList = 0;
3620 for (unsigned i = 0; i != NumElements; ++i) {
3621 EnumConstantDecl *ECD =
3622 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3623 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003624
3625 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003626 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003627 assert(InitVal.getBitWidth() >= IntWidth &&
3628 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003629 if (InitVal.getBitWidth() > IntWidth) {
3630 llvm::APSInt V(InitVal);
3631 V.trunc(IntWidth);
3632 V.extend(InitVal.getBitWidth());
3633 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003634 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3635 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003636 }
Chris Lattnerac609682007-08-28 06:15:15 +00003637
3638 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003639 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003640 NumPositiveBits = std::max(NumPositiveBits,
3641 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003642 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003643 NumNegativeBits = std::max(NumNegativeBits,
3644 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003645
Chris Lattnerac609682007-08-28 06:15:15 +00003646 // Keep track of whether every enum element has type int (very commmon).
3647 if (AllElementsInt)
3648 AllElementsInt = ECD->getType() == Context.IntTy;
3649
Reid Spencer5f016e22007-07-11 17:01:13 +00003650 ECD->setNextDeclarator(EltList);
3651 EltList = ECD;
3652 }
3653
Chris Lattnerac609682007-08-28 06:15:15 +00003654 // Figure out the type that should be used for this enum.
3655 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3656 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003657 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003658
3659 if (NumNegativeBits) {
3660 // If there is a negative value, figure out the smallest integer type (of
3661 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003662 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003663 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003664 BestWidth = IntWidth;
3665 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003666 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003667
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003668 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003669 BestType = Context.LongTy;
3670 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003671 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003672
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003673 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003674 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3675 BestType = Context.LongLongTy;
3676 }
3677 }
3678 } else {
3679 // If there is no negative value, figure out which of uint, ulong, ulonglong
3680 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003681 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003682 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003683 BestWidth = IntWidth;
3684 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003685 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003686 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003687 } else {
3688 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003689 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003690 "How could an initializer get larger than ULL?");
3691 BestType = Context.UnsignedLongLongTy;
3692 }
3693 }
3694
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003695 // Loop over all of the enumerator constants, changing their types to match
3696 // the type of the enum if needed.
3697 for (unsigned i = 0; i != NumElements; ++i) {
3698 EnumConstantDecl *ECD =
3699 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3700 if (!ECD) continue; // Already issued a diagnostic.
3701
3702 // Standard C says the enumerators have int type, but we allow, as an
3703 // extension, the enumerators to be larger than int size. If each
3704 // enumerator value fits in an int, type it as an int, otherwise type it the
3705 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3706 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003707 if (ECD->getType() == Context.IntTy) {
3708 // Make sure the init value is signed.
3709 llvm::APSInt IV = ECD->getInitVal();
3710 IV.setIsSigned(true);
3711 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003712
3713 if (getLangOptions().CPlusPlus)
3714 // C++ [dcl.enum]p4: Following the closing brace of an
3715 // enum-specifier, each enumerator has the type of its
3716 // enumeration.
3717 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003718 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003719 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003720
3721 // Determine whether the value fits into an int.
3722 llvm::APSInt InitVal = ECD->getInitVal();
3723 bool FitsInInt;
3724 if (InitVal.isUnsigned() || !InitVal.isNegative())
3725 FitsInInt = InitVal.getActiveBits() < IntWidth;
3726 else
3727 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3728
3729 // If it fits into an integer type, force it. Otherwise force it to match
3730 // the enum decl type.
3731 QualType NewTy;
3732 unsigned NewWidth;
3733 bool NewSign;
3734 if (FitsInInt) {
3735 NewTy = Context.IntTy;
3736 NewWidth = IntWidth;
3737 NewSign = true;
3738 } else if (ECD->getType() == BestType) {
3739 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003740 if (getLangOptions().CPlusPlus)
3741 // C++ [dcl.enum]p4: Following the closing brace of an
3742 // enum-specifier, each enumerator has the type of its
3743 // enumeration.
3744 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003745 continue;
3746 } else {
3747 NewTy = BestType;
3748 NewWidth = BestWidth;
3749 NewSign = BestType->isSignedIntegerType();
3750 }
3751
3752 // Adjust the APSInt value.
3753 InitVal.extOrTrunc(NewWidth);
3754 InitVal.setIsSigned(NewSign);
3755 ECD->setInitVal(InitVal);
3756
3757 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003758 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3759 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003760 if (getLangOptions().CPlusPlus)
3761 // C++ [dcl.enum]p4: Following the closing brace of an
3762 // enum-specifier, each enumerator has the type of its
3763 // enumeration.
3764 ECD->setType(EnumType);
3765 else
3766 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003767 }
Chris Lattnerac609682007-08-28 06:15:15 +00003768
Douglas Gregor44b43212008-12-11 16:49:14 +00003769 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003770}
3771
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003772Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003773 ExprArg expr) {
3774 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3775
Chris Lattner8e25d862008-03-16 00:16:02 +00003776 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003777}
3778
Douglas Gregorf44515a2008-12-16 22:23:02 +00003779
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003780void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3781 ExprTy *alignment, SourceLocation PragmaLoc,
3782 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3783 Expr *Alignment = static_cast<Expr *>(alignment);
3784
3785 // If specified then alignment must be a "small" power of two.
3786 unsigned AlignmentVal = 0;
3787 if (Alignment) {
3788 llvm::APSInt Val;
3789 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3790 !Val.isPowerOf2() ||
3791 Val.getZExtValue() > 16) {
3792 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3793 delete Alignment;
3794 return; // Ignore
3795 }
3796
3797 AlignmentVal = (unsigned) Val.getZExtValue();
3798 }
3799
3800 switch (Kind) {
3801 case Action::PPK_Default: // pack([n])
3802 PackContext.setAlignment(AlignmentVal);
3803 break;
3804
3805 case Action::PPK_Show: // pack(show)
3806 // Show the current alignment, making sure to show the right value
3807 // for the default.
3808 AlignmentVal = PackContext.getAlignment();
3809 // FIXME: This should come from the target.
3810 if (AlignmentVal == 0)
3811 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003812 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003813 break;
3814
3815 case Action::PPK_Push: // pack(push [, id] [, [n])
3816 PackContext.push(Name);
3817 // Set the new alignment if specified.
3818 if (Alignment)
3819 PackContext.setAlignment(AlignmentVal);
3820 break;
3821
3822 case Action::PPK_Pop: // pack(pop [, id] [, n])
3823 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3824 // "#pragma pack(pop, identifier, n) is undefined"
3825 if (Alignment && Name)
3826 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3827
3828 // Do the pop.
3829 if (!PackContext.pop(Name)) {
3830 // If a name was specified then failure indicates the name
3831 // wasn't found. Otherwise failure indicates the stack was
3832 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003833 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3834 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003835
3836 // FIXME: Warn about popping named records as MSVC does.
3837 } else {
3838 // Pop succeeded, set the new alignment if specified.
3839 if (Alignment)
3840 PackContext.setAlignment(AlignmentVal);
3841 }
3842 break;
3843
3844 default:
3845 assert(0 && "Invalid #pragma pack kind.");
3846 }
3847}
3848
3849bool PragmaPackStack::pop(IdentifierInfo *Name) {
3850 if (Stack.empty())
3851 return false;
3852
3853 // If name is empty just pop top.
3854 if (!Name) {
3855 Alignment = Stack.back().first;
3856 Stack.pop_back();
3857 return true;
3858 }
3859
3860 // Otherwise, find the named record.
3861 for (unsigned i = Stack.size(); i != 0; ) {
3862 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003863 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003864 // Found it, pop up to and including this record.
3865 Alignment = Stack[i].first;
3866 Stack.erase(Stack.begin() + i, Stack.end());
3867 return true;
3868 }
3869 }
3870
3871 return false;
3872}