blob: dce1e129a59750e1c4f4ca3d3952d2a9935f24b8 [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 Gregor44b43212008-12-11 16:49:14 +0000119 if (CurContext == TD->getDeclContext()) {
120 // We're pushing the tag into the current context, which might
121 // require some reshuffling in the identifier resolver.
122 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000123 I = IdResolver.begin(TD->getDeclName(), CurContext,
124 false/*LookInParentCtx*/),
125 IEnd = IdResolver.end();
126 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
127 NamedDecl *PrevDecl = *I;
128 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
129 PrevDecl = *I, ++I) {
130 if (TD->declarationReplaces(*I)) {
131 // This is a redeclaration. Remove it from the chain and
132 // break out, so that we'll add in the shadowed
133 // declaration.
134 S->RemoveDecl(*I);
135 if (PrevDecl == *I) {
136 IdResolver.RemoveDecl(*I);
137 IdResolver.AddDecl(TD);
138 return;
139 } else {
140 IdResolver.RemoveDecl(*I);
141 break;
142 }
143 }
144 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000145
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000146 // There is already a declaration with the same name in the same
147 // scope, which is not a tag declaration. It must be found
148 // before we find the new declaration, so insert the new
149 // declaration at the end of the chain.
150 IdResolver.AddShadowedDecl(TD, PrevDecl);
151
152 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000153 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000154 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000155 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000156 // We are pushing the name of a function, which might be an
157 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000158 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor074149e2009-01-05 19:45:36 +0000159 DeclContext *DC = FD->getDeclContext();
160 while (DC->isTransparentContext())
161 DC = DC->getParent();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000162 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000163 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000164 false/*LookInParentCtx*/),
165 IdResolver.end(),
166 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
167 FD));
168 if (Redecl != IdResolver.end()) {
169 // There is already a declaration of a function on our
170 // IdResolver chain. Replace it with this declaration.
171 S->RemoveDecl(*Redecl);
172 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000174 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000175
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000176 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000177}
178
Steve Naroffb216c882007-10-09 22:01:59 +0000179void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000180 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000181 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
182 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
185 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000186 Decl *TmpD = static_cast<Decl*>(*I);
187 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000188
Douglas Gregor44b43212008-12-11 16:49:14 +0000189 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
190 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000191
Douglas Gregor44b43212008-12-11 16:49:14 +0000192 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000193
Douglas Gregor44b43212008-12-11 16:49:14 +0000194 // Remove this name from our lexical scope.
195 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 }
197}
198
Steve Naroffe8043c32008-04-01 23:04:06 +0000199/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
200/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000201ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000202 // The third "scope" argument is 0 since we aren't enabling lazy built-in
203 // creation from this context.
204 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000205
Steve Naroffb327ce02008-04-02 14:35:35 +0000206 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000207}
208
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000209/// MaybeConstructOverloadSet - Name lookup has determined that the
210/// elements in [I, IEnd) have the name that we are looking for, and
211/// *I is a match for the namespace. This routine returns an
212/// appropriate Decl for name lookup, which may either be *I or an
213/// OverloadeFunctionDecl that represents the overloaded functions in
214/// [I, IEnd).
215///
216/// The existance of this routine is temporary; LookupDecl should
217/// probably be able to return multiple results, to deal with cases of
218/// ambiguity and overloaded functions without needing to create a
219/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000220template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000221static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000222MaybeConstructOverloadSet(ASTContext &Context,
223 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000224 assert(I != IEnd && "Iterator range cannot be empty");
225 assert(!isa<OverloadedFunctionDecl>(*I) &&
226 "Cannot have an overloaded function");
227
228 if (isa<FunctionDecl>(*I)) {
229 // If we found a function, there might be more functions. If
230 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000231 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000232 OverloadedFunctionDecl *Ovl = 0;
233 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
234 if (!Ovl) {
235 // FIXME: We leak this overload set. Eventually, we want to
236 // stop building the declarations for these overload sets, so
237 // there will be nothing to leak.
238 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000239 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000240 (*I)->getDeclName());
241 Ovl->addOverload(cast<FunctionDecl>(*I));
242 }
243 Ovl->addOverload(cast<FunctionDecl>(*Last));
244 }
245
246 // If we had more than one function, we built an overload
247 // set. Return it.
248 if (Ovl)
249 return Ovl;
250 }
251
252 return *I;
253}
254
Steve Naroffe8043c32008-04-01 23:04:06 +0000255/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000256/// namespace. NamespaceNameOnly - during lookup only namespace names
257/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
258/// 'When looking up a namespace-name in a using-directive or
259/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000260Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000261 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000262 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000263 bool LookInParent,
264 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000265 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000266 unsigned NS = NSI;
267 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
268 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000269
Douglas Gregore267ff32008-12-11 20:41:00 +0000270 if (LookupCtx == 0 &&
271 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
272 // Unqualified name lookup in C/Objective-C and name lookup for
273 // labels in C++ is purely lexical, so search in the
274 // declarations attached to the name.
275 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000276 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregore267ff32008-12-11 20:41:00 +0000277 IdentifierResolver::iterator I
278 = IdResolver.begin(Name, CurContext, LookInParent);
279
280 // Scan up the scope chain looking for a decl that matches this
281 // identifier that is in the appropriate namespace. This search
282 // should not take long, as shadowing of names is uncommon, and
283 // deep shadowing is extremely uncommon.
284 for (; I != IdResolver.end(); ++I)
285 if ((*I)->getIdentifierNamespace() & NS)
Douglas Gregorf780abc2008-12-30 03:27:21 +0000286 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000287 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000288 // Perform qualified name lookup into the LookupCtx.
289 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000290 DeclContext::lookup_const_iterator I, E;
291 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregorf780abc2008-12-30 03:27:21 +0000292 if ((*I)->getIdentifierNamespace() & NS) {
293 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) {
294 // Skip non-namespace name.
295 } else {
296 return MaybeConstructOverloadSet(Context, I, E);
297 }
298 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000299 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000300 // Name lookup for ordinary names and tag names in C++ requires
301 // looking into scopes that aren't strictly lexical, and
302 // therefore we walk through the context as well as walking
303 // through the scopes.
304 IdentifierResolver::iterator
305 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
306 IEnd = IdResolver.end();
307 for (; S; S = S->getParent()) {
308 // Check whether the IdResolver has anything in this scope.
309 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000310 for (; I != IEnd && S->isDeclScope(*I); ++I) {
311 if ((*I)->getIdentifierNamespace() & NS) {
Douglas Gregorf780abc2008-12-30 03:27:21 +0000312 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) {
313 // Skip non-namespace name.
314 } else {
315 // We found something. Look for anything else in our scope
316 // with this same name and in an acceptable identifier
317 // namespace, so that we can construct an overload set if we
318 // need to.
319 IdentifierResolver::iterator LastI = I;
320 for (++LastI; LastI != IEnd; ++LastI) {
321 if (((*LastI)->getIdentifierNamespace() & NS) == 0 ||
322 !S->isDeclScope(*LastI))
323 break;
324 }
325 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000326 }
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000327 }
328 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000329
330 // If there is an entity associated with this scope, it's a
331 // DeclContext. We might need to perform qualified lookup into
332 // it.
333 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
334 while (Ctx && Ctx->isFunctionOrMethod())
335 Ctx = Ctx->getParent();
336 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
337 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000338 DeclContext::lookup_const_iterator I, E;
339 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000340 // FIXME: Cache this result in the IdResolver
Douglas Gregorf780abc2008-12-30 03:27:21 +0000341 if ((*I)->getIdentifierNamespace() & NS) {
342 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) {}
343 else return MaybeConstructOverloadSet(Context, I, E);
344 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000345 }
346
347 Ctx = Ctx->getParent();
348 }
349
Douglas Gregor074149e2009-01-05 19:45:36 +0000350 if (!LookInParent && !Ctx->isTransparentContext())
Douglas Gregor44b43212008-12-11 16:49:14 +0000351 return 0;
352 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000353 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 // If we didn't find a use of this identifier, and if the identifier
356 // corresponds to a compiler builtin, create the decl object for the builtin
357 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000358 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000359 IdentifierInfo *II = Name.getAsIdentifierInfo();
360 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000361 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000362 // If this is a builtin on this (or all) targets, create the decl.
363 if (unsigned BuiltinID = II->getBuiltinID())
364 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
365 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000366 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000367 // @interface and @compatibility_alias introduce typedef-like names.
368 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000369 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000370 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000371 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
372 if (IDI != ObjCInterfaceDecls.end())
373 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000374 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
375 if (I != ObjCAliasDecls.end())
376 return I->second->getClassInterface();
377 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 }
379 return 0;
380}
381
Chris Lattner95e2c712008-05-05 22:18:14 +0000382void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000383 if (!Context.getBuiltinVaListType().isNull())
384 return;
385
386 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000387 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000388 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000389 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
390}
391
Reid Spencer5f016e22007-07-11 17:01:13 +0000392/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
393/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000394ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
395 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 Builtin::ID BID = (Builtin::ID)bid;
397
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000398 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000399 InitBuiltinVaListType();
400
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000401 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000402 FunctionDecl *New = FunctionDecl::Create(Context,
403 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000404 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000405 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406
Chris Lattner95e2c712008-05-05 22:18:14 +0000407 // Create Decl objects for each parameter, adding them to the
408 // FunctionDecl.
409 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
410 llvm::SmallVector<ParmVarDecl*, 16> Params;
411 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
412 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
413 FT->getArgType(i), VarDecl::None, 0,
414 0));
415 New->setParams(&Params[0], Params.size());
416 }
417
418
419
Chris Lattner7f925cc2008-04-11 07:00:53 +0000420 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000421 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 return New;
423}
424
Sebastian Redlc42e1182008-11-11 11:37:55 +0000425/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
426/// everything from the standard library is defined.
427NamespaceDecl *Sema::GetStdNamespace() {
428 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000429 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000430 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000431 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000432 0, Global, /*enableLazyBuiltinCreation=*/false);
433 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
434 }
435 return StdNamespace;
436}
437
Reid Spencer5f016e22007-07-11 17:01:13 +0000438/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
439/// and scope as a previous declaration 'Old'. Figure out how to resolve this
440/// situation, merging decls or emitting diagnostics as appropriate.
441///
Steve Naroffe8043c32008-04-01 23:04:06 +0000442TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000443 // Allow multiple definitions for ObjC built-in typedefs.
444 // FIXME: Verify the underlying types are equivalent!
445 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000446 const IdentifierInfo *TypeID = New->getIdentifier();
447 switch (TypeID->getLength()) {
448 default: break;
449 case 2:
450 if (!TypeID->isStr("id"))
451 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000452 Context.setObjCIdType(New);
453 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000454 case 5:
455 if (!TypeID->isStr("Class"))
456 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000457 Context.setObjCClassType(New);
458 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000459 case 3:
460 if (!TypeID->isStr("SEL"))
461 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000462 Context.setObjCSelType(New);
463 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000464 case 8:
465 if (!TypeID->isStr("Protocol"))
466 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000467 Context.setObjCProtoType(New->getUnderlyingType());
468 return New;
469 }
470 // Fall through - the typedef name was not a builtin type.
471 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // Verify the old decl was also a typedef.
473 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
474 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000475 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000476 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000477 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 return New;
479 }
480
Chris Lattner99cb9972008-07-25 18:44:27 +0000481 // If the typedef types are not identical, reject them in all languages and
482 // with any extensions enabled.
483 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
484 Context.getCanonicalType(Old->getUnderlyingType()) !=
485 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000486 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000487 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000488 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000489 return Old;
490 }
491
Eli Friedman54ecfce2008-06-11 06:20:39 +0000492 if (getLangOptions().Microsoft) return New;
493
Douglas Gregorbbe27432008-11-21 16:29:06 +0000494 // C++ [dcl.typedef]p2:
495 // In a given non-class scope, a typedef specifier can be used to
496 // redefine the name of any type declared in that scope to refer
497 // to the type to which it already refers.
498 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
499 return New;
500
501 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000502 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
503 // *either* declaration is in a system header. The code below implements
504 // this adhoc compatibility rule. FIXME: The following code will not
505 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000506 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
507 SourceManager &SrcMgr = Context.getSourceManager();
508 if (SrcMgr.isInSystemHeader(Old->getLocation()))
509 return New;
510 if (SrcMgr.isInSystemHeader(New->getLocation()))
511 return New;
512 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000513
Chris Lattner08631c52008-11-23 21:45:46 +0000514 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000515 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 return New;
517}
518
Chris Lattner6b6b5372008-06-26 18:38:35 +0000519/// DeclhasAttr - returns true if decl Declaration already has the target
520/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000521static bool DeclHasAttr(const Decl *decl, const Attr *target) {
522 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
523 if (attr->getKind() == target->getKind())
524 return true;
525
526 return false;
527}
528
529/// MergeAttributes - append attributes from the Old decl to the New one.
530static void MergeAttributes(Decl *New, Decl *Old) {
531 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
532
Chris Lattnerddee4232008-03-03 03:28:21 +0000533 while (attr) {
534 tmp = attr;
535 attr = attr->getNext();
536
537 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000538 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000539 New->addAttr(tmp);
540 } else {
541 tmp->setNext(0);
542 delete(tmp);
543 }
544 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000545
546 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000547}
548
Chris Lattner04421082008-04-08 04:40:51 +0000549/// MergeFunctionDecl - We just parsed a function 'New' from
550/// declarator D which has the same name and scope as a previous
551/// declaration 'Old'. Figure out how to resolve this situation,
552/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553/// Redeclaration will be set true if this New is a redeclaration OldD.
554///
555/// In C++, New and Old must be declarations that are not
556/// overloaded. Use IsOverload to determine whether New and Old are
557/// overloaded, and to select the Old declaration that New should be
558/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000559FunctionDecl *
560Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 assert(!isa<OverloadedFunctionDecl>(OldD) &&
562 "Cannot merge with an overloaded function declaration");
563
Douglas Gregorf0097952008-04-21 02:02:58 +0000564 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 // Verify the old decl was also a function.
566 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
567 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000568 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000569 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000570 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 return New;
572 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573
574 // Determine whether the previous declaration was a definition,
575 // implicit declaration, or a declaration.
576 diag::kind PrevDiag;
577 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000578 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000579 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000580 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000582 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000583
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000584 QualType OldQType = Context.getCanonicalType(Old->getType());
585 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000586
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000587 if (getLangOptions().CPlusPlus) {
588 // (C++98 13.1p2):
589 // Certain function declarations cannot be overloaded:
590 // -- Function declarations that differ only in the return type
591 // cannot be overloaded.
592 QualType OldReturnType
593 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
594 QualType NewReturnType
595 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
596 if (OldReturnType != NewReturnType) {
597 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
598 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000599 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000600 return New;
601 }
602
603 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
604 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
605 if (OldMethod && NewMethod) {
606 // -- Member function declarations with the same name and the
607 // same parameter types cannot be overloaded if any of them
608 // is a static member function declaration.
609 if (OldMethod->isStatic() || NewMethod->isStatic()) {
610 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
611 Diag(Old->getLocation(), PrevDiag);
612 return New;
613 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000614
615 // C++ [class.mem]p1:
616 // [...] A member shall not be declared twice in the
617 // member-specification, except that a nested class or member
618 // class template can be declared and then later defined.
619 if (OldMethod->getLexicalDeclContext() ==
620 NewMethod->getLexicalDeclContext()) {
621 unsigned NewDiag;
622 if (isa<CXXConstructorDecl>(OldMethod))
623 NewDiag = diag::err_constructor_redeclared;
624 else if (isa<CXXDestructorDecl>(NewMethod))
625 NewDiag = diag::err_destructor_redeclared;
626 else if (isa<CXXConversionDecl>(NewMethod))
627 NewDiag = diag::err_conv_function_redeclared;
628 else
629 NewDiag = diag::err_member_redeclared;
630
631 Diag(New->getLocation(), NewDiag);
632 Diag(Old->getLocation(), PrevDiag);
633 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000634 }
635
636 // (C++98 8.3.5p3):
637 // All declarations for a function shall agree exactly in both the
638 // return type and the parameter-type-list.
639 if (OldQType == NewQType) {
640 // We have a redeclaration.
641 MergeAttributes(New, Old);
642 Redeclaration = true;
643 return MergeCXXFunctionDecl(New, Old);
644 }
645
646 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000647 }
Chris Lattner04421082008-04-08 04:40:51 +0000648
649 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000650 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000651 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000652 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000653 MergeAttributes(New, Old);
654 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000655 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000656 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000657
Steve Naroff837618c2008-01-16 15:01:34 +0000658 // A function that has already been declared has been redeclared or defined
659 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000660
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
662 // TODO: This is totally simplistic. It should handle merging functions
663 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000664 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000665 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 return New;
667}
668
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000669/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000670static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000671 if (VD->isFileVarDecl())
672 return (!VD->getInit() &&
673 (VD->getStorageClass() == VarDecl::None ||
674 VD->getStorageClass() == VarDecl::Static));
675 return false;
676}
677
678/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
679/// when dealing with C "tentative" external object definitions (C99 6.9.2).
680void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
681 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000682 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000683
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000684 // FIXME: I don't this will actually see all of the
685 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000686 for (IdentifierResolver::iterator
687 I = IdResolver.begin(VD->getIdentifier(),
688 VD->getDeclContext(), false/*LookInParentCtx*/),
689 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000690 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000691 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
692
Steve Narofff855e6f2008-08-10 15:20:13 +0000693 // Handle the following case:
694 // int a[10];
695 // int a[]; - the code below makes sure we set the correct type.
696 // int a[11]; - this is an error, size isn't 10.
697 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
698 OldDecl->getType()->isConstantArrayType())
699 VD->setType(OldDecl->getType());
700
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000701 // Check for "tentative" definitions. We can't accomplish this in
702 // MergeVarDecl since the initializer hasn't been attached.
703 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
704 continue;
705
706 // Handle __private_extern__ just like extern.
707 if (OldDecl->getStorageClass() != VarDecl::Extern &&
708 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
709 VD->getStorageClass() != VarDecl::Extern &&
710 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000711 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000712 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000713 }
714 }
715 }
716}
717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718/// MergeVarDecl - We just parsed a variable 'New' which has the same name
719/// and scope as a previous declaration 'Old'. Figure out how to resolve this
720/// situation, merging decls or emitting diagnostics as appropriate.
721///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000722/// Tentative definition rules (C99 6.9.2p2) are checked by
723/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
724/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000725///
Steve Naroffe8043c32008-04-01 23:04:06 +0000726VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 // Verify the old decl was also a variable.
728 VarDecl *Old = dyn_cast<VarDecl>(OldD);
729 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000730 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000731 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000732 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 return New;
734 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000735
736 MergeAttributes(New, Old);
737
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000739 QualType OldCType = Context.getCanonicalType(Old->getType());
740 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000741 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000742 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000743 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 return New;
745 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000746 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
747 if (New->getStorageClass() == VarDecl::Static &&
748 (Old->getStorageClass() == VarDecl::None ||
749 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000750 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000751 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000752 return New;
753 }
754 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
755 if (New->getStorageClass() != VarDecl::Static &&
756 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000757 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000758 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000759 return New;
760 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000761 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
762 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000763 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000764 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 }
766 return New;
767}
768
Chris Lattner04421082008-04-08 04:40:51 +0000769/// CheckParmsForFunctionDef - Check that the parameters of the given
770/// function are appropriate for the definition of a function. This
771/// takes care of any checks that cannot be performed on the
772/// declaration itself, e.g., that the types of each of the function
773/// parameters are complete.
774bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
775 bool HasInvalidParm = false;
776 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
777 ParmVarDecl *Param = FD->getParamDecl(p);
778
779 // C99 6.7.5.3p4: the parameters in a parameter type list in a
780 // function declarator that is part of a function definition of
781 // that function shall not have incomplete type.
782 if (Param->getType()->isIncompleteType() &&
783 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000784 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000785 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000786 Param->setInvalidDecl();
787 HasInvalidParm = true;
788 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000789
790 // C99 6.9.1p5: If the declarator includes a parameter type list, the
791 // declaration of each parameter shall include an identifier.
792 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
793 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000794 }
795
796 return HasInvalidParm;
797}
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
800/// no declarator (e.g. "struct foo;") is parsed.
801Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000802 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
803 if (!DS.isMissingDeclaratorOk()) {
804 // FIXME: This diagnostic is emitted even when various previous
805 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
806 // DeclSpec has no means of communicating this information, and the
807 // responsible parser functions are quite far apart.
808 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
809 << DS.getSourceRange();
810 return 0;
811 }
812
Steve Naroff92199282007-11-17 21:37:36 +0000813 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000814}
815
Steve Naroffd0091aa2008-01-10 22:15:12 +0000816bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000817 // Get the type before calling CheckSingleAssignmentConstraints(), since
818 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000819 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000820
821 if (getLangOptions().CPlusPlus)
822 return PerformCopyInitialization(Init, DeclType, "initializing");
823
Chris Lattner5cf216b2008-01-04 18:04:52 +0000824 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
825 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
826 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000827}
828
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000829bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000830 const ArrayType *AT = Context.getAsArrayType(DeclT);
831
832 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000833 // C99 6.7.8p14. We have an array of character type with unknown size
834 // being initialized to a string literal.
835 llvm::APSInt ConstVal(32);
836 ConstVal = strLiteral->getByteLength() + 1;
837 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000838 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000839 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000840 } else {
841 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000842 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000843 // FIXME: Avoid truncation for 64-bit length strings.
844 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000845 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000846 diag::warn_initializer_string_for_char_array_too_long)
847 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000848 }
849 // Set type from "char *" to "constant array of char".
850 strLiteral->setType(DeclT);
851 // For now, we always return false (meaning success).
852 return false;
853}
854
855StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000856 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000857 if (AT && AT->getElementType()->isCharType()) {
858 return dyn_cast<StringLiteral>(Init);
859 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000860 return 0;
861}
862
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000863bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
864 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000865 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000866 if (DeclType->isDependentType() || Init->isTypeDependent())
867 return false;
868
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000869 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000870 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000871 // (8.3.2), shall be initialized by an object, or function, of
872 // type T or by an object that can be converted into a T.
873 if (DeclType->isReferenceType())
874 return CheckReferenceInit(Init, DeclType);
875
Steve Naroffca107302008-01-21 23:53:58 +0000876 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
877 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000878 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000879 return Diag(InitLoc, diag::err_variable_object_no_init)
880 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000881
Steve Naroff2fdc3742007-12-10 22:44:33 +0000882 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
883 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000884 // FIXME: Handle wide strings
885 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
886 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000887
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000888 // C++ [dcl.init]p14:
889 // -- If the destination type is a (possibly cv-qualified) class
890 // type:
891 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
892 QualType DeclTypeC = Context.getCanonicalType(DeclType);
893 QualType InitTypeC = Context.getCanonicalType(Init->getType());
894
895 // -- If the initialization is direct-initialization, or if it is
896 // copy-initialization where the cv-unqualified version of the
897 // source type is the same class as, or a derived class of, the
898 // class of the destination, constructors are considered.
899 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
900 IsDerivedFrom(InitTypeC, DeclTypeC)) {
901 CXXConstructorDecl *Constructor
902 = PerformInitializationByConstructor(DeclType, &Init, 1,
903 InitLoc, Init->getSourceRange(),
904 InitEntity, IK_Copy);
905 return Constructor == 0;
906 }
907
908 // -- Otherwise (i.e., for the remaining copy-initialization
909 // cases), user-defined conversion sequences that can
910 // convert from the source type to the destination type or
911 // (when a conversion function is used) to a derived class
912 // thereof are enumerated as described in 13.3.1.4, and the
913 // best one is chosen through overload resolution
914 // (13.3). If the conversion cannot be done or is
915 // ambiguous, the initialization is ill-formed. The
916 // function selected is called with the initializer
917 // expression as its argument; if the function is a
918 // constructor, the call initializes a temporary of the
919 // destination type.
920 // FIXME: We're pretending to do copy elision here; return to
921 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000922 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000923 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000924
Douglas Gregor61366e92008-12-24 00:01:03 +0000925 if (InitEntity)
926 return Diag(InitLoc, diag::err_cannot_initialize_decl)
927 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
928 << Init->getType() << Init->getSourceRange();
929 else
930 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
931 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
932 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000933 }
934
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000935 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000936 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000937 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
938 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000939
Steve Naroffd0091aa2008-01-10 22:15:12 +0000940 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000941 } else if (getLangOptions().CPlusPlus) {
942 // C++ [dcl.init]p14:
943 // [...] If the class is an aggregate (8.5.1), and the initializer
944 // is a brace-enclosed list, see 8.5.1.
945 //
946 // Note: 8.5.1 is handled below; here, we diagnose the case where
947 // we have an initializer list and a destination type that is not
948 // an aggregate.
949 // FIXME: In C++0x, this is yet another form of initialization.
950 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
951 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
952 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000953 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000954 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000955 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000956 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000957
Steve Naroff0cca7492008-05-01 22:18:59 +0000958 InitListChecker CheckInitList(this, InitList, DeclType);
959 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000960}
961
Douglas Gregor10bd3682008-11-17 22:58:34 +0000962/// GetNameForDeclarator - Determine the full declaration name for the
963/// given Declarator.
964DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
965 switch (D.getKind()) {
966 case Declarator::DK_Abstract:
967 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
968 return DeclarationName();
969
970 case Declarator::DK_Normal:
971 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
972 return DeclarationName(D.getIdentifier());
973
974 case Declarator::DK_Constructor: {
975 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
976 Ty = Context.getCanonicalType(Ty);
977 return Context.DeclarationNames.getCXXConstructorName(Ty);
978 }
979
980 case Declarator::DK_Destructor: {
981 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
982 Ty = Context.getCanonicalType(Ty);
983 return Context.DeclarationNames.getCXXDestructorName(Ty);
984 }
985
986 case Declarator::DK_Conversion: {
987 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
988 Ty = Context.getCanonicalType(Ty);
989 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
990 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000991
992 case Declarator::DK_Operator:
993 assert(D.getIdentifier() == 0 && "operator names have no identifier");
994 return Context.DeclarationNames.getCXXOperatorName(
995 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000996 }
997
998 assert(false && "Unknown name kind");
999 return DeclarationName();
1000}
1001
Douglas Gregor584049d2008-12-15 23:53:10 +00001002/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1003/// functions Declaration and Definition are "nearly" matching. This
1004/// heuristic is used to improve diagnostics in the case where an
1005/// out-of-line member function definition doesn't match any
1006/// declaration within the class.
1007static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1008 FunctionDecl *Declaration,
1009 FunctionDecl *Definition) {
1010 if (Declaration->param_size() != Definition->param_size())
1011 return false;
1012 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1013 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1014 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1015
1016 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1017 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1018 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1019 return false;
1020 }
1021
1022 return true;
1023}
1024
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001025Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001026Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1027 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001028 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001029 DeclarationName Name = GetNameForDeclarator(D);
1030
Chris Lattnere80a59c2007-07-25 00:24:17 +00001031 // All of these full declarators require an identifier. If it doesn't have
1032 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001033 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001034 if (!D.getInvalidType()) // Reject this if we think it is valid.
1035 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001036 diag::err_declarator_need_ident)
1037 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001038 return 0;
1039 }
1040
Chris Lattner31e05722007-08-26 06:24:45 +00001041 // The scope passed in may not be a decl scope. Zip up the scope tree until
1042 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001043 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1044 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001045 S = S->getParent();
1046
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001047 DeclContext *DC;
1048 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001049 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001050 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001051
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001052 // See if this is a redefinition of a variable in the same scope.
1053 if (!D.getCXXScopeSpec().isSet()) {
1054 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001055 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001056 } else { // Something like "int foo::x;"
1057 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001058 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001059
1060 // C++ 7.3.1.2p2:
1061 // Members (including explicit specializations of templates) of a named
1062 // namespace can also be defined outside that namespace by explicit
1063 // qualification of the name being defined, provided that the entity being
1064 // defined was already declared in the namespace and the definition appears
1065 // after the point of declaration in a namespace that encloses the
1066 // declarations namespace.
1067 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001068 // Note that we only check the context at this point. We don't yet
1069 // have enough information to make sure that PrevDecl is actually
1070 // the declaration we want to match. For example, given:
1071 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001072 // class X {
1073 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001074 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001075 // };
1076 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001077 // void X::f(int) { } // ill-formed
1078 //
1079 // In this case, PrevDecl will point to the overload set
1080 // containing the two f's declared in X, but neither of them
1081 // matches.
1082 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001083 // The qualifying scope doesn't enclose the original declaration.
1084 // Emit diagnostic based on current scope.
1085 SourceLocation L = D.getIdentifierLoc();
1086 SourceRange R = D.getCXXScopeSpec().getRange();
1087 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001088 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001089 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001090 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001091 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001092 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001093 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001094 }
1095 }
1096
Douglas Gregorf57172b2008-12-08 18:40:42 +00001097 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001098 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001099 InvalidDecl = InvalidDecl
1100 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001101 // Just pretend that we didn't see the previous declaration.
1102 PrevDecl = 0;
1103 }
1104
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001105 // In C++, the previous declaration we find might be a tag type
1106 // (class or enum). In this case, the new declaration will hide the
1107 // tag type.
1108 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1109 PrevDecl = 0;
1110
Chris Lattner41af0932007-11-14 06:34:38 +00001111 QualType R = GetTypeForDeclarator(D, S);
1112 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001115 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1116 if (D.getCXXScopeSpec().isSet()) {
1117 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1118 << D.getCXXScopeSpec().getRange();
1119 InvalidDecl = true;
1120 // Pretend we didn't see the scope specifier.
1121 DC = 0;
1122 }
1123
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001124 // Check that there are no default arguments (C++ only).
1125 if (getLangOptions().CPlusPlus)
1126 CheckExtraCXXDefaultArguments(D);
1127
Chris Lattner41af0932007-11-14 06:34:38 +00001128 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 if (!NewTD) return 0;
1130
1131 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001132 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001133 // Merge the decl with the existing one if appropriate. If the decl is
1134 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001135 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1137 if (NewTD == 0) return 0;
1138 }
1139 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001140 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1142 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001143 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001144 if (NewTD->getUnderlyingType()->isVariableArrayType())
1145 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1146 else
1147 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1148
Steve Naroffd7444aa2007-08-31 17:20:07 +00001149 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 }
1151 }
Chris Lattner41af0932007-11-14 06:34:38 +00001152 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001153 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 switch (D.getDeclSpec().getStorageClassSpec()) {
1155 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001156 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001158 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001159 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001160 InvalidDecl = true;
1161 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1163 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1164 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001165 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 }
1167
Chris Lattnera98e58d2008-03-15 21:24:04 +00001168 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001169 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001170 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1171
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001172 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001173 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001174 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001175 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001176 "Constructors can only be declared in a member context");
1177
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001178 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001179
1180 // Create the new declaration
1181 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001182 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001183 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001184 isExplicit, isInline,
1185 /*isImplicitlyDeclared=*/false);
1186
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001187 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001188 NewFD->setInvalidDecl();
1189 } else if (D.getKind() == Declarator::DK_Destructor) {
1190 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001191 if (DC->isCXXRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001192 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001193
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001194 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001195 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001196 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001197 isInline,
1198 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001199
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001200 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001201 NewFD->setInvalidDecl();
1202 } else {
1203 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001204
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001205 // Create a FunctionDecl to satisfy the function definition parsing
1206 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001207 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001208 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001209 // FIXME: Move to DeclGroup...
1210 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001211 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001212 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001213 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001214 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001216 Diag(D.getIdentifierLoc(),
1217 diag::err_conv_function_not_member);
1218 return 0;
1219 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001220 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001221
Douglas Gregor70316a02008-12-26 15:00:45 +00001222 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001223 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001224 isInline, isExplicit);
1225
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001226 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001227 NewFD->setInvalidDecl();
1228 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001229 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001230 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001231 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001232 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001233 (SC == FunctionDecl::Static), isInline,
1234 LastDeclarator);
1235 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001236 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001237 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001238 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001239 // FIXME: Move to DeclGroup...
1240 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001241 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001242
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001243 // Set the lexical context. If the declarator has a C++
1244 // scope specifier, the lexical context will be different
1245 // from the semantic context.
1246 NewFD->setLexicalDeclContext(CurContext);
1247
Daniel Dunbara80f8742008-08-05 01:35:17 +00001248 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001249 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001250 // The parser guarantees this is a string.
1251 StringLiteral *SE = cast<StringLiteral>(E);
1252 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1253 SE->getByteLength())));
1254 }
1255
Chris Lattner04421082008-04-08 04:40:51 +00001256 // Copy the parameter declarations from the declarator D to
1257 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001258 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001259 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1260
1261 // Create Decl objects for each parameter, adding them to the
1262 // FunctionDecl.
1263 llvm::SmallVector<ParmVarDecl*, 16> Params;
1264
1265 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1266 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001267 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001268 // We let through "const void" here because Sema::GetTypeForDeclarator
1269 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001270 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1271 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001272 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1273 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001274 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1275
Chris Lattnerdef026a2008-04-10 02:26:16 +00001276 // In C++, the empty parameter-type-list must be spelled "void"; a
1277 // typedef of void is not permitted.
1278 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001279 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001280 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1281 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001282 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001283 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1284 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1285 }
1286
1287 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001288 } else if (R->getAsTypedefType()) {
1289 // When we're declaring a function with a typedef, as in the
1290 // following example, we'll need to synthesize (unnamed)
1291 // parameters for use in the declaration.
1292 //
1293 // @code
1294 // typedef void fn(int);
1295 // fn f;
1296 // @endcode
1297 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1298 if (!FT) {
1299 // This is a typedef of a function with no prototype, so we
1300 // don't need to do anything.
1301 } else if ((FT->getNumArgs() == 0) ||
1302 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1303 FT->getArgType(0)->isVoidType())) {
1304 // This is a zero-argument function. We don't need to do anything.
1305 } else {
1306 // Synthesize a parameter for each argument type.
1307 llvm::SmallVector<ParmVarDecl*, 16> Params;
1308 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1309 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001310 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001311 SourceLocation(), 0,
1312 *ArgType, VarDecl::None,
1313 0, 0));
1314 }
1315
1316 NewFD->setParams(&Params[0], Params.size());
1317 }
Chris Lattner04421082008-04-08 04:40:51 +00001318 }
1319
Douglas Gregor72b505b2008-12-16 21:30:33 +00001320 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1321 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001322 else if (isa<CXXDestructorDecl>(NewFD)) {
1323 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1324 Record->setUserDeclaredDestructor(true);
1325 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1326 // user-defined destructor.
1327 Record->setPOD(false);
1328 } else if (CXXConversionDecl *Conversion =
1329 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001330 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001331
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001332 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1333 if (NewFD->isOverloadedOperator() &&
1334 CheckOverloadedOperatorDeclaration(NewFD))
1335 NewFD->setInvalidDecl();
1336
Steve Naroffffce4d52008-01-09 23:34:55 +00001337 // Merge the decl with the existing one if appropriate. Since C functions
1338 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001339 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001340 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001341 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342
1343 // If C++, determine whether NewFD is an overload of PrevDecl or
1344 // a declaration that requires merging. If it's an overload,
1345 // there's no more work to do here; we'll just add the new
1346 // function to the scope.
1347 OverloadedFunctionDecl::function_iterator MatchedDecl;
1348 if (!getLangOptions().CPlusPlus ||
1349 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1350 Decl *OldDecl = PrevDecl;
1351
1352 // If PrevDecl was an overloaded function, extract the
1353 // FunctionDecl that matched.
1354 if (isa<OverloadedFunctionDecl>(PrevDecl))
1355 OldDecl = *MatchedDecl;
1356
1357 // NewFD and PrevDecl represent declarations that need to be
1358 // merged.
1359 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1360
1361 if (NewFD == 0) return 0;
1362 if (Redeclaration) {
1363 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1364
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001365 // An out-of-line member function declaration must also be a
1366 // definition (C++ [dcl.meaning]p1).
1367 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1368 !InvalidDecl) {
1369 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1370 << D.getCXXScopeSpec().getRange();
1371 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001372 }
1373 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001374 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001375
1376 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1377 // The user tried to provide an out-of-line definition for a
1378 // member function, but there was no such member function
1379 // declared (C++ [class.mfct]p2). For example:
1380 //
1381 // class X {
1382 // void f() const;
1383 // };
1384 //
1385 // void X::f() { } // ill-formed
1386 //
1387 // Complain about this problem, and attempt to suggest close
1388 // matches (e.g., those that differ only in cv-qualifiers and
1389 // whether the parameter types are references).
1390 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1391 << cast<CXXRecordDecl>(DC)->getDeclName()
1392 << D.getCXXScopeSpec().getRange();
1393 InvalidDecl = true;
1394
1395 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1396 if (!PrevDecl) {
1397 // Nothing to suggest.
1398 } else if (OverloadedFunctionDecl *Ovl
1399 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1400 for (OverloadedFunctionDecl::function_iterator
1401 Func = Ovl->function_begin(),
1402 FuncEnd = Ovl->function_end();
1403 Func != FuncEnd; ++Func) {
1404 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1405 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1406
1407 }
1408 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1409 // Suggest this no matter how mismatched it is; it's the only
1410 // thing we have.
1411 unsigned diag;
1412 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1413 diag = diag::note_member_def_close_match;
1414 else if (Method->getBody())
1415 diag = diag::note_previous_definition;
1416 else
1417 diag = diag::note_previous_declaration;
1418 Diag(Method->getLocation(), diag);
1419 }
1420
1421 PrevDecl = 0;
1422 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001424 // Handle attributes. We need to have merged decls when handling attributes
1425 // (for example to check for conflicts, etc).
1426 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001428
Douglas Gregor584049d2008-12-15 23:53:10 +00001429 if (getLangOptions().CPlusPlus) {
1430 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001431 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001432
1433 // An out-of-line member function declaration must also be a
1434 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001435 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001436 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1437 << D.getCXXScopeSpec().getRange();
1438 InvalidDecl = true;
1439 }
1440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001442 // Check that there are no default arguments (C++ only).
1443 if (getLangOptions().CPlusPlus)
1444 CheckExtraCXXDefaultArguments(D);
1445
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001446 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001447 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1448 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001449 InvalidDecl = true;
1450 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001451
1452 VarDecl *NewVD;
1453 VarDecl::StorageClass SC;
1454 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001455 default: assert(0 && "Unknown storage class!");
1456 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1457 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1458 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1459 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1460 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1461 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001462 case DeclSpec::SCS_mutable:
1463 // mutable can only appear on non-static class members, so it's always
1464 // an error here
1465 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1466 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001467 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001468 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001469 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001470
1471 IdentifierInfo *II = Name.getAsIdentifierInfo();
1472 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001473 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1474 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001475 return 0;
1476 }
1477
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001478 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001480 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001481 D.getIdentifierLoc(), II,
1482 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001483 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001484 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001485 if (S->getFnParent() == 0) {
1486 // C99 6.9p2: The storage-class specifiers auto and register shall not
1487 // appear in the declaration specifiers in an external declaration.
1488 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001489 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001490 InvalidDecl = true;
1491 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001493 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1494 II, R, SC, LastDeclarator,
1495 // FIXME: Move to DeclGroup...
1496 D.getDeclSpec().getSourceRange().getBegin());
1497 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001498 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001500 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001501
Daniel Dunbara735ad82008-08-06 00:03:29 +00001502 // Handle GNU asm-label extension (encoded as an attribute).
1503 if (Expr *E = (Expr*) D.getAsmLabel()) {
1504 // The parser guarantees this is a string.
1505 StringLiteral *SE = cast<StringLiteral>(E);
1506 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1507 SE->getByteLength())));
1508 }
1509
Nate Begemanc8e89a82008-03-14 18:07:10 +00001510 // Emit an error if an address space was applied to decl with local storage.
1511 // This includes arrays of objects with address space qualifiers, but not
1512 // automatic variables that point to other address spaces.
1513 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001514 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1515 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1516 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001517 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001518 // Merge the decl with the existing one if appropriate. If the decl is
1519 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001520 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001521 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1522 // The user tried to define a non-static data member
1523 // out-of-line (C++ [dcl.meaning]p1).
1524 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1525 << D.getCXXScopeSpec().getRange();
1526 NewVD->Destroy(Context);
1527 return 0;
1528 }
1529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 NewVD = MergeVarDecl(NewVD, PrevDecl);
1531 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001532
1533 if (D.getCXXScopeSpec().isSet()) {
1534 // No previous declaration in the qualifying scope.
1535 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1536 << Name << D.getCXXScopeSpec().getRange();
1537 InvalidDecl = true;
1538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 New = NewVD;
1541 }
1542
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001543 // Set the lexical context. If the declarator has a C++ scope specifier, the
1544 // lexical context will be different from the semantic context.
1545 New->setLexicalDeclContext(CurContext);
1546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001548 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001549 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001550 // If any semantic error occurred, mark the decl as invalid.
1551 if (D.getInvalidType() || InvalidDecl)
1552 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001553
1554 return New;
1555}
1556
Steve Naroff6594a702008-10-27 11:34:16 +00001557void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001558 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1559 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001560}
1561
Eli Friedmanc594b322008-05-20 13:48:25 +00001562bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1563 switch (Init->getStmtClass()) {
1564 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001565 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001566 return true;
1567 case Expr::ParenExprClass: {
1568 const ParenExpr* PE = cast<ParenExpr>(Init);
1569 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1570 }
1571 case Expr::CompoundLiteralExprClass:
1572 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001573 case Expr::DeclRefExprClass:
1574 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001575 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001576 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1577 if (VD->hasGlobalStorage())
1578 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001579 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001580 return true;
1581 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001582 if (isa<FunctionDecl>(D))
1583 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001584 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001585 return true;
1586 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001587 case Expr::MemberExprClass: {
1588 const MemberExpr *M = cast<MemberExpr>(Init);
1589 if (M->isArrow())
1590 return CheckAddressConstantExpression(M->getBase());
1591 return CheckAddressConstantExpressionLValue(M->getBase());
1592 }
1593 case Expr::ArraySubscriptExprClass: {
1594 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1595 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1596 return CheckAddressConstantExpression(ASE->getBase()) ||
1597 CheckArithmeticConstantExpression(ASE->getIdx());
1598 }
1599 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001600 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001601 return false;
1602 case Expr::UnaryOperatorClass: {
1603 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1604
1605 // C99 6.6p9
1606 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001607 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001608
Steve Naroff6594a702008-10-27 11:34:16 +00001609 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001610 return true;
1611 }
1612 }
1613}
1614
1615bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1616 switch (Init->getStmtClass()) {
1617 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001618 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001619 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001620 case Expr::ParenExprClass:
1621 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001622 case Expr::StringLiteralClass:
1623 case Expr::ObjCStringLiteralClass:
1624 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001625 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001626 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001627 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1628 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1629 Builtin::BI__builtin___CFStringMakeConstantString)
1630 return false;
1631
Steve Naroff6594a702008-10-27 11:34:16 +00001632 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001633 return true;
1634
Eli Friedmanc594b322008-05-20 13:48:25 +00001635 case Expr::UnaryOperatorClass: {
1636 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1637
1638 // C99 6.6p9
1639 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1640 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1641
1642 if (Exp->getOpcode() == UnaryOperator::Extension)
1643 return CheckAddressConstantExpression(Exp->getSubExpr());
1644
Steve Naroff6594a702008-10-27 11:34:16 +00001645 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001646 return true;
1647 }
1648 case Expr::BinaryOperatorClass: {
1649 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1650 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1651
1652 Expr *PExp = Exp->getLHS();
1653 Expr *IExp = Exp->getRHS();
1654 if (IExp->getType()->isPointerType())
1655 std::swap(PExp, IExp);
1656
1657 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1658 return CheckAddressConstantExpression(PExp) ||
1659 CheckArithmeticConstantExpression(IExp);
1660 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001661 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001662 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001663 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001664 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1665 // Check for implicit promotion
1666 if (SubExpr->getType()->isFunctionType() ||
1667 SubExpr->getType()->isArrayType())
1668 return CheckAddressConstantExpressionLValue(SubExpr);
1669 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001670
1671 // Check for pointer->pointer cast
1672 if (SubExpr->getType()->isPointerType())
1673 return CheckAddressConstantExpression(SubExpr);
1674
Eli Friedmanc3f07642008-08-25 20:46:57 +00001675 if (SubExpr->getType()->isIntegralType()) {
1676 // Check for the special-case of a pointer->int->pointer cast;
1677 // this isn't standard, but some code requires it. See
1678 // PR2720 for an example.
1679 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1680 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1681 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1682 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1683 if (IntWidth >= PointerWidth) {
1684 return CheckAddressConstantExpression(SubCast->getSubExpr());
1685 }
1686 }
1687 }
1688 }
1689 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001690 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001691 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001692
Steve Naroff6594a702008-10-27 11:34:16 +00001693 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001694 return true;
1695 }
1696 case Expr::ConditionalOperatorClass: {
1697 // FIXME: Should we pedwarn here?
1698 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1699 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001700 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001701 return true;
1702 }
1703 if (CheckArithmeticConstantExpression(Exp->getCond()))
1704 return true;
1705 if (Exp->getLHS() &&
1706 CheckAddressConstantExpression(Exp->getLHS()))
1707 return true;
1708 return CheckAddressConstantExpression(Exp->getRHS());
1709 }
1710 case Expr::AddrLabelExprClass:
1711 return false;
1712 }
1713}
1714
Eli Friedman4caf0552008-06-09 05:05:07 +00001715static const Expr* FindExpressionBaseAddress(const Expr* E);
1716
1717static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1718 switch (E->getStmtClass()) {
1719 default:
1720 return E;
1721 case Expr::ParenExprClass: {
1722 const ParenExpr* PE = cast<ParenExpr>(E);
1723 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1724 }
1725 case Expr::MemberExprClass: {
1726 const MemberExpr *M = cast<MemberExpr>(E);
1727 if (M->isArrow())
1728 return FindExpressionBaseAddress(M->getBase());
1729 return FindExpressionBaseAddressLValue(M->getBase());
1730 }
1731 case Expr::ArraySubscriptExprClass: {
1732 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1733 return FindExpressionBaseAddress(ASE->getBase());
1734 }
1735 case Expr::UnaryOperatorClass: {
1736 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1737
1738 if (Exp->getOpcode() == UnaryOperator::Deref)
1739 return FindExpressionBaseAddress(Exp->getSubExpr());
1740
1741 return E;
1742 }
1743 }
1744}
1745
1746static const Expr* FindExpressionBaseAddress(const Expr* E) {
1747 switch (E->getStmtClass()) {
1748 default:
1749 return E;
1750 case Expr::ParenExprClass: {
1751 const ParenExpr* PE = cast<ParenExpr>(E);
1752 return FindExpressionBaseAddress(PE->getSubExpr());
1753 }
1754 case Expr::UnaryOperatorClass: {
1755 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1756
1757 // C99 6.6p9
1758 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1759 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1760
1761 if (Exp->getOpcode() == UnaryOperator::Extension)
1762 return FindExpressionBaseAddress(Exp->getSubExpr());
1763
1764 return E;
1765 }
1766 case Expr::BinaryOperatorClass: {
1767 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1768
1769 Expr *PExp = Exp->getLHS();
1770 Expr *IExp = Exp->getRHS();
1771 if (IExp->getType()->isPointerType())
1772 std::swap(PExp, IExp);
1773
1774 return FindExpressionBaseAddress(PExp);
1775 }
1776 case Expr::ImplicitCastExprClass: {
1777 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1778
1779 // Check for implicit promotion
1780 if (SubExpr->getType()->isFunctionType() ||
1781 SubExpr->getType()->isArrayType())
1782 return FindExpressionBaseAddressLValue(SubExpr);
1783
1784 // Check for pointer->pointer cast
1785 if (SubExpr->getType()->isPointerType())
1786 return FindExpressionBaseAddress(SubExpr);
1787
1788 // We assume that we have an arithmetic expression here;
1789 // if we don't, we'll figure it out later
1790 return 0;
1791 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001792 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001793 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1794
1795 // Check for pointer->pointer cast
1796 if (SubExpr->getType()->isPointerType())
1797 return FindExpressionBaseAddress(SubExpr);
1798
1799 // We assume that we have an arithmetic expression here;
1800 // if we don't, we'll figure it out later
1801 return 0;
1802 }
1803 }
1804}
1805
Anders Carlsson51fe9962008-11-22 21:04:56 +00001806bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001807 switch (Init->getStmtClass()) {
1808 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001809 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001810 return true;
1811 case Expr::ParenExprClass: {
1812 const ParenExpr* PE = cast<ParenExpr>(Init);
1813 return CheckArithmeticConstantExpression(PE->getSubExpr());
1814 }
1815 case Expr::FloatingLiteralClass:
1816 case Expr::IntegerLiteralClass:
1817 case Expr::CharacterLiteralClass:
1818 case Expr::ImaginaryLiteralClass:
1819 case Expr::TypesCompatibleExprClass:
1820 case Expr::CXXBoolLiteralExprClass:
1821 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001822 case Expr::CallExprClass:
1823 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001824 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001825
1826 // Allow any constant foldable calls to builtins.
1827 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001828 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001829
Steve Naroff6594a702008-10-27 11:34:16 +00001830 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001831 return true;
1832 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00001833 case Expr::DeclRefExprClass:
1834 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001835 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1836 if (isa<EnumConstantDecl>(D))
1837 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001838 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001839 return true;
1840 }
1841 case Expr::CompoundLiteralExprClass:
1842 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1843 // but vectors are allowed to be magic.
1844 if (Init->getType()->isVectorType())
1845 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001846 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001847 return true;
1848 case Expr::UnaryOperatorClass: {
1849 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1850
1851 switch (Exp->getOpcode()) {
1852 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1853 // See C99 6.6p3.
1854 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001855 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001856 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001857 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001858 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1859 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001860 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001861 return true;
1862 case UnaryOperator::Extension:
1863 case UnaryOperator::LNot:
1864 case UnaryOperator::Plus:
1865 case UnaryOperator::Minus:
1866 case UnaryOperator::Not:
1867 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1868 }
1869 }
Sebastian Redl05189992008-11-11 17:56:53 +00001870 case Expr::SizeOfAlignOfExprClass: {
1871 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001872 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001873 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001874 return false;
1875 // alignof always evaluates to a constant.
1876 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001877 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001878 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001879 return true;
1880 }
1881 return false;
1882 }
1883 case Expr::BinaryOperatorClass: {
1884 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1885
1886 if (Exp->getLHS()->getType()->isArithmeticType() &&
1887 Exp->getRHS()->getType()->isArithmeticType()) {
1888 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1889 CheckArithmeticConstantExpression(Exp->getRHS());
1890 }
1891
Eli Friedman4caf0552008-06-09 05:05:07 +00001892 if (Exp->getLHS()->getType()->isPointerType() &&
1893 Exp->getRHS()->getType()->isPointerType()) {
1894 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1895 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1896
1897 // Only allow a null (constant integer) base; we could
1898 // allow some additional cases if necessary, but this
1899 // is sufficient to cover offsetof-like constructs.
1900 if (!LHSBase && !RHSBase) {
1901 return CheckAddressConstantExpression(Exp->getLHS()) ||
1902 CheckAddressConstantExpression(Exp->getRHS());
1903 }
1904 }
1905
Steve Naroff6594a702008-10-27 11:34:16 +00001906 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001907 return true;
1908 }
1909 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001910 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001911 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001912 if (SubExpr->getType()->isArithmeticType())
1913 return CheckArithmeticConstantExpression(SubExpr);
1914
Eli Friedmanb529d832008-09-02 09:37:00 +00001915 if (SubExpr->getType()->isPointerType()) {
1916 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1917 // If the pointer has a null base, this is an offsetof-like construct
1918 if (!Base)
1919 return CheckAddressConstantExpression(SubExpr);
1920 }
1921
Steve Naroff6594a702008-10-27 11:34:16 +00001922 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001923 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001924 }
1925 case Expr::ConditionalOperatorClass: {
1926 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001927
1928 // If GNU extensions are disabled, we require all operands to be arithmetic
1929 // constant expressions.
1930 if (getLangOptions().NoExtensions) {
1931 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1932 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1933 CheckArithmeticConstantExpression(Exp->getRHS());
1934 }
1935
1936 // Otherwise, we have to emulate some of the behavior of fold here.
1937 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1938 // because it can constant fold things away. To retain compatibility with
1939 // GCC code, we see if we can fold the condition to a constant (which we
1940 // should always be able to do in theory). If so, we only require the
1941 // specified arm of the conditional to be a constant. This is a horrible
1942 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001943 Expr::EvalResult EvalResult;
1944 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1945 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001946 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001947 // won't be able to either. Use it to emit the diagnostic though.
1948 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001949 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001950 return Res;
1951 }
1952
1953 // Verify that the side following the condition is also a constant.
1954 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001955 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001956 std::swap(TrueSide, FalseSide);
1957
1958 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001959 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001960
1961 // Okay, the evaluated side evaluates to a constant, so we accept this.
1962 // Check to see if the other side is obviously not a constant. If so,
1963 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001964 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001965 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001966 diag::ext_typecheck_expression_not_constant_but_accepted)
1967 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001968 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001969 }
1970 }
1971}
1972
1973bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001974 Expr::EvalResult Result;
1975
Nuno Lopes9a979c32008-07-07 16:46:50 +00001976 Init = Init->IgnoreParens();
1977
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001978 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1979 return false;
1980
Eli Friedmanc594b322008-05-20 13:48:25 +00001981 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1982 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1983 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1984
Nuno Lopes9a979c32008-07-07 16:46:50 +00001985 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1986 return CheckForConstantInitializer(e->getInitializer(), DclT);
1987
Eli Friedmanc594b322008-05-20 13:48:25 +00001988 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1989 unsigned numInits = Exp->getNumInits();
1990 for (unsigned i = 0; i < numInits; i++) {
1991 // FIXME: Need to get the type of the declaration for C++,
1992 // because it could be a reference?
1993 if (CheckForConstantInitializer(Exp->getInit(i),
1994 Exp->getInit(i)->getType()))
1995 return true;
1996 }
1997 return false;
1998 }
1999
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002000 // FIXME: We can probably remove some of this code below, now that
2001 // Expr::Evaluate is doing the heavy lifting for scalars.
2002
Eli Friedmanc594b322008-05-20 13:48:25 +00002003 if (Init->isNullPointerConstant(Context))
2004 return false;
2005 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002006 QualType InitTy = Context.getCanonicalType(Init->getType())
2007 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002008 if (InitTy == Context.BoolTy) {
2009 // Special handling for pointers implicitly cast to bool;
2010 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2011 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2012 Expr* SubE = ICE->getSubExpr();
2013 if (SubE->getType()->isPointerType() ||
2014 SubE->getType()->isArrayType() ||
2015 SubE->getType()->isFunctionType()) {
2016 return CheckAddressConstantExpression(Init);
2017 }
2018 }
2019 } else if (InitTy->isIntegralType()) {
2020 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002021 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002022 SubE = CE->getSubExpr();
2023 // Special check for pointer cast to int; we allow as an extension
2024 // an address constant cast to an integer if the integer
2025 // is of an appropriate width (this sort of code is apparently used
2026 // in some places).
2027 // FIXME: Add pedwarn?
2028 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2029 if (SubE && (SubE->getType()->isPointerType() ||
2030 SubE->getType()->isArrayType() ||
2031 SubE->getType()->isFunctionType())) {
2032 unsigned IntWidth = Context.getTypeSize(Init->getType());
2033 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2034 if (IntWidth >= PointerWidth)
2035 return CheckAddressConstantExpression(Init);
2036 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002037 }
2038
2039 return CheckArithmeticConstantExpression(Init);
2040 }
2041
2042 if (Init->getType()->isPointerType())
2043 return CheckAddressConstantExpression(Init);
2044
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002045 // An array type at the top level that isn't an init-list must
2046 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002047 if (Init->getType()->isArrayType())
2048 return false;
2049
Nuno Lopes73419bf2008-09-01 18:42:41 +00002050 if (Init->getType()->isFunctionType())
2051 return false;
2052
Steve Naroff8af6a452008-10-02 17:12:56 +00002053 // Allow block exprs at top level.
2054 if (Init->getType()->isBlockPointerType())
2055 return false;
2056
Steve Naroff6594a702008-10-27 11:34:16 +00002057 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002058 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002059}
2060
Sebastian Redl798d1192008-12-13 16:23:55 +00002061void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002062 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002063 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002064 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002065
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002066 // If there is no declaration, there was an error parsing it. Just ignore
2067 // the initializer.
2068 if (RealDecl == 0) {
2069 delete Init;
2070 return;
2071 }
Steve Naroffbb204692007-09-12 14:07:44 +00002072
Steve Naroff410e3e22007-09-12 20:13:48 +00002073 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2074 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002075 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2076 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002077 RealDecl->setInvalidDecl();
2078 return;
2079 }
Steve Naroffbb204692007-09-12 14:07:44 +00002080 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002081 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002082 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002083 if (VDecl->isBlockVarDecl()) {
2084 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002085 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002086 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002087 VDecl->setInvalidDecl();
2088 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002089 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002090 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002091 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002092
2093 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2094 if (!getLangOptions().CPlusPlus) {
2095 if (SC == VarDecl::Static) // C99 6.7.8p4.
2096 CheckForConstantInitializer(Init, DclT);
2097 }
Steve Naroffbb204692007-09-12 14:07:44 +00002098 }
Steve Naroff248a7532008-04-15 22:42:06 +00002099 } else if (VDecl->isFileVarDecl()) {
2100 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002101 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002102 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002103 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002104 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002105 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002106
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002107 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2108 if (!getLangOptions().CPlusPlus) {
2109 // C99 6.7.8p4. All file scoped initializers need to be constant.
2110 CheckForConstantInitializer(Init, DclT);
2111 }
Steve Naroffbb204692007-09-12 14:07:44 +00002112 }
2113 // If the type changed, it means we had an incomplete type that was
2114 // completed by the initializer. For example:
2115 // int ary[] = { 1, 3, 5 };
2116 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002117 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002118 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002119 Init->setType(DclT);
2120 }
Steve Naroffbb204692007-09-12 14:07:44 +00002121
2122 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002123 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002124 return;
2125}
2126
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002127void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2128 Decl *RealDecl = static_cast<Decl *>(dcl);
2129
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002130 // If there is no declaration, there was an error parsing it. Just ignore it.
2131 if (RealDecl == 0)
2132 return;
2133
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002134 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2135 QualType Type = Var->getType();
2136 // C++ [dcl.init.ref]p3:
2137 // The initializer can be omitted for a reference only in a
2138 // parameter declaration (8.3.5), in the declaration of a
2139 // function return type, in the declaration of a class member
2140 // within its class declaration (9.2), and where the extern
2141 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002142 if (Type->isReferenceType() &&
2143 Var->getStorageClass() != VarDecl::Extern &&
2144 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002145 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002146 << Var->getDeclName()
2147 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002148 Var->setInvalidDecl();
2149 return;
2150 }
2151
2152 // C++ [dcl.init]p9:
2153 //
2154 // If no initializer is specified for an object, and the object
2155 // is of (possibly cv-qualified) non-POD class type (or array
2156 // thereof), the object shall be default-initialized; if the
2157 // object is of const-qualified type, the underlying class type
2158 // shall have a user-declared default constructor.
2159 if (getLangOptions().CPlusPlus) {
2160 QualType InitType = Type;
2161 if (const ArrayType *Array = Context.getAsArrayType(Type))
2162 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002163 if (Var->getStorageClass() != VarDecl::Extern &&
2164 Var->getStorageClass() != VarDecl::PrivateExtern &&
2165 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002166 const CXXConstructorDecl *Constructor
2167 = PerformInitializationByConstructor(InitType, 0, 0,
2168 Var->getLocation(),
2169 SourceRange(Var->getLocation(),
2170 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002171 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002172 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002173 if (!Constructor)
2174 Var->setInvalidDecl();
2175 }
2176 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002177
Douglas Gregor818ce482008-10-29 13:50:18 +00002178#if 0
2179 // FIXME: Temporarily disabled because we are not properly parsing
2180 // linkage specifications on declarations, e.g.,
2181 //
2182 // extern "C" const CGPoint CGPointerZero;
2183 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002184 // C++ [dcl.init]p9:
2185 //
2186 // If no initializer is specified for an object, and the
2187 // object is of (possibly cv-qualified) non-POD class type (or
2188 // array thereof), the object shall be default-initialized; if
2189 // the object is of const-qualified type, the underlying class
2190 // type shall have a user-declared default
2191 // constructor. Otherwise, if no initializer is specified for
2192 // an object, the object and its subobjects, if any, have an
2193 // indeterminate initial value; if the object or any of its
2194 // subobjects are of const-qualified type, the program is
2195 // ill-formed.
2196 //
2197 // This isn't technically an error in C, so we don't diagnose it.
2198 //
2199 // FIXME: Actually perform the POD/user-defined default
2200 // constructor check.
2201 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002202 Context.getCanonicalType(Type).isConstQualified() &&
2203 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002204 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2205 << Var->getName()
2206 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002207#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002208 }
2209}
2210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211/// The declarators are chained together backwards, reverse the list.
2212Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2213 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002214 Decl *GroupDecl = static_cast<Decl*>(group);
2215 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002216 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002217
2218 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2219 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002220 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002221 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002222 else { // reverse the list.
2223 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002224 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002225 Group->setNextDeclarator(NewGroup);
2226 NewGroup = Group;
2227 Group = Next;
2228 }
2229 }
2230 // Perform semantic analysis that depends on having fully processed both
2231 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002232 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002233 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2234 if (!IDecl)
2235 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002236 QualType T = IDecl->getType();
2237
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002238 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002239 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002240
2241 // FIXME: This won't give the correct result for
2242 // int a[10][n];
2243 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002244 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002245 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2246 SizeRange;
2247
Eli Friedmanc5773c42008-02-15 18:16:39 +00002248 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002249 } else {
2250 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2251 // static storage duration, it shall not have a variable length array.
2252 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002253 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2254 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002255 IDecl->setInvalidDecl();
2256 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002257 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2258 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002259 IDecl->setInvalidDecl();
2260 }
2261 }
2262 } else if (T->isVariablyModifiedType()) {
2263 if (IDecl->isFileVarDecl()) {
2264 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2265 IDecl->setInvalidDecl();
2266 } else {
2267 if (IDecl->getStorageClass() == VarDecl::Extern) {
2268 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2269 IDecl->setInvalidDecl();
2270 }
Steve Naroffbb204692007-09-12 14:07:44 +00002271 }
2272 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002273
Steve Naroffbb204692007-09-12 14:07:44 +00002274 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2275 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002276 if (IDecl->isBlockVarDecl() &&
2277 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002278 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002279 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002280 IDecl->setInvalidDecl();
2281 }
2282 }
2283 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2284 // object that has file scope without an initializer, and without a
2285 // storage-class specifier or with the storage-class specifier "static",
2286 // constitutes a tentative definition. Note: A tentative definition with
2287 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002288 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002289 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002290 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2291 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002292 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002293 // C99 6.9.2p3: If the declaration of an identifier for an object is
2294 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2295 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002296 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002297 IDecl->setInvalidDecl();
2298 }
2299 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002300 if (IDecl->isFileVarDecl())
2301 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002302 }
2303 return NewGroup;
2304}
Steve Naroffe1223f72007-08-28 03:03:08 +00002305
Chris Lattner04421082008-04-08 04:40:51 +00002306/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2307/// to introduce parameters into function prototype scope.
2308Sema::DeclTy *
2309Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002310 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002311
Chris Lattner04421082008-04-08 04:40:51 +00002312 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002313 VarDecl::StorageClass StorageClass = VarDecl::None;
2314 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2315 StorageClass = VarDecl::Register;
2316 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002317 Diag(DS.getStorageClassSpecLoc(),
2318 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002319 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002320 }
2321 if (DS.isThreadSpecified()) {
2322 Diag(DS.getThreadSpecLoc(),
2323 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002324 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002325 }
2326
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002327 // Check that there are no default arguments inside the type of this
2328 // parameter (C++ only).
2329 if (getLangOptions().CPlusPlus)
2330 CheckExtraCXXDefaultArguments(D);
2331
Chris Lattner04421082008-04-08 04:40:51 +00002332 // In this context, we *do not* check D.getInvalidType(). If the declarator
2333 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2334 // though it will not reflect the user specified type.
2335 QualType parmDeclType = GetTypeForDeclarator(D, S);
2336
2337 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2338
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2340 // Can this happen for params? We already checked that they don't conflict
2341 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002342 IdentifierInfo *II = D.getIdentifier();
2343 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002344 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002345 // Maybe we will complain about the shadowed template parameter.
2346 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2347 // Just pretend that we didn't see the previous declaration.
2348 PrevDecl = 0;
2349 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002350 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002351
2352 // Recover by removing the name
2353 II = 0;
2354 D.SetIdentifier(0, D.getIdentifierLoc());
2355 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002357
2358 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2359 // Doing the promotion here has a win and a loss. The win is the type for
2360 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2361 // code generator). The loss is the orginal type isn't preserved. For example:
2362 //
2363 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2364 // int blockvardecl[5];
2365 // sizeof(parmvardecl); // size == 4
2366 // sizeof(blockvardecl); // size == 20
2367 // }
2368 //
2369 // For expressions, all implicit conversions are captured using the
2370 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2371 //
2372 // FIXME: If a source translation tool needs to see the original type, then
2373 // we need to consider storing both types (in ParmVarDecl)...
2374 //
Chris Lattnere6327742008-04-02 05:18:44 +00002375 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002376 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002377 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002378 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002379 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002380
Chris Lattner04421082008-04-08 04:40:51 +00002381 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2382 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002383 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002384 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002385
Chris Lattner04421082008-04-08 04:40:51 +00002386 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002387 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002388
Douglas Gregor584049d2008-12-15 23:53:10 +00002389 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2390 if (D.getCXXScopeSpec().isSet()) {
2391 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2392 << D.getCXXScopeSpec().getRange();
2393 New->setInvalidDecl();
2394 }
2395
Douglas Gregor44b43212008-12-11 16:49:14 +00002396 // Add the parameter declaration into this scope.
2397 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002398 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002399 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002400
Chris Lattner3ff30c82008-06-29 00:02:00 +00002401 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002403
Reid Spencer5f016e22007-07-11 17:01:13 +00002404}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002405
Chris Lattnerb652cea2007-10-09 17:14:05 +00002406Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002407 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2409 "Not a function declarator!");
2410 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002411
Reid Spencer5f016e22007-07-11 17:01:13 +00002412 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2413 // for a K&R function.
2414 if (!FTI.hasPrototype) {
2415 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002416 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002417 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2418 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002419 // Implicitly declare the argument as type 'int' for lack of a better
2420 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002421 DeclSpec DS;
2422 const char* PrevSpec; // unused
2423 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2424 PrevSpec);
2425 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2426 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2427 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 }
2429 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002431 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002432 }
2433
Douglas Gregor584049d2008-12-15 23:53:10 +00002434 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002435
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002436 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002437 ActOnDeclarator(ParentScope, D, 0,
2438 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002439}
2440
2441Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2442 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002443 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002444
2445 // See if this is a redefinition.
2446 const FunctionDecl *Definition;
2447 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002448 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002449 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002450 }
2451
Douglas Gregor44b43212008-12-11 16:49:14 +00002452 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002453
Chris Lattner04421082008-04-08 04:40:51 +00002454 // Check the validity of our function parameters
2455 CheckParmsForFunctionDef(FD);
2456
2457 // Introduce our parameters into the function scope
2458 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2459 ParmVarDecl *Param = FD->getParamDecl(p);
2460 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002461 if (Param->getIdentifier())
2462 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 }
Chris Lattner04421082008-04-08 04:40:51 +00002464
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002465 // Checking attributes of current function definition
2466 // dllimport attribute.
2467 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2468 // dllimport attribute cannot be applied to definition.
2469 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2470 Diag(FD->getLocation(),
2471 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2472 << "dllimport";
2473 FD->setInvalidDecl();
2474 return FD;
2475 } else {
2476 // If a symbol previously declared dllimport is later defined, the
2477 // attribute is ignored in subsequent references, and a warning is
2478 // emitted.
2479 Diag(FD->getLocation(),
2480 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2481 << FD->getNameAsCString() << "dllimport";
2482 }
2483 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 return FD;
2485}
2486
Sebastian Redl798d1192008-12-13 16:23:55 +00002487Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002488 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002489 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002490 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002491 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002492 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002493 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002494 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002495 } else
2496 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002497 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 // Verify and clean out per-function state.
2499
2500 // Check goto/label use.
2501 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2502 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2503 // Verify that we have no forward references left. If so, there was a goto
2504 // or address of a label taken, but no definition of it. Label fwd
2505 // definitions are indicated with a null substmt.
2506 if (I->second->getSubStmt() == 0) {
2507 LabelStmt *L = I->second;
2508 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002509 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002510
2511 // At this point, we have gotos that use the bogus label. Stitch it into
2512 // the function body so that they aren't leaked and that the AST is well
2513 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002514 if (Body) {
2515 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002516 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002517 } else {
2518 // The whole function wasn't parsed correctly, just delete this.
2519 delete L;
2520 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002521 }
2522 }
2523 LabelMap.clear();
2524
Steve Naroffd6d054d2007-11-11 23:20:51 +00002525 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002526}
2527
Reid Spencer5f016e22007-07-11 17:01:13 +00002528/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2529/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002530ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2531 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002532 // Extension in C99. Legal in C90, but warn about it.
2533 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002534 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002535 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002536 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002537
2538 // FIXME: handle stuff like:
2539 // void foo() { extern float X(); }
2540 // void bar() { X(); } <-- implicit decl for X in another scope.
2541
2542 // Set a Declarator for the implicit definition: int foo();
2543 const char *Dummy;
2544 DeclSpec DS;
2545 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2546 Error = Error; // Silence warning.
2547 assert(!Error && "Error setting up implicit decl!");
2548 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002549 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002550 D.SetIdentifier(&II, Loc);
2551
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002552 // Insert this function into translation-unit scope.
2553
2554 DeclContext *PrevDC = CurContext;
2555 CurContext = Context.getTranslationUnitDecl();
2556
Steve Naroffe2ef8152008-04-04 14:32:09 +00002557 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002558 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002559 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002560
2561 CurContext = PrevDC;
2562
Steve Naroffe2ef8152008-04-04 14:32:09 +00002563 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002564}
2565
2566
Chris Lattner41af0932007-11-14 06:34:38 +00002567TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002568 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002570 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002571
2572 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002573 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2574 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002575 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002576 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002577 if (D.getInvalidType())
2578 NewTD->setInvalidDecl();
2579 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002580}
2581
Steve Naroff08d92e42007-09-15 18:49:24 +00002582/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002583/// former case, Name will be non-null. In the later case, Name will be null.
2584/// TagType indicates what kind of tag this is. TK indicates whether this is a
2585/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002586Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002587 SourceLocation KWLoc, const CXXScopeSpec &SS,
2588 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002589 AttributeList *Attr,
2590 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002591 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002592 assert((Name != 0 || TK == TK_Definition) &&
2593 "Nameless record must be a definition!");
2594
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002595 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 switch (TagType) {
2597 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002598 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2599 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2600 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2601 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002602 }
2603
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002604 DeclContext *DC = CurContext;
2605 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002606
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002607 if (Name && SS.isNotEmpty()) {
2608 // We have a nested-name tag ('struct foo::bar').
2609
2610 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002611 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002612 Name = 0;
2613 goto CreateNewDecl;
2614 }
2615
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002616 DC = static_cast<DeclContext*>(SS.getScopeRep());
2617 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002618 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2619
2620 // A tag 'foo::bar' must already exist.
2621 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002622 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002623 Name = 0;
2624 goto CreateNewDecl;
2625 }
2626 } else {
2627 // If this is a named struct, check to see if there was a previous forward
2628 // declaration or definition.
2629 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2630 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2631 }
2632
Douglas Gregorf57172b2008-12-08 18:40:42 +00002633 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002634 // Maybe we will complain about the shadowed template parameter.
2635 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2636 // Just pretend that we didn't see the previous declaration.
2637 PrevDecl = 0;
2638 }
2639
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002640 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002641 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2642 "unexpected Decl type");
2643 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002644 // If this is a use of a previous tag, or if the tag is already declared
2645 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002646 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002647 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002648 // Make sure that this wasn't declared as an enum and now used as a
2649 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002650 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002651 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002652 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002653 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002654 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002655 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002656 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002657 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002658
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002659 // FIXME: In the future, return a variant or some other clue
2660 // for the consumer of this Decl to know it doesn't own it.
2661 // For our current ASTs this shouldn't be a problem, but will
2662 // need to be changed with DeclGroups.
2663 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002664 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002665
2666 // Diagnose attempts to redefine a tag.
2667 if (TK == TK_Definition) {
2668 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2669 Diag(NameLoc, diag::err_redefinition) << Name;
2670 Diag(Def->getLocation(), diag::note_previous_definition);
2671 // If this is a redefinition, recover by making this struct be
2672 // anonymous, which will make any later references get the previous
2673 // definition.
2674 Name = 0;
2675 PrevDecl = 0;
2676 }
2677 // Okay, this is definition of a previously declared or referenced
2678 // tag PrevDecl. We're going to create a new Decl for it.
2679 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002680 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002681 // If we get here we have (another) forward declaration or we
2682 // have a definition. Just create a new decl.
2683 } else {
2684 // If we get here, this is a definition of a new tag type in a nested
2685 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2686 // new decl/type. We set PrevDecl to NULL so that the entities
2687 // have distinct types.
2688 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002690 // If we get here, we're going to create a new Decl. If PrevDecl
2691 // is non-NULL, it's a definition of the tag declared by
2692 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002693 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002694 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002695 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002696 // The tag name clashes with a namespace name, issue an error and
2697 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002698 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002699 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002700 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002701 PrevDecl = 0;
2702 } else {
2703 // The existing declaration isn't relevant to us; we're in a
2704 // new scope, so clear out the previous declaration.
2705 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002706 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002709
Chris Lattnercc98eac2008-12-17 07:13:27 +00002710CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002711
2712 // If there is an identifier, use the location of the identifier as the
2713 // location of the decl, otherwise use the location of the struct/union
2714 // keyword.
2715 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2716
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002717 // Otherwise, create a new declaration. If there is a previous
2718 // declaration of the same entity, the two will be linked via
2719 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002721 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2723 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002724 New = EnumDecl::Create(Context, DC, Loc, Name,
2725 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002726 // If this is an undefined enum, warn.
2727 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002728 } else {
2729 // struct/union/class
2730
Reid Spencer5f016e22007-07-11 17:01:13 +00002731 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2732 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002733 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002734 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002735 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2736 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002737 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002738 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2739 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002740 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002741
2742 if (Kind != TagDecl::TK_enum) {
2743 // Handle #pragma pack: if the #pragma pack stack has non-default
2744 // alignment, make up a packed attribute for this decl. These
2745 // attributes are checked when the ASTContext lays out the
2746 // structure.
2747 //
2748 // It is important for implementing the correct semantics that this
2749 // happen here (in act on tag decl). The #pragma pack stack is
2750 // maintained as a result of parser callbacks which can occur at
2751 // many points during the parsing of a struct declaration (because
2752 // the #pragma tokens are effectively skipped over during the
2753 // parsing of the struct).
2754 if (unsigned Alignment = PackContext.getAlignment())
2755 New->addAttr(new PackedAttr(Alignment * 8));
2756 }
2757
2758 if (Attr)
2759 ProcessDeclAttributeList(New, Attr);
2760
2761 // Set the lexical context. If the tag has a C++ scope specifier, the
2762 // lexical context will be different from the semantic context.
2763 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002764
2765 // If this has an identifier, add it to the scope stack.
2766 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002767 // The scope passed in may not be a decl scope. Zip up the scope tree until
2768 // we find one that is.
2769 while ((S->getFlags() & Scope::DeclScope) == 0)
2770 S = S->getParent();
2771
2772 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002773 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002775
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 return New;
2777}
2778
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002779
Chris Lattner1d353ba2008-11-12 21:17:48 +00002780/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2781/// types into constant array types in certain situations which would otherwise
2782/// be errors (for GCC compatibility).
2783static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2784 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002785 // This method tries to turn a variable array into a constant
2786 // array even when the size isn't an ICE. This is necessary
2787 // for compatibility with code that depends on gcc's buggy
2788 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002789 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2790 if (!VLATy) return QualType();
2791
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002792 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002793 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002794 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002795 return QualType();
2796
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002797 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2798 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002799 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2800 return Context.getConstantArrayType(VLATy->getElementType(),
2801 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002802 return QualType();
2803}
2804
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002805bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002806 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002807 // FIXME: 6.7.2.1p4 - verify the field type.
2808
2809 llvm::APSInt Value;
2810 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2811 return true;
2812
Chris Lattnercd087072008-12-12 04:56:04 +00002813 // Zero-width bitfield is ok for anonymous field.
2814 if (Value == 0 && FieldName)
2815 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2816
2817 if (Value.isNegative())
2818 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002819
2820 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2821 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002822 if (TypeSize && Value.getZExtValue() > TypeSize)
2823 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2824 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002825
2826 return false;
2827}
2828
Steve Naroff08d92e42007-09-15 18:49:24 +00002829/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002830/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002831Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002832 SourceLocation DeclStart,
2833 Declarator &D, ExprTy *BitfieldWidth) {
2834 IdentifierInfo *II = D.getIdentifier();
2835 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002837 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002838 if (II) Loc = D.getIdentifierLoc();
2839
2840 // FIXME: Unnamed fields can be handled in various different ways, for
2841 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002842
Reid Spencer5f016e22007-07-11 17:01:13 +00002843 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002844 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2845 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002846
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2848 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002849 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002850 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002851 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002852 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002853 T = FixedTy;
2854 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002855 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002856 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002857 InvalidDecl = true;
2858 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002860
2861 if (BitWidth) {
2862 if (VerifyBitField(Loc, II, T, BitWidth))
2863 InvalidDecl = true;
2864 } else {
2865 // Not a bitfield.
2866
2867 // validate II.
2868
2869 }
2870
Reid Spencer5f016e22007-07-11 17:01:13 +00002871 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002872 FieldDecl *NewFD;
2873
Douglas Gregor44b43212008-12-11 16:49:14 +00002874 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2875 // other way to determine the current RecordDecl.
2876 NewFD = FieldDecl::Create(Context, Record,
2877 Loc, II, T, BitWidth,
2878 D.getDeclSpec().getStorageClassSpec() ==
2879 DeclSpec::SCS_mutable,
2880 /*PrevDecl=*/0);
2881
Sebastian Redl64b45f72009-01-05 20:52:13 +00002882 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002883 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002884 if (!T->isPODType())
2885 cast<CXXRecordDecl>(Record)->setPOD(false);
2886 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002887
Chris Lattner3ff30c82008-06-29 00:02:00 +00002888 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002889
Steve Naroff5912a352007-08-28 20:14:24 +00002890 if (D.getInvalidType() || InvalidDecl)
2891 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002892
2893 if (II && getLangOptions().CPlusPlus)
2894 PushOnScopeChains(NewFD, S);
2895 else
2896 Record->addDecl(Context, NewFD);
2897
Steve Naroff5912a352007-08-28 20:14:24 +00002898 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002899}
2900
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002901/// TranslateIvarVisibility - Translate visibility from a token ID to an
2902/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002903static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002904TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002905 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002906 default: assert(0 && "Unknown visitibility kind");
2907 case tok::objc_private: return ObjCIvarDecl::Private;
2908 case tok::objc_public: return ObjCIvarDecl::Public;
2909 case tok::objc_protected: return ObjCIvarDecl::Protected;
2910 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002911 }
2912}
2913
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002914/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2915/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002916Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002917 SourceLocation DeclStart,
2918 Declarator &D, ExprTy *BitfieldWidth,
2919 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002920 IdentifierInfo *II = D.getIdentifier();
2921 Expr *BitWidth = (Expr*)BitfieldWidth;
2922 SourceLocation Loc = DeclStart;
2923 if (II) Loc = D.getIdentifierLoc();
2924
2925 // FIXME: Unnamed fields can be handled in various different ways, for
2926 // example, unnamed unions inject all members into the struct namespace!
2927
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002928 QualType T = GetTypeForDeclarator(D, S);
2929 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2930 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002931
2932 if (BitWidth) {
2933 // TODO: Validate.
2934 //printf("WARNING: BITFIELDS IGNORED!\n");
2935
2936 // 6.7.2.1p3
2937 // 6.7.2.1p4
2938
2939 } else {
2940 // Not a bitfield.
2941
2942 // validate II.
2943
2944 }
2945
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002946 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2947 // than a variably modified type.
2948 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002949 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002950 InvalidDecl = true;
2951 }
2952
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002953 // Get the visibility (access control) for this ivar.
2954 ObjCIvarDecl::AccessControl ac =
2955 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2956 : ObjCIvarDecl::None;
2957
2958 // Construct the decl.
2959 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002960 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002961
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002962 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002963 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002964
2965 if (D.getInvalidType() || InvalidDecl)
2966 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002967
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002968 return NewID;
2969}
2970
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002971void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002972 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002973 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002974 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002975 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002976 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2977 assert(EnclosingDecl && "missing record or interface decl");
2978 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2979
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002980 if (Record)
2981 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2982 // Diagnose code like:
2983 // struct S { struct S {} X; };
2984 // We discover this when we complete the outer S. Reject and ignore the
2985 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002986 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002987 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002988 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002989 Record->setInvalidDecl();
2990 return;
2991 }
2992
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 // Verify that all the fields are okay.
2994 unsigned NumNamedMembers = 0;
2995 llvm::SmallVector<FieldDecl*, 32> RecFields;
2996 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002997
Reid Spencer5f016e22007-07-11 17:01:13 +00002998 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002999
Steve Naroff74216642007-09-14 22:20:54 +00003000 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3001 assert(FD && "missing field decl");
3002
3003 // Remember all fields.
3004 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003005
3006 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003007 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00003008
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003010 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003011 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003012 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003013 FD->setInvalidDecl();
3014 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 continue;
3016 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3018 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003019 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003020 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003021 FD->setInvalidDecl();
3022 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003023 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003024 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003026 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003027 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003028 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003029 FD->setInvalidDecl();
3030 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003031 continue;
3032 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003033 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003034 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003035 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003036 FD->setInvalidDecl();
3037 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 continue;
3039 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003040 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003041 if (Record)
3042 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003043 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3045 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003046 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003047 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3048 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003049 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003050 Record->setHasFlexibleArrayMember(true);
3051 } else {
3052 // If this is a struct/class and this is not the last element, reject
3053 // it. Note that GCC supports variable sized arrays in the middle of
3054 // structures.
3055 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003056 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003057 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003058 FD->setInvalidDecl();
3059 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 continue;
3061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003062 // We support flexible arrays at the end of structs in other structs
3063 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003064 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003065 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003066 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003067 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 }
3069 }
3070 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003071 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003072 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003073 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003074 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003075 FD->setInvalidDecl();
3076 EnclosingDecl->setInvalidDecl();
3077 continue;
3078 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003079 // Keep track of the number of named members.
3080 if (IdentifierInfo *II = FD->getIdentifier()) {
3081 // Detect duplicate member names.
3082 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003083 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003084 // Find the previous decl.
3085 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003086 for (unsigned i = 0; ; ++i) {
3087 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003088 if (RecFields[i]->getIdentifier() == II) {
3089 PrevLoc = RecFields[i]->getLocation();
3090 break;
3091 }
3092 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003093 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003094 FD->setInvalidDecl();
3095 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 continue;
3097 }
3098 ++NumNamedMembers;
3099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003101
Reid Spencer5f016e22007-07-11 17:01:13 +00003102 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003103 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003104 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003105 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3106 // Sema::ActOnFinishCXXClassDef.
3107 if (!isa<CXXRecordDecl>(Record))
3108 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003109 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003110 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003111 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003112 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003113 // Must enforce the rule that ivars in the base classes may not be
3114 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003115 if (ID->getSuperClass()) {
3116 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3117 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3118 ObjCIvarDecl* Ivar = (*IVI);
3119 IdentifierInfo *II = Ivar->getIdentifier();
3120 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3121 if (prevIvar) {
3122 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3123 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003124 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003125 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003126 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003127 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003128 else if (ObjCImplementationDecl *IMPDecl =
3129 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003130 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3131 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003132 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003133 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003134 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003135
3136 if (Attr)
3137 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003138}
3139
Douglas Gregor074149e2009-01-05 19:45:36 +00003140void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
3141 EnumDecl *Enum = cast_or_null<EnumDecl>((Decl *)EnumD);
3142
3143 if (Enum) {
3144 // Enter the enumeration context.
3145 PushDeclContext(S, Enum);
3146 }
3147}
3148
Steve Naroff08d92e42007-09-15 18:49:24 +00003149Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 DeclTy *lastEnumConst,
3151 SourceLocation IdLoc, IdentifierInfo *Id,
3152 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003153 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003154 EnumConstantDecl *LastEnumConst =
3155 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3156 Expr *Val = static_cast<Expr*>(val);
3157
Chris Lattner31e05722007-08-26 06:24:45 +00003158 // The scope passed in may not be a decl scope. Zip up the scope tree until
3159 // we find one that is.
3160 while ((S->getFlags() & Scope::DeclScope) == 0)
3161 S = S->getParent();
3162
Reid Spencer5f016e22007-07-11 17:01:13 +00003163 // Verify that there isn't already something declared with this name in this
3164 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003165 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003166 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003167 // Maybe we will complain about the shadowed template parameter.
3168 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3169 // Just pretend that we didn't see the previous declaration.
3170 PrevDecl = 0;
3171 }
3172
3173 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003174 // When in C++, we may get a TagDecl with the same name; in this case the
3175 // enum constant will 'hide' the tag.
3176 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3177 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003178 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003180 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003181 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003182 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003183 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003184 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 return 0;
3186 }
3187 }
3188
3189 llvm::APSInt EnumVal(32);
3190 QualType EltTy;
3191 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003192 // Make sure to promote the operand type to int.
3193 UsualUnaryConversions(Val);
3194
Reid Spencer5f016e22007-07-11 17:01:13 +00003195 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3196 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003197 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003198 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003199 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003200 } else {
3201 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003202 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003203 }
3204
3205 if (!Val) {
3206 if (LastEnumConst) {
3207 // Assign the last value + 1.
3208 EnumVal = LastEnumConst->getInitVal();
3209 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003210
3211 // Check for overflow on increment.
3212 if (EnumVal < LastEnumConst->getInitVal())
3213 Diag(IdLoc, diag::warn_enum_value_overflow);
3214
Chris Lattnerb7416f92007-08-27 17:37:24 +00003215 EltTy = LastEnumConst->getType();
3216 } else {
3217 // First value, set to zero.
3218 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003219 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003220 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 }
3222
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003223 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003224 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3225 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003226 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003227
3228 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003229 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003230
3231 // Add this enumerator into the enum itself.
3232 // FIXME: This means that the enumerator is stored in two
3233 // DeclContexts. This is not a long-term solution.
3234 New->setLexicalDeclContext(TheEnumDecl);
3235 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003236 return New;
3237}
3238
Steve Naroff02408c62008-08-07 14:08:16 +00003239// FIXME: For consistency with ActOnFields(), we should have the parser
3240// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003241void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003242 DeclTy **Elements, unsigned NumElements) {
3243 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003244 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003245
Douglas Gregor074149e2009-01-05 19:45:36 +00003246 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3247 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3248 // Diagnose code like:
3249 // enum e0 {
3250 // E0 = sizeof(enum e0 { E1 })
3251 // };
3252 Diag(Def->getLocation(), diag::err_nested_redefinition)
3253 << Enum->getDeclName();
3254 Diag(Enum->getLocation(), diag::note_previous_definition);
3255 Enum->setInvalidDecl();
3256 PopDeclContext();
3257 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003258 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003259
Chris Lattnere37f0be2007-08-28 05:10:31 +00003260 // TODO: If the result value doesn't fit in an int, it must be a long or long
3261 // long value. ISO C does not support this, but GCC does as an extension,
3262 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003263 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003264
Chris Lattnerac609682007-08-28 06:15:15 +00003265 // Verify that all the values are okay, compute the size of the values, and
3266 // reverse the list.
3267 unsigned NumNegativeBits = 0;
3268 unsigned NumPositiveBits = 0;
3269
3270 // Keep track of whether all elements have type int.
3271 bool AllElementsInt = true;
3272
Reid Spencer5f016e22007-07-11 17:01:13 +00003273 EnumConstantDecl *EltList = 0;
3274 for (unsigned i = 0; i != NumElements; ++i) {
3275 EnumConstantDecl *ECD =
3276 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3277 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003278
3279 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003280 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003281 assert(InitVal.getBitWidth() >= IntWidth &&
3282 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003283 if (InitVal.getBitWidth() > IntWidth) {
3284 llvm::APSInt V(InitVal);
3285 V.trunc(IntWidth);
3286 V.extend(InitVal.getBitWidth());
3287 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003288 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3289 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003290 }
Chris Lattnerac609682007-08-28 06:15:15 +00003291
3292 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003293 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003294 NumPositiveBits = std::max(NumPositiveBits,
3295 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003296 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003297 NumNegativeBits = std::max(NumNegativeBits,
3298 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003299
Chris Lattnerac609682007-08-28 06:15:15 +00003300 // Keep track of whether every enum element has type int (very commmon).
3301 if (AllElementsInt)
3302 AllElementsInt = ECD->getType() == Context.IntTy;
3303
Reid Spencer5f016e22007-07-11 17:01:13 +00003304 ECD->setNextDeclarator(EltList);
3305 EltList = ECD;
3306 }
3307
Chris Lattnerac609682007-08-28 06:15:15 +00003308 // Figure out the type that should be used for this enum.
3309 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3310 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003311 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003312
3313 if (NumNegativeBits) {
3314 // If there is a negative value, figure out the smallest integer type (of
3315 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003316 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003317 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003318 BestWidth = IntWidth;
3319 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003320 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003321
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003322 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003323 BestType = Context.LongTy;
3324 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003325 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003326
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003327 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003328 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3329 BestType = Context.LongLongTy;
3330 }
3331 }
3332 } else {
3333 // If there is no negative value, figure out which of uint, ulong, ulonglong
3334 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003335 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003336 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003337 BestWidth = IntWidth;
3338 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003339 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003340 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003341 } else {
3342 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003343 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003344 "How could an initializer get larger than ULL?");
3345 BestType = Context.UnsignedLongLongTy;
3346 }
3347 }
3348
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003349 // Loop over all of the enumerator constants, changing their types to match
3350 // the type of the enum if needed.
3351 for (unsigned i = 0; i != NumElements; ++i) {
3352 EnumConstantDecl *ECD =
3353 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3354 if (!ECD) continue; // Already issued a diagnostic.
3355
3356 // Standard C says the enumerators have int type, but we allow, as an
3357 // extension, the enumerators to be larger than int size. If each
3358 // enumerator value fits in an int, type it as an int, otherwise type it the
3359 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3360 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003361 if (ECD->getType() == Context.IntTy) {
3362 // Make sure the init value is signed.
3363 llvm::APSInt IV = ECD->getInitVal();
3364 IV.setIsSigned(true);
3365 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003366
3367 if (getLangOptions().CPlusPlus)
3368 // C++ [dcl.enum]p4: Following the closing brace of an
3369 // enum-specifier, each enumerator has the type of its
3370 // enumeration.
3371 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003372 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003373 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003374
3375 // Determine whether the value fits into an int.
3376 llvm::APSInt InitVal = ECD->getInitVal();
3377 bool FitsInInt;
3378 if (InitVal.isUnsigned() || !InitVal.isNegative())
3379 FitsInInt = InitVal.getActiveBits() < IntWidth;
3380 else
3381 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3382
3383 // If it fits into an integer type, force it. Otherwise force it to match
3384 // the enum decl type.
3385 QualType NewTy;
3386 unsigned NewWidth;
3387 bool NewSign;
3388 if (FitsInInt) {
3389 NewTy = Context.IntTy;
3390 NewWidth = IntWidth;
3391 NewSign = true;
3392 } else if (ECD->getType() == BestType) {
3393 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003394 if (getLangOptions().CPlusPlus)
3395 // C++ [dcl.enum]p4: Following the closing brace of an
3396 // enum-specifier, each enumerator has the type of its
3397 // enumeration.
3398 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003399 continue;
3400 } else {
3401 NewTy = BestType;
3402 NewWidth = BestWidth;
3403 NewSign = BestType->isSignedIntegerType();
3404 }
3405
3406 // Adjust the APSInt value.
3407 InitVal.extOrTrunc(NewWidth);
3408 InitVal.setIsSigned(NewSign);
3409 ECD->setInitVal(InitVal);
3410
3411 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003412 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3413 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003414 if (getLangOptions().CPlusPlus)
3415 // C++ [dcl.enum]p4: Following the closing brace of an
3416 // enum-specifier, each enumerator has the type of its
3417 // enumeration.
3418 ECD->setType(EnumType);
3419 else
3420 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003421 }
Chris Lattnerac609682007-08-28 06:15:15 +00003422
Douglas Gregor44b43212008-12-11 16:49:14 +00003423 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003424 Consumer.HandleTagDeclDefinition(Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003425
3426 // Leave the context of the enumeration.
3427 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00003428}
3429
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003430Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003431 ExprArg expr) {
3432 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3433
Chris Lattner8e25d862008-03-16 00:16:02 +00003434 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003435}
3436
Douglas Gregorf44515a2008-12-16 22:23:02 +00003437
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003438void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3439 ExprTy *alignment, SourceLocation PragmaLoc,
3440 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3441 Expr *Alignment = static_cast<Expr *>(alignment);
3442
3443 // If specified then alignment must be a "small" power of two.
3444 unsigned AlignmentVal = 0;
3445 if (Alignment) {
3446 llvm::APSInt Val;
3447 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3448 !Val.isPowerOf2() ||
3449 Val.getZExtValue() > 16) {
3450 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3451 delete Alignment;
3452 return; // Ignore
3453 }
3454
3455 AlignmentVal = (unsigned) Val.getZExtValue();
3456 }
3457
3458 switch (Kind) {
3459 case Action::PPK_Default: // pack([n])
3460 PackContext.setAlignment(AlignmentVal);
3461 break;
3462
3463 case Action::PPK_Show: // pack(show)
3464 // Show the current alignment, making sure to show the right value
3465 // for the default.
3466 AlignmentVal = PackContext.getAlignment();
3467 // FIXME: This should come from the target.
3468 if (AlignmentVal == 0)
3469 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003470 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003471 break;
3472
3473 case Action::PPK_Push: // pack(push [, id] [, [n])
3474 PackContext.push(Name);
3475 // Set the new alignment if specified.
3476 if (Alignment)
3477 PackContext.setAlignment(AlignmentVal);
3478 break;
3479
3480 case Action::PPK_Pop: // pack(pop [, id] [, n])
3481 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3482 // "#pragma pack(pop, identifier, n) is undefined"
3483 if (Alignment && Name)
3484 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3485
3486 // Do the pop.
3487 if (!PackContext.pop(Name)) {
3488 // If a name was specified then failure indicates the name
3489 // wasn't found. Otherwise failure indicates the stack was
3490 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003491 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3492 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003493
3494 // FIXME: Warn about popping named records as MSVC does.
3495 } else {
3496 // Pop succeeded, set the new alignment if specified.
3497 if (Alignment)
3498 PackContext.setAlignment(AlignmentVal);
3499 }
3500 break;
3501
3502 default:
3503 assert(0 && "Invalid #pragma pack kind.");
3504 }
3505}
3506
3507bool PragmaPackStack::pop(IdentifierInfo *Name) {
3508 if (Stack.empty())
3509 return false;
3510
3511 // If name is empty just pop top.
3512 if (!Name) {
3513 Alignment = Stack.back().first;
3514 Stack.pop_back();
3515 return true;
3516 }
3517
3518 // Otherwise, find the named record.
3519 for (unsigned i = Stack.size(); i != 0; ) {
3520 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003521 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003522 // Found it, pop up to and including this record.
3523 Alignment = Stack[i].first;
3524 Stack.erase(Stack.begin() + i, Stack.end());
3525 return true;
3526 }
3527 }
3528
3529 return false;
3530}