blob: e1c9efc326e7d9a4035828408e28e824742bd1fa [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +000096 // Move up the scope chain until we find the nearest enclosing
97 // non-transparent context. The declaration will be introduced into this
98 // scope.
99 while (S->getEntity() &&
100 ((DeclContext *)S->getEntity())->isTransparentContext())
101 S = S->getParent();
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000105 // Add scoped declarations into their context, so that they can be
106 // found later. Declarations without a context won't be inserted
107 // into any context.
108 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
109 CurContext->addDecl(Context, SD);
110
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000111 // C++ [basic.scope]p4:
112 // -- exactly one declaration shall declare a class name or
113 // enumeration name that is not a typedef name and the other
114 // declarations shall all refer to the same object or
115 // enumerator, or all refer to functions and function templates;
116 // in this case the class name or enumeration name is hidden.
117 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000154 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000155 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000176}
177
Steve Naroffb216c882007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000187
Douglas Gregor44b43212008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000190
Douglas Gregor44b43212008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196}
197
Steve Naroffe8043c32008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000204
Steve Naroffb327ce02008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000206}
207
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000219template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000220static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221MaybeConstructOverloadSet(ASTContext &Context,
222 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000223 assert(I != IEnd && "Iterator range cannot be empty");
224 assert(!isa<OverloadedFunctionDecl>(*I) &&
225 "Cannot have an overloaded function");
226
227 if (isa<FunctionDecl>(*I)) {
228 // If we found a function, there might be more functions. If
229 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000230 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000231 OverloadedFunctionDecl *Ovl = 0;
232 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233 if (!Ovl) {
234 // FIXME: We leak this overload set. Eventually, we want to
235 // stop building the declarations for these overload sets, so
236 // there will be nothing to leak.
237 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000238 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000239 (*I)->getDeclName());
240 Ovl->addOverload(cast<FunctionDecl>(*I));
241 }
242 Ovl->addOverload(cast<FunctionDecl>(*Last));
243 }
244
245 // If we had more than one function, we built an overload
246 // set. Return it.
247 if (Ovl)
248 return Ovl;
249 }
250
251 return *I;
252}
253
Steve Naroffe8043c32008-04-01 23:04:06 +0000254/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000255/// namespace. NamespaceNameOnly - during lookup only namespace names
256/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
257/// 'When looking up a namespace-name in a using-directive or
258/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000260 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000261 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000262 bool LookInParent,
263 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000264 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000265 unsigned NS = NSI;
266 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
267 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000268
Douglas Gregore267ff32008-12-11 20:41:00 +0000269 if (LookupCtx == 0 &&
270 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
271 // Unqualified name lookup in C/Objective-C and name lookup for
272 // labels in C++ is purely lexical, so search in the
273 // declarations attached to the name.
274 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000275 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregore267ff32008-12-11 20:41:00 +0000276 IdentifierResolver::iterator I
277 = IdResolver.begin(Name, CurContext, LookInParent);
278
279 // Scan up the scope chain looking for a decl that matches this
280 // identifier that is in the appropriate namespace. This search
281 // should not take long, as shadowing of names is uncommon, and
282 // deep shadowing is extremely uncommon.
283 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000284 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000285 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000286 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000287 // Perform qualified name lookup into the LookupCtx.
288 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000289 DeclContext::lookup_const_iterator I, E;
290 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000291 if ((*I)->isInIdentifierNamespace(NS)) {
292 // Ignore non-namespace names if we're only looking for namespaces.
293 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
294
295 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000296 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000297 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000298 // Name lookup for ordinary names and tag names in C++ requires
299 // looking into scopes that aren't strictly lexical, and
300 // therefore we walk through the context as well as walking
301 // through the scopes.
302 IdentifierResolver::iterator
303 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
304 IEnd = IdResolver.end();
305 for (; S; S = S->getParent()) {
306 // Check whether the IdResolver has anything in this scope.
307 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000308 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000309 if ((*I)->isInIdentifierNamespace(NS)) {
310 // Ignore non-namespace names if we're only looking for namespaces.
311 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
312 continue;
313
314 // We found something. Look for anything else in our scope
315 // with this same name and in an acceptable identifier
316 // namespace, so that we can construct an overload set if we
317 // need to.
318 IdentifierResolver::iterator LastI = I;
319 for (++LastI; LastI != IEnd; ++LastI) {
320 if (!(*LastI)->isInIdentifierNamespace(NS) ||
321 !S->isDeclScope(*LastI))
322 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000323 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000324 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000325 }
326 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000327
328 // If there is an entity associated with this scope, it's a
329 // DeclContext. We might need to perform qualified lookup into
330 // it.
331 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
332 while (Ctx && Ctx->isFunctionOrMethod())
333 Ctx = Ctx->getParent();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000334 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000335 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000336 DeclContext::lookup_const_iterator I, E;
337 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000338 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000339 if ((*I)->isInIdentifierNamespace(NS)) {
340 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
341 continue;
342 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000343 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000344 }
345
346 Ctx = Ctx->getParent();
347 }
348
Douglas Gregor074149e2009-01-05 19:45:36 +0000349 if (!LookInParent && !Ctx->isTransparentContext())
Douglas Gregor44b43212008-12-11 16:49:14 +0000350 return 0;
351 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000352 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // If we didn't find a use of this identifier, and if the identifier
355 // corresponds to a compiler builtin, create the decl object for the builtin
356 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000357 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000358 IdentifierInfo *II = Name.getAsIdentifierInfo();
359 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000360 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000361 // If this is a builtin on this (or all) targets, create the decl.
362 if (unsigned BuiltinID = II->getBuiltinID())
363 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
364 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000365 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000366 // @interface and @compatibility_alias introduce typedef-like names.
367 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000368 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000369 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000370 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
371 if (IDI != ObjCInterfaceDecls.end())
372 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000373 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
374 if (I != ObjCAliasDecls.end())
375 return I->second->getClassInterface();
376 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 }
378 return 0;
379}
380
Chris Lattner95e2c712008-05-05 22:18:14 +0000381void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000382 if (!Context.getBuiltinVaListType().isNull())
383 return;
384
385 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000386 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000387 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000388 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
389}
390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
392/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000393ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
394 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 Builtin::ID BID = (Builtin::ID)bid;
396
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000397 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000398 InitBuiltinVaListType();
399
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000400 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000401 FunctionDecl *New = FunctionDecl::Create(Context,
402 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000403 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000404 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000405
Chris Lattner95e2c712008-05-05 22:18:14 +0000406 // Create Decl objects for each parameter, adding them to the
407 // FunctionDecl.
408 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
409 llvm::SmallVector<ParmVarDecl*, 16> Params;
410 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
411 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
412 FT->getArgType(i), VarDecl::None, 0,
413 0));
414 New->setParams(&Params[0], Params.size());
415 }
416
417
418
Chris Lattner7f925cc2008-04-11 07:00:53 +0000419 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000420 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 return New;
422}
423
Sebastian Redlc42e1182008-11-11 11:37:55 +0000424/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
425/// everything from the standard library is defined.
426NamespaceDecl *Sema::GetStdNamespace() {
427 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000428 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000429 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000430 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000431 0, Global, /*enableLazyBuiltinCreation=*/false);
432 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
433 }
434 return StdNamespace;
435}
436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
438/// and scope as a previous declaration 'Old'. Figure out how to resolve this
439/// situation, merging decls or emitting diagnostics as appropriate.
440///
Steve Naroffe8043c32008-04-01 23:04:06 +0000441TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000442 // Allow multiple definitions for ObjC built-in typedefs.
443 // FIXME: Verify the underlying types are equivalent!
444 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000445 const IdentifierInfo *TypeID = New->getIdentifier();
446 switch (TypeID->getLength()) {
447 default: break;
448 case 2:
449 if (!TypeID->isStr("id"))
450 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000451 Context.setObjCIdType(New);
452 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000453 case 5:
454 if (!TypeID->isStr("Class"))
455 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000456 Context.setObjCClassType(New);
457 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000458 case 3:
459 if (!TypeID->isStr("SEL"))
460 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000461 Context.setObjCSelType(New);
462 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000463 case 8:
464 if (!TypeID->isStr("Protocol"))
465 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000466 Context.setObjCProtoType(New->getUnderlyingType());
467 return New;
468 }
469 // Fall through - the typedef name was not a builtin type.
470 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // Verify the old decl was also a typedef.
472 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
473 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000474 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000475 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000476 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 return New;
478 }
479
Chris Lattner99cb9972008-07-25 18:44:27 +0000480 // If the typedef types are not identical, reject them in all languages and
481 // with any extensions enabled.
482 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
483 Context.getCanonicalType(Old->getUnderlyingType()) !=
484 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000485 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000486 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000487 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000488 return Old;
489 }
490
Eli Friedman54ecfce2008-06-11 06:20:39 +0000491 if (getLangOptions().Microsoft) return New;
492
Douglas Gregorbbe27432008-11-21 16:29:06 +0000493 // C++ [dcl.typedef]p2:
494 // In a given non-class scope, a typedef specifier can be used to
495 // redefine the name of any type declared in that scope to refer
496 // to the type to which it already refers.
497 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
498 return New;
499
500 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000501 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
502 // *either* declaration is in a system header. The code below implements
503 // this adhoc compatibility rule. FIXME: The following code will not
504 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000505 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
506 SourceManager &SrcMgr = Context.getSourceManager();
507 if (SrcMgr.isInSystemHeader(Old->getLocation()))
508 return New;
509 if (SrcMgr.isInSystemHeader(New->getLocation()))
510 return New;
511 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000512
Chris Lattner08631c52008-11-23 21:45:46 +0000513 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000514 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 return New;
516}
517
Chris Lattner6b6b5372008-06-26 18:38:35 +0000518/// DeclhasAttr - returns true if decl Declaration already has the target
519/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000520static bool DeclHasAttr(const Decl *decl, const Attr *target) {
521 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
522 if (attr->getKind() == target->getKind())
523 return true;
524
525 return false;
526}
527
528/// MergeAttributes - append attributes from the Old decl to the New one.
529static void MergeAttributes(Decl *New, Decl *Old) {
530 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
531
Chris Lattnerddee4232008-03-03 03:28:21 +0000532 while (attr) {
533 tmp = attr;
534 attr = attr->getNext();
535
536 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000537 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000538 New->addAttr(tmp);
539 } else {
540 tmp->setNext(0);
541 delete(tmp);
542 }
543 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000544
545 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000546}
547
Chris Lattner04421082008-04-08 04:40:51 +0000548/// MergeFunctionDecl - We just parsed a function 'New' from
549/// declarator D which has the same name and scope as a previous
550/// declaration 'Old'. Figure out how to resolve this situation,
551/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552/// Redeclaration will be set true if this New is a redeclaration OldD.
553///
554/// In C++, New and Old must be declarations that are not
555/// overloaded. Use IsOverload to determine whether New and Old are
556/// overloaded, and to select the Old declaration that New should be
557/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000558FunctionDecl *
559Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 assert(!isa<OverloadedFunctionDecl>(OldD) &&
561 "Cannot merge with an overloaded function declaration");
562
Douglas Gregorf0097952008-04-21 02:02:58 +0000563 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 // Verify the old decl was also a function.
565 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
566 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000567 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000568 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000569 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 return New;
571 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572
573 // Determine whether the previous declaration was a definition,
574 // implicit declaration, or a declaration.
575 diag::kind PrevDiag;
576 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000577 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000579 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000581 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000582
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000583 QualType OldQType = Context.getCanonicalType(Old->getType());
584 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000585
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 if (getLangOptions().CPlusPlus) {
587 // (C++98 13.1p2):
588 // Certain function declarations cannot be overloaded:
589 // -- Function declarations that differ only in the return type
590 // cannot be overloaded.
591 QualType OldReturnType
592 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
593 QualType NewReturnType
594 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
595 if (OldReturnType != NewReturnType) {
596 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
597 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000598 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000599 return New;
600 }
601
602 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
603 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
604 if (OldMethod && NewMethod) {
605 // -- Member function declarations with the same name and the
606 // same parameter types cannot be overloaded if any of them
607 // is a static member function declaration.
608 if (OldMethod->isStatic() || NewMethod->isStatic()) {
609 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
610 Diag(Old->getLocation(), PrevDiag);
611 return New;
612 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000613
614 // C++ [class.mem]p1:
615 // [...] A member shall not be declared twice in the
616 // member-specification, except that a nested class or member
617 // class template can be declared and then later defined.
618 if (OldMethod->getLexicalDeclContext() ==
619 NewMethod->getLexicalDeclContext()) {
620 unsigned NewDiag;
621 if (isa<CXXConstructorDecl>(OldMethod))
622 NewDiag = diag::err_constructor_redeclared;
623 else if (isa<CXXDestructorDecl>(NewMethod))
624 NewDiag = diag::err_destructor_redeclared;
625 else if (isa<CXXConversionDecl>(NewMethod))
626 NewDiag = diag::err_conv_function_redeclared;
627 else
628 NewDiag = diag::err_member_redeclared;
629
630 Diag(New->getLocation(), NewDiag);
631 Diag(Old->getLocation(), PrevDiag);
632 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000633 }
634
635 // (C++98 8.3.5p3):
636 // All declarations for a function shall agree exactly in both the
637 // return type and the parameter-type-list.
638 if (OldQType == NewQType) {
639 // We have a redeclaration.
640 MergeAttributes(New, Old);
641 Redeclaration = true;
642 return MergeCXXFunctionDecl(New, Old);
643 }
644
645 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000646 }
Chris Lattner04421082008-04-08 04:40:51 +0000647
648 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000649 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000650 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000651 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000652 MergeAttributes(New, Old);
653 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000654 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000655 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000656
Steve Naroff837618c2008-01-16 15:01:34 +0000657 // A function that has already been declared has been redeclared or defined
658 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000659
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
661 // TODO: This is totally simplistic. It should handle merging functions
662 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000663 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000664 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 return New;
666}
667
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000668/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000669static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000670 if (VD->isFileVarDecl())
671 return (!VD->getInit() &&
672 (VD->getStorageClass() == VarDecl::None ||
673 VD->getStorageClass() == VarDecl::Static));
674 return false;
675}
676
677/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
678/// when dealing with C "tentative" external object definitions (C99 6.9.2).
679void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
680 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000681 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000682
Douglas Gregore21b9942009-01-07 16:34:42 +0000683 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000684 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000685 for (IdentifierResolver::iterator
686 I = IdResolver.begin(VD->getIdentifier(),
687 VD->getDeclContext(), false/*LookInParentCtx*/),
688 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000689 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000690 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
691
Steve Narofff855e6f2008-08-10 15:20:13 +0000692 // Handle the following case:
693 // int a[10];
694 // int a[]; - the code below makes sure we set the correct type.
695 // int a[11]; - this is an error, size isn't 10.
696 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
697 OldDecl->getType()->isConstantArrayType())
698 VD->setType(OldDecl->getType());
699
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000700 // Check for "tentative" definitions. We can't accomplish this in
701 // MergeVarDecl since the initializer hasn't been attached.
702 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
703 continue;
704
705 // Handle __private_extern__ just like extern.
706 if (OldDecl->getStorageClass() != VarDecl::Extern &&
707 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
708 VD->getStorageClass() != VarDecl::Extern &&
709 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000710 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000711 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000712 }
713 }
714 }
715}
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717/// MergeVarDecl - We just parsed a variable 'New' which has the same name
718/// and scope as a previous declaration 'Old'. Figure out how to resolve this
719/// situation, merging decls or emitting diagnostics as appropriate.
720///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000721/// Tentative definition rules (C99 6.9.2p2) are checked by
722/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
723/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000724///
Steve Naroffe8043c32008-04-01 23:04:06 +0000725VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // Verify the old decl was also a variable.
727 VarDecl *Old = dyn_cast<VarDecl>(OldD);
728 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000729 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000730 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000731 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 return New;
733 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000734
735 MergeAttributes(New, Old);
736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000738 QualType OldCType = Context.getCanonicalType(Old->getType());
739 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000740 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000741 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000742 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 return New;
744 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000745 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
746 if (New->getStorageClass() == VarDecl::Static &&
747 (Old->getStorageClass() == VarDecl::None ||
748 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000749 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000750 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000751 return New;
752 }
753 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
754 if (New->getStorageClass() != VarDecl::Static &&
755 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000757 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000758 return New;
759 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000760 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
761 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000762 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000763 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
765 return New;
766}
767
Chris Lattner04421082008-04-08 04:40:51 +0000768/// CheckParmsForFunctionDef - Check that the parameters of the given
769/// function are appropriate for the definition of a function. This
770/// takes care of any checks that cannot be performed on the
771/// declaration itself, e.g., that the types of each of the function
772/// parameters are complete.
773bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
774 bool HasInvalidParm = false;
775 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
776 ParmVarDecl *Param = FD->getParamDecl(p);
777
778 // C99 6.7.5.3p4: the parameters in a parameter type list in a
779 // function declarator that is part of a function definition of
780 // that function shall not have incomplete type.
781 if (Param->getType()->isIncompleteType() &&
782 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000783 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000784 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000785 Param->setInvalidDecl();
786 HasInvalidParm = true;
787 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000788
789 // C99 6.9.1p5: If the declarator includes a parameter type list, the
790 // declaration of each parameter shall include an identifier.
791 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
792 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000793 }
794
795 return HasInvalidParm;
796}
797
Reid Spencer5f016e22007-07-11 17:01:13 +0000798/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
799/// no declarator (e.g. "struct foo;") is parsed.
800Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000801 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
802 if (!DS.isMissingDeclaratorOk()) {
803 // FIXME: This diagnostic is emitted even when various previous
804 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
805 // DeclSpec has no means of communicating this information, and the
806 // responsible parser functions are quite far apart.
807 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
808 << DS.getSourceRange();
809 return 0;
810 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000811
812 TagDecl *Tag
813 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
814 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
815 if (!Record->getDeclName() && Record->isDefinition() &&
816 !Record->isInvalidDecl())
817 return BuildAnonymousStructOrUnion(S, DS, Record);
818 }
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000819
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000820 return Tag;
821}
822
823/// InjectAnonymousStructOrUnionMembers - Inject the members of the
824/// anonymous struct or union AnonRecord into the owning context Owner
825/// and scope S. This routine will be invoked just after we realize
826/// that an unnamed union or struct is actually an anonymous union or
827/// struct, e.g.,
828///
829/// @code
830/// union {
831/// int i;
832/// float f;
833/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
834/// // f into the surrounding scope.x
835/// @endcode
836///
837/// This routine is recursive, injecting the names of nested anonymous
838/// structs/unions into the owning context and scope as well.
839bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
840 RecordDecl *AnonRecord) {
841 bool Invalid = false;
842 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
843 FEnd = AnonRecord->field_end();
844 F != FEnd; ++F) {
845 if ((*F)->getDeclName()) {
846 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
847 S, Owner, false, false, false);
848 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
849 // C++ [class.union]p2:
850 // The names of the members of an anonymous union shall be
851 // distinct from the names of any other entity in the
852 // scope in which the anonymous union is declared.
853 unsigned diagKind
854 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
855 : diag::err_anonymous_struct_member_redecl;
856 Diag((*F)->getLocation(), diagKind)
857 << (*F)->getDeclName();
858 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
859 Invalid = true;
860 } else {
861 // C++ [class.union]p2:
862 // For the purpose of name lookup, after the anonymous union
863 // definition, the members of the anonymous union are
864 // considered to have been defined in the scope in which the
865 // anonymous union is declared.
866 Owner->insert(Context, *F);
867 S->AddDecl(*F);
868 IdResolver.AddDecl(*F);
869 }
870 } else if (const RecordType *InnerRecordType
871 = (*F)->getType()->getAsRecordType()) {
872 RecordDecl *InnerRecord = InnerRecordType->getDecl();
873 if (InnerRecord->isAnonymousStructOrUnion())
874 Invalid = Invalid ||
875 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
876 }
877 }
878
879 return Invalid;
880}
881
882/// ActOnAnonymousStructOrUnion - Handle the declaration of an
883/// anonymous structure or union. Anonymous unions are a C++ feature
884/// (C++ [class.union]) and a GNU C extension; anonymous structures
885/// are a GNU C and GNU C++ extension.
886Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
887 RecordDecl *Record) {
888 DeclContext *Owner = Record->getDeclContext();
889
890 // Diagnose whether this anonymous struct/union is an extension.
891 if (Record->isUnion() && !getLangOptions().CPlusPlus)
892 Diag(Record->getLocation(), diag::ext_anonymous_union);
893 else if (!Record->isUnion())
894 Diag(Record->getLocation(), diag::ext_anonymous_struct);
895
896 // C and C++ require different kinds of checks for anonymous
897 // structs/unions.
898 bool Invalid = false;
899 if (getLangOptions().CPlusPlus) {
900 const char* PrevSpec = 0;
901 // C++ [class.union]p3:
902 // Anonymous unions declared in a named namespace or in the
903 // global namespace shall be declared static.
904 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 (isa<TranslationUnitDecl>(Owner) ||
906 (isa<NamespaceDecl>(Owner) &&
907 cast<NamespaceDecl>(Owner)->getDeclName()))) {
908 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
909 Invalid = true;
910
911 // Recover by adding 'static'.
912 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
913 }
914 // C++ [class.union]p3:
915 // A storage class is not allowed in a declaration of an
916 // anonymous union in a class scope.
917 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
918 isa<RecordDecl>(Owner)) {
919 Diag(DS.getStorageClassSpecLoc(),
920 diag::err_anonymous_union_with_storage_spec);
921 Invalid = true;
922
923 // Recover by removing the storage specifier.
924 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
925 PrevSpec);
926 }
927 } else {
928 // FIXME: Check GNU C semantics
929 }
930
931 if (!Record->isUnion() && !Owner->isRecord()) {
932 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
933 Invalid = true;
934 }
935
936 // Create a declaration for this anonymous struct/union.
937 ScopedDecl *Anon = 0;
938 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
939 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
940 /*IdentifierInfo=*/0,
941 Context.getTypeDeclType(Record),
942 /*BitWidth=*/0, /*Mutable=*/false,
943 /*PrevDecl=*/0);
944 } else {
945 VarDecl::StorageClass SC;
946 switch (DS.getStorageClassSpec()) {
947 default: assert(0 && "Unknown storage class!");
948 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
949 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
950 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
951 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
952 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
953 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
954 case DeclSpec::SCS_mutable:
955 // mutable can only appear on non-static class members, so it's always
956 // an error here
957 Diag(Record->getLocation(), diag::err_mutable_nonmember);
958 Invalid = true;
959 SC = VarDecl::None;
960 break;
961 }
962
963 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
964 /*IdentifierInfo=*/0,
965 Context.getTypeDeclType(Record),
966 SC, /*FIXME:LastDeclarator=*/0,
967 DS.getSourceRange().getBegin());
968 }
969
970 // Add the anonymous struct/union object to the current
971 // context. We'll be referencing this object when we refer to one of
972 // its members.
973 Owner->addDecl(Context, Anon);
974
975 // Inject the members of the anonymous struct/union into the owning
976 // context and into the identifier resolver chain for name lookup
977 // purposes.
978 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
979
980 // Mark this as an anonymous struct/union type. Note that we do not
981 // do this until after we have already checked and injected the
982 // members of this anonymous struct/union type, because otherwise
983 // the members could be injected twice: once by DeclContext when it
984 // builds its lookup table, and once by
985 // InjectAnonymousStructOrUnionMembers.
986 Record->setAnonymousStructOrUnion(true);
987
988 if (Invalid)
989 Anon->setInvalidDecl();
990
991 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000992}
993
Steve Naroffd0091aa2008-01-10 22:15:12 +0000994bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000995 // Get the type before calling CheckSingleAssignmentConstraints(), since
996 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000997 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000998
999 if (getLangOptions().CPlusPlus)
1000 return PerformCopyInitialization(Init, DeclType, "initializing");
1001
Chris Lattner5cf216b2008-01-04 18:04:52 +00001002 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1003 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1004 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001005}
1006
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001007bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001008 const ArrayType *AT = Context.getAsArrayType(DeclT);
1009
1010 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001011 // C99 6.7.8p14. We have an array of character type with unknown size
1012 // being initialized to a string literal.
1013 llvm::APSInt ConstVal(32);
1014 ConstVal = strLiteral->getByteLength() + 1;
1015 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001016 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001017 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001018 } else {
1019 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001020 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001021 // FIXME: Avoid truncation for 64-bit length strings.
1022 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001023 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001024 diag::warn_initializer_string_for_char_array_too_long)
1025 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001026 }
1027 // Set type from "char *" to "constant array of char".
1028 strLiteral->setType(DeclT);
1029 // For now, we always return false (meaning success).
1030 return false;
1031}
1032
1033StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001034 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001035 if (AT && AT->getElementType()->isCharType()) {
1036 return dyn_cast<StringLiteral>(Init);
1037 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001038 return 0;
1039}
1040
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001041bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1042 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001043 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001044 if (DeclType->isDependentType() || Init->isTypeDependent())
1045 return false;
1046
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001047 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001048 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001049 // (8.3.2), shall be initialized by an object, or function, of
1050 // type T or by an object that can be converted into a T.
1051 if (DeclType->isReferenceType())
1052 return CheckReferenceInit(Init, DeclType);
1053
Steve Naroffca107302008-01-21 23:53:58 +00001054 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1055 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001056 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001057 return Diag(InitLoc, diag::err_variable_object_no_init)
1058 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001059
Steve Naroff2fdc3742007-12-10 22:44:33 +00001060 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1061 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001062 // FIXME: Handle wide strings
1063 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1064 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001065
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001066 // C++ [dcl.init]p14:
1067 // -- If the destination type is a (possibly cv-qualified) class
1068 // type:
1069 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1070 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1071 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1072
1073 // -- If the initialization is direct-initialization, or if it is
1074 // copy-initialization where the cv-unqualified version of the
1075 // source type is the same class as, or a derived class of, the
1076 // class of the destination, constructors are considered.
1077 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1078 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1079 CXXConstructorDecl *Constructor
1080 = PerformInitializationByConstructor(DeclType, &Init, 1,
1081 InitLoc, Init->getSourceRange(),
1082 InitEntity, IK_Copy);
1083 return Constructor == 0;
1084 }
1085
1086 // -- Otherwise (i.e., for the remaining copy-initialization
1087 // cases), user-defined conversion sequences that can
1088 // convert from the source type to the destination type or
1089 // (when a conversion function is used) to a derived class
1090 // thereof are enumerated as described in 13.3.1.4, and the
1091 // best one is chosen through overload resolution
1092 // (13.3). If the conversion cannot be done or is
1093 // ambiguous, the initialization is ill-formed. The
1094 // function selected is called with the initializer
1095 // expression as its argument; if the function is a
1096 // constructor, the call initializes a temporary of the
1097 // destination type.
1098 // FIXME: We're pretending to do copy elision here; return to
1099 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001100 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001101 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001102
Douglas Gregor61366e92008-12-24 00:01:03 +00001103 if (InitEntity)
1104 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1105 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1106 << Init->getType() << Init->getSourceRange();
1107 else
1108 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1109 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1110 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001111 }
1112
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001113 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001114 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001115 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1116 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001117
Steve Naroffd0091aa2008-01-10 22:15:12 +00001118 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001119 } else if (getLangOptions().CPlusPlus) {
1120 // C++ [dcl.init]p14:
1121 // [...] If the class is an aggregate (8.5.1), and the initializer
1122 // is a brace-enclosed list, see 8.5.1.
1123 //
1124 // Note: 8.5.1 is handled below; here, we diagnose the case where
1125 // we have an initializer list and a destination type that is not
1126 // an aggregate.
1127 // FIXME: In C++0x, this is yet another form of initialization.
1128 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1129 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1130 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001131 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001132 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001133 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001134 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001135
Steve Naroff0cca7492008-05-01 22:18:59 +00001136 InitListChecker CheckInitList(this, InitList, DeclType);
1137 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001138}
1139
Douglas Gregor10bd3682008-11-17 22:58:34 +00001140/// GetNameForDeclarator - Determine the full declaration name for the
1141/// given Declarator.
1142DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1143 switch (D.getKind()) {
1144 case Declarator::DK_Abstract:
1145 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1146 return DeclarationName();
1147
1148 case Declarator::DK_Normal:
1149 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1150 return DeclarationName(D.getIdentifier());
1151
1152 case Declarator::DK_Constructor: {
1153 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1154 Ty = Context.getCanonicalType(Ty);
1155 return Context.DeclarationNames.getCXXConstructorName(Ty);
1156 }
1157
1158 case Declarator::DK_Destructor: {
1159 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1160 Ty = Context.getCanonicalType(Ty);
1161 return Context.DeclarationNames.getCXXDestructorName(Ty);
1162 }
1163
1164 case Declarator::DK_Conversion: {
1165 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1166 Ty = Context.getCanonicalType(Ty);
1167 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1168 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001169
1170 case Declarator::DK_Operator:
1171 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1172 return Context.DeclarationNames.getCXXOperatorName(
1173 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001174 }
1175
1176 assert(false && "Unknown name kind");
1177 return DeclarationName();
1178}
1179
Douglas Gregor584049d2008-12-15 23:53:10 +00001180/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1181/// functions Declaration and Definition are "nearly" matching. This
1182/// heuristic is used to improve diagnostics in the case where an
1183/// out-of-line member function definition doesn't match any
1184/// declaration within the class.
1185static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1186 FunctionDecl *Declaration,
1187 FunctionDecl *Definition) {
1188 if (Declaration->param_size() != Definition->param_size())
1189 return false;
1190 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1191 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1192 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1193
1194 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1195 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1196 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1197 return false;
1198 }
1199
1200 return true;
1201}
1202
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001203Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001204Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1205 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001206 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001207 DeclarationName Name = GetNameForDeclarator(D);
1208
Chris Lattnere80a59c2007-07-25 00:24:17 +00001209 // All of these full declarators require an identifier. If it doesn't have
1210 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001211 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001212 if (!D.getInvalidType()) // Reject this if we think it is valid.
1213 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001214 diag::err_declarator_need_ident)
1215 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001216 return 0;
1217 }
1218
Chris Lattner31e05722007-08-26 06:24:45 +00001219 // The scope passed in may not be a decl scope. Zip up the scope tree until
1220 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001221 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1222 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001223 S = S->getParent();
1224
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001225 DeclContext *DC;
1226 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001227 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001228 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001229
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001230 // See if this is a redefinition of a variable in the same scope.
1231 if (!D.getCXXScopeSpec().isSet()) {
1232 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001233 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001234 } else { // Something like "int foo::x;"
1235 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001236 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001237
1238 // C++ 7.3.1.2p2:
1239 // Members (including explicit specializations of templates) of a named
1240 // namespace can also be defined outside that namespace by explicit
1241 // qualification of the name being defined, provided that the entity being
1242 // defined was already declared in the namespace and the definition appears
1243 // after the point of declaration in a namespace that encloses the
1244 // declarations namespace.
1245 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001246 // Note that we only check the context at this point. We don't yet
1247 // have enough information to make sure that PrevDecl is actually
1248 // the declaration we want to match. For example, given:
1249 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001250 // class X {
1251 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001252 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001253 // };
1254 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001255 // void X::f(int) { } // ill-formed
1256 //
1257 // In this case, PrevDecl will point to the overload set
1258 // containing the two f's declared in X, but neither of them
1259 // matches.
1260 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001261 // The qualifying scope doesn't enclose the original declaration.
1262 // Emit diagnostic based on current scope.
1263 SourceLocation L = D.getIdentifierLoc();
1264 SourceRange R = D.getCXXScopeSpec().getRange();
1265 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001266 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001267 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001268 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001269 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001270 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001271 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001272 }
1273 }
1274
Douglas Gregorf57172b2008-12-08 18:40:42 +00001275 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001276 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001277 InvalidDecl = InvalidDecl
1278 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001279 // Just pretend that we didn't see the previous declaration.
1280 PrevDecl = 0;
1281 }
1282
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001283 // In C++, the previous declaration we find might be a tag type
1284 // (class or enum). In this case, the new declaration will hide the
1285 // tag type.
1286 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1287 PrevDecl = 0;
1288
Chris Lattner41af0932007-11-14 06:34:38 +00001289 QualType R = GetTypeForDeclarator(D, S);
1290 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1291
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001293 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1294 if (D.getCXXScopeSpec().isSet()) {
1295 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1296 << D.getCXXScopeSpec().getRange();
1297 InvalidDecl = true;
1298 // Pretend we didn't see the scope specifier.
1299 DC = 0;
1300 }
1301
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001302 // Check that there are no default arguments (C++ only).
1303 if (getLangOptions().CPlusPlus)
1304 CheckExtraCXXDefaultArguments(D);
1305
Chris Lattner41af0932007-11-14 06:34:38 +00001306 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 if (!NewTD) return 0;
1308
1309 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001310 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001311 // Merge the decl with the existing one if appropriate. If the decl is
1312 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001313 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1315 if (NewTD == 0) return 0;
1316 }
1317 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001318 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1320 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001321 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001322 if (NewTD->getUnderlyingType()->isVariableArrayType())
1323 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1324 else
1325 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1326
Steve Naroffd7444aa2007-08-31 17:20:07 +00001327 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 }
1329 }
Chris Lattner41af0932007-11-14 06:34:38 +00001330 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001331 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 switch (D.getDeclSpec().getStorageClassSpec()) {
1333 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001334 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001335 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001336 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001337 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001338 InvalidDecl = true;
1339 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1341 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1342 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001343 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001344 }
1345
Chris Lattnera98e58d2008-03-15 21:24:04 +00001346 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001347 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001348 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1349
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001350 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001351 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001352 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001353 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001354 "Constructors can only be declared in a member context");
1355
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001356 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001357
1358 // Create the new declaration
1359 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001360 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001361 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001362 isExplicit, isInline,
1363 /*isImplicitlyDeclared=*/false);
1364
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001365 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001366 NewFD->setInvalidDecl();
1367 } else if (D.getKind() == Declarator::DK_Destructor) {
1368 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001369 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001370 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001371
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001372 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001373 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001374 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001375 isInline,
1376 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001377
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001378 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001379 NewFD->setInvalidDecl();
1380 } else {
1381 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001382
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001383 // Create a FunctionDecl to satisfy the function definition parsing
1384 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001385 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001386 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001387 // FIXME: Move to DeclGroup...
1388 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001389 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001390 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001391 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001392 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001393 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001394 Diag(D.getIdentifierLoc(),
1395 diag::err_conv_function_not_member);
1396 return 0;
1397 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001398 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001399
Douglas Gregor70316a02008-12-26 15:00:45 +00001400 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001401 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001402 isInline, isExplicit);
1403
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001404 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001405 NewFD->setInvalidDecl();
1406 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001407 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001408 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001409 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001410 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001411 (SC == FunctionDecl::Static), isInline,
1412 LastDeclarator);
1413 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001414 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001415 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001416 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001417 // FIXME: Move to DeclGroup...
1418 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001419 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001420
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001421 // Set the lexical context. If the declarator has a C++
1422 // scope specifier, the lexical context will be different
1423 // from the semantic context.
1424 NewFD->setLexicalDeclContext(CurContext);
1425
Daniel Dunbara80f8742008-08-05 01:35:17 +00001426 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001427 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001428 // The parser guarantees this is a string.
1429 StringLiteral *SE = cast<StringLiteral>(E);
1430 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1431 SE->getByteLength())));
1432 }
1433
Chris Lattner04421082008-04-08 04:40:51 +00001434 // Copy the parameter declarations from the declarator D to
1435 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001436 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001437 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1438
1439 // Create Decl objects for each parameter, adding them to the
1440 // FunctionDecl.
1441 llvm::SmallVector<ParmVarDecl*, 16> Params;
1442
1443 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1444 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001445 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001446 // We let through "const void" here because Sema::GetTypeForDeclarator
1447 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001448 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1449 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001450 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1451 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001452 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1453
Chris Lattnerdef026a2008-04-10 02:26:16 +00001454 // In C++, the empty parameter-type-list must be spelled "void"; a
1455 // typedef of void is not permitted.
1456 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001457 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001458 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1459 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001460 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001461 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1462 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1463 }
1464
1465 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001466 } else if (R->getAsTypedefType()) {
1467 // When we're declaring a function with a typedef, as in the
1468 // following example, we'll need to synthesize (unnamed)
1469 // parameters for use in the declaration.
1470 //
1471 // @code
1472 // typedef void fn(int);
1473 // fn f;
1474 // @endcode
1475 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1476 if (!FT) {
1477 // This is a typedef of a function with no prototype, so we
1478 // don't need to do anything.
1479 } else if ((FT->getNumArgs() == 0) ||
1480 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1481 FT->getArgType(0)->isVoidType())) {
1482 // This is a zero-argument function. We don't need to do anything.
1483 } else {
1484 // Synthesize a parameter for each argument type.
1485 llvm::SmallVector<ParmVarDecl*, 16> Params;
1486 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1487 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001488 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001489 SourceLocation(), 0,
1490 *ArgType, VarDecl::None,
1491 0, 0));
1492 }
1493
1494 NewFD->setParams(&Params[0], Params.size());
1495 }
Chris Lattner04421082008-04-08 04:40:51 +00001496 }
1497
Douglas Gregor72b505b2008-12-16 21:30:33 +00001498 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1499 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001500 else if (isa<CXXDestructorDecl>(NewFD)) {
1501 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1502 Record->setUserDeclaredDestructor(true);
1503 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1504 // user-defined destructor.
1505 Record->setPOD(false);
1506 } else if (CXXConversionDecl *Conversion =
1507 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001508 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001509
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001510 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1511 if (NewFD->isOverloadedOperator() &&
1512 CheckOverloadedOperatorDeclaration(NewFD))
1513 NewFD->setInvalidDecl();
1514
Steve Naroffffce4d52008-01-09 23:34:55 +00001515 // Merge the decl with the existing one if appropriate. Since C functions
1516 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001517 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001518 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001519 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520
1521 // If C++, determine whether NewFD is an overload of PrevDecl or
1522 // a declaration that requires merging. If it's an overload,
1523 // there's no more work to do here; we'll just add the new
1524 // function to the scope.
1525 OverloadedFunctionDecl::function_iterator MatchedDecl;
1526 if (!getLangOptions().CPlusPlus ||
1527 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1528 Decl *OldDecl = PrevDecl;
1529
1530 // If PrevDecl was an overloaded function, extract the
1531 // FunctionDecl that matched.
1532 if (isa<OverloadedFunctionDecl>(PrevDecl))
1533 OldDecl = *MatchedDecl;
1534
1535 // NewFD and PrevDecl represent declarations that need to be
1536 // merged.
1537 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1538
1539 if (NewFD == 0) return 0;
1540 if (Redeclaration) {
1541 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1542
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001543 // An out-of-line member function declaration must also be a
1544 // definition (C++ [dcl.meaning]p1).
1545 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1546 !InvalidDecl) {
1547 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1548 << D.getCXXScopeSpec().getRange();
1549 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001550 }
1551 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001552 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001553
1554 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1555 // The user tried to provide an out-of-line definition for a
1556 // member function, but there was no such member function
1557 // declared (C++ [class.mfct]p2). For example:
1558 //
1559 // class X {
1560 // void f() const;
1561 // };
1562 //
1563 // void X::f() { } // ill-formed
1564 //
1565 // Complain about this problem, and attempt to suggest close
1566 // matches (e.g., those that differ only in cv-qualifiers and
1567 // whether the parameter types are references).
1568 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1569 << cast<CXXRecordDecl>(DC)->getDeclName()
1570 << D.getCXXScopeSpec().getRange();
1571 InvalidDecl = true;
1572
1573 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1574 if (!PrevDecl) {
1575 // Nothing to suggest.
1576 } else if (OverloadedFunctionDecl *Ovl
1577 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1578 for (OverloadedFunctionDecl::function_iterator
1579 Func = Ovl->function_begin(),
1580 FuncEnd = Ovl->function_end();
1581 Func != FuncEnd; ++Func) {
1582 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1583 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1584
1585 }
1586 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1587 // Suggest this no matter how mismatched it is; it's the only
1588 // thing we have.
1589 unsigned diag;
1590 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1591 diag = diag::note_member_def_close_match;
1592 else if (Method->getBody())
1593 diag = diag::note_previous_definition;
1594 else
1595 diag = diag::note_previous_declaration;
1596 Diag(Method->getLocation(), diag);
1597 }
1598
1599 PrevDecl = 0;
1600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001602 // Handle attributes. We need to have merged decls when handling attributes
1603 // (for example to check for conflicts, etc).
1604 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001606
Douglas Gregor584049d2008-12-15 23:53:10 +00001607 if (getLangOptions().CPlusPlus) {
1608 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001609 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001610
1611 // An out-of-line member function declaration must also be a
1612 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001613 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001614 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1615 << D.getCXXScopeSpec().getRange();
1616 InvalidDecl = true;
1617 }
1618 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001620 // Check that there are no default arguments (C++ only).
1621 if (getLangOptions().CPlusPlus)
1622 CheckExtraCXXDefaultArguments(D);
1623
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001624 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001625 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1626 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001627 InvalidDecl = true;
1628 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001629
1630 VarDecl *NewVD;
1631 VarDecl::StorageClass SC;
1632 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001633 default: assert(0 && "Unknown storage class!");
1634 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1635 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1636 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1637 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1638 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1639 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001640 case DeclSpec::SCS_mutable:
1641 // mutable can only appear on non-static class members, so it's always
1642 // an error here
1643 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1644 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001645 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001646 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001647 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001648
1649 IdentifierInfo *II = Name.getAsIdentifierInfo();
1650 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001651 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1652 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001653 return 0;
1654 }
1655
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001656 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001657 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001658 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001659 D.getIdentifierLoc(), II,
1660 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001661 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001662 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001663 if (S->getFnParent() == 0) {
1664 // C99 6.9p2: The storage-class specifiers auto and register shall not
1665 // appear in the declaration specifiers in an external declaration.
1666 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001667 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001668 InvalidDecl = true;
1669 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001670 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001671 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1672 II, R, SC, LastDeclarator,
1673 // FIXME: Move to DeclGroup...
1674 D.getDeclSpec().getSourceRange().getBegin());
1675 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001676 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001677 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001678 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001679
Daniel Dunbara735ad82008-08-06 00:03:29 +00001680 // Handle GNU asm-label extension (encoded as an attribute).
1681 if (Expr *E = (Expr*) D.getAsmLabel()) {
1682 // The parser guarantees this is a string.
1683 StringLiteral *SE = cast<StringLiteral>(E);
1684 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1685 SE->getByteLength())));
1686 }
1687
Nate Begemanc8e89a82008-03-14 18:07:10 +00001688 // Emit an error if an address space was applied to decl with local storage.
1689 // This includes arrays of objects with address space qualifiers, but not
1690 // automatic variables that point to other address spaces.
1691 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001692 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1693 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1694 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001695 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001696 // Merge the decl with the existing one if appropriate. If the decl is
1697 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001698 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001699 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1700 // The user tried to define a non-static data member
1701 // out-of-line (C++ [dcl.meaning]p1).
1702 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1703 << D.getCXXScopeSpec().getRange();
1704 NewVD->Destroy(Context);
1705 return 0;
1706 }
1707
Reid Spencer5f016e22007-07-11 17:01:13 +00001708 NewVD = MergeVarDecl(NewVD, PrevDecl);
1709 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001710
1711 if (D.getCXXScopeSpec().isSet()) {
1712 // No previous declaration in the qualifying scope.
1713 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1714 << Name << D.getCXXScopeSpec().getRange();
1715 InvalidDecl = true;
1716 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 New = NewVD;
1719 }
1720
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001721 // Set the lexical context. If the declarator has a C++ scope specifier, the
1722 // lexical context will be different from the semantic context.
1723 New->setLexicalDeclContext(CurContext);
1724
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001726 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001727 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001728 // If any semantic error occurred, mark the decl as invalid.
1729 if (D.getInvalidType() || InvalidDecl)
1730 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001731
1732 return New;
1733}
1734
Steve Naroff6594a702008-10-27 11:34:16 +00001735void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001736 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1737 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001738}
1739
Eli Friedmanc594b322008-05-20 13:48:25 +00001740bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1741 switch (Init->getStmtClass()) {
1742 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001743 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001744 return true;
1745 case Expr::ParenExprClass: {
1746 const ParenExpr* PE = cast<ParenExpr>(Init);
1747 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1748 }
1749 case Expr::CompoundLiteralExprClass:
1750 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001751 case Expr::DeclRefExprClass:
1752 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001753 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001754 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1755 if (VD->hasGlobalStorage())
1756 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001757 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001758 return true;
1759 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001760 if (isa<FunctionDecl>(D))
1761 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001762 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001763 return true;
1764 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001765 case Expr::MemberExprClass: {
1766 const MemberExpr *M = cast<MemberExpr>(Init);
1767 if (M->isArrow())
1768 return CheckAddressConstantExpression(M->getBase());
1769 return CheckAddressConstantExpressionLValue(M->getBase());
1770 }
1771 case Expr::ArraySubscriptExprClass: {
1772 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1773 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1774 return CheckAddressConstantExpression(ASE->getBase()) ||
1775 CheckArithmeticConstantExpression(ASE->getIdx());
1776 }
1777 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001778 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001779 return false;
1780 case Expr::UnaryOperatorClass: {
1781 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1782
1783 // C99 6.6p9
1784 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001785 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001786
Steve Naroff6594a702008-10-27 11:34:16 +00001787 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001788 return true;
1789 }
1790 }
1791}
1792
1793bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1794 switch (Init->getStmtClass()) {
1795 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001796 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001797 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001798 case Expr::ParenExprClass:
1799 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001800 case Expr::StringLiteralClass:
1801 case Expr::ObjCStringLiteralClass:
1802 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001803 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001804 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001805 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1806 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1807 Builtin::BI__builtin___CFStringMakeConstantString)
1808 return false;
1809
Steve Naroff6594a702008-10-27 11:34:16 +00001810 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001811 return true;
1812
Eli Friedmanc594b322008-05-20 13:48:25 +00001813 case Expr::UnaryOperatorClass: {
1814 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1815
1816 // C99 6.6p9
1817 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1818 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1819
1820 if (Exp->getOpcode() == UnaryOperator::Extension)
1821 return CheckAddressConstantExpression(Exp->getSubExpr());
1822
Steve Naroff6594a702008-10-27 11:34:16 +00001823 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001824 return true;
1825 }
1826 case Expr::BinaryOperatorClass: {
1827 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1828 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1829
1830 Expr *PExp = Exp->getLHS();
1831 Expr *IExp = Exp->getRHS();
1832 if (IExp->getType()->isPointerType())
1833 std::swap(PExp, IExp);
1834
1835 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1836 return CheckAddressConstantExpression(PExp) ||
1837 CheckArithmeticConstantExpression(IExp);
1838 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001839 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001840 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001841 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001842 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1843 // Check for implicit promotion
1844 if (SubExpr->getType()->isFunctionType() ||
1845 SubExpr->getType()->isArrayType())
1846 return CheckAddressConstantExpressionLValue(SubExpr);
1847 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001848
1849 // Check for pointer->pointer cast
1850 if (SubExpr->getType()->isPointerType())
1851 return CheckAddressConstantExpression(SubExpr);
1852
Eli Friedmanc3f07642008-08-25 20:46:57 +00001853 if (SubExpr->getType()->isIntegralType()) {
1854 // Check for the special-case of a pointer->int->pointer cast;
1855 // this isn't standard, but some code requires it. See
1856 // PR2720 for an example.
1857 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1858 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1859 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1860 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1861 if (IntWidth >= PointerWidth) {
1862 return CheckAddressConstantExpression(SubCast->getSubExpr());
1863 }
1864 }
1865 }
1866 }
1867 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001868 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001869 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001870
Steve Naroff6594a702008-10-27 11:34:16 +00001871 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001872 return true;
1873 }
1874 case Expr::ConditionalOperatorClass: {
1875 // FIXME: Should we pedwarn here?
1876 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1877 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001878 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001879 return true;
1880 }
1881 if (CheckArithmeticConstantExpression(Exp->getCond()))
1882 return true;
1883 if (Exp->getLHS() &&
1884 CheckAddressConstantExpression(Exp->getLHS()))
1885 return true;
1886 return CheckAddressConstantExpression(Exp->getRHS());
1887 }
1888 case Expr::AddrLabelExprClass:
1889 return false;
1890 }
1891}
1892
Eli Friedman4caf0552008-06-09 05:05:07 +00001893static const Expr* FindExpressionBaseAddress(const Expr* E);
1894
1895static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1896 switch (E->getStmtClass()) {
1897 default:
1898 return E;
1899 case Expr::ParenExprClass: {
1900 const ParenExpr* PE = cast<ParenExpr>(E);
1901 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1902 }
1903 case Expr::MemberExprClass: {
1904 const MemberExpr *M = cast<MemberExpr>(E);
1905 if (M->isArrow())
1906 return FindExpressionBaseAddress(M->getBase());
1907 return FindExpressionBaseAddressLValue(M->getBase());
1908 }
1909 case Expr::ArraySubscriptExprClass: {
1910 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1911 return FindExpressionBaseAddress(ASE->getBase());
1912 }
1913 case Expr::UnaryOperatorClass: {
1914 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1915
1916 if (Exp->getOpcode() == UnaryOperator::Deref)
1917 return FindExpressionBaseAddress(Exp->getSubExpr());
1918
1919 return E;
1920 }
1921 }
1922}
1923
1924static const Expr* FindExpressionBaseAddress(const Expr* E) {
1925 switch (E->getStmtClass()) {
1926 default:
1927 return E;
1928 case Expr::ParenExprClass: {
1929 const ParenExpr* PE = cast<ParenExpr>(E);
1930 return FindExpressionBaseAddress(PE->getSubExpr());
1931 }
1932 case Expr::UnaryOperatorClass: {
1933 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1934
1935 // C99 6.6p9
1936 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1937 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1938
1939 if (Exp->getOpcode() == UnaryOperator::Extension)
1940 return FindExpressionBaseAddress(Exp->getSubExpr());
1941
1942 return E;
1943 }
1944 case Expr::BinaryOperatorClass: {
1945 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1946
1947 Expr *PExp = Exp->getLHS();
1948 Expr *IExp = Exp->getRHS();
1949 if (IExp->getType()->isPointerType())
1950 std::swap(PExp, IExp);
1951
1952 return FindExpressionBaseAddress(PExp);
1953 }
1954 case Expr::ImplicitCastExprClass: {
1955 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1956
1957 // Check for implicit promotion
1958 if (SubExpr->getType()->isFunctionType() ||
1959 SubExpr->getType()->isArrayType())
1960 return FindExpressionBaseAddressLValue(SubExpr);
1961
1962 // Check for pointer->pointer cast
1963 if (SubExpr->getType()->isPointerType())
1964 return FindExpressionBaseAddress(SubExpr);
1965
1966 // We assume that we have an arithmetic expression here;
1967 // if we don't, we'll figure it out later
1968 return 0;
1969 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001970 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001971 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1972
1973 // Check for pointer->pointer cast
1974 if (SubExpr->getType()->isPointerType())
1975 return FindExpressionBaseAddress(SubExpr);
1976
1977 // We assume that we have an arithmetic expression here;
1978 // if we don't, we'll figure it out later
1979 return 0;
1980 }
1981 }
1982}
1983
Anders Carlsson51fe9962008-11-22 21:04:56 +00001984bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001985 switch (Init->getStmtClass()) {
1986 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001987 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001988 return true;
1989 case Expr::ParenExprClass: {
1990 const ParenExpr* PE = cast<ParenExpr>(Init);
1991 return CheckArithmeticConstantExpression(PE->getSubExpr());
1992 }
1993 case Expr::FloatingLiteralClass:
1994 case Expr::IntegerLiteralClass:
1995 case Expr::CharacterLiteralClass:
1996 case Expr::ImaginaryLiteralClass:
1997 case Expr::TypesCompatibleExprClass:
1998 case Expr::CXXBoolLiteralExprClass:
1999 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002000 case Expr::CallExprClass:
2001 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002002 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002003
2004 // Allow any constant foldable calls to builtins.
2005 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002006 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002007
Steve Naroff6594a702008-10-27 11:34:16 +00002008 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002009 return true;
2010 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002011 case Expr::DeclRefExprClass:
2012 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002013 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2014 if (isa<EnumConstantDecl>(D))
2015 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002016 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002017 return true;
2018 }
2019 case Expr::CompoundLiteralExprClass:
2020 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2021 // but vectors are allowed to be magic.
2022 if (Init->getType()->isVectorType())
2023 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002024 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002025 return true;
2026 case Expr::UnaryOperatorClass: {
2027 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2028
2029 switch (Exp->getOpcode()) {
2030 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2031 // See C99 6.6p3.
2032 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002033 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002034 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002035 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002036 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2037 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002038 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002039 return true;
2040 case UnaryOperator::Extension:
2041 case UnaryOperator::LNot:
2042 case UnaryOperator::Plus:
2043 case UnaryOperator::Minus:
2044 case UnaryOperator::Not:
2045 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2046 }
2047 }
Sebastian Redl05189992008-11-11 17:56:53 +00002048 case Expr::SizeOfAlignOfExprClass: {
2049 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002050 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002051 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002052 return false;
2053 // alignof always evaluates to a constant.
2054 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002055 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002056 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002057 return true;
2058 }
2059 return false;
2060 }
2061 case Expr::BinaryOperatorClass: {
2062 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2063
2064 if (Exp->getLHS()->getType()->isArithmeticType() &&
2065 Exp->getRHS()->getType()->isArithmeticType()) {
2066 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2067 CheckArithmeticConstantExpression(Exp->getRHS());
2068 }
2069
Eli Friedman4caf0552008-06-09 05:05:07 +00002070 if (Exp->getLHS()->getType()->isPointerType() &&
2071 Exp->getRHS()->getType()->isPointerType()) {
2072 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2073 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2074
2075 // Only allow a null (constant integer) base; we could
2076 // allow some additional cases if necessary, but this
2077 // is sufficient to cover offsetof-like constructs.
2078 if (!LHSBase && !RHSBase) {
2079 return CheckAddressConstantExpression(Exp->getLHS()) ||
2080 CheckAddressConstantExpression(Exp->getRHS());
2081 }
2082 }
2083
Steve Naroff6594a702008-10-27 11:34:16 +00002084 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002085 return true;
2086 }
2087 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002088 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002089 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002090 if (SubExpr->getType()->isArithmeticType())
2091 return CheckArithmeticConstantExpression(SubExpr);
2092
Eli Friedmanb529d832008-09-02 09:37:00 +00002093 if (SubExpr->getType()->isPointerType()) {
2094 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2095 // If the pointer has a null base, this is an offsetof-like construct
2096 if (!Base)
2097 return CheckAddressConstantExpression(SubExpr);
2098 }
2099
Steve Naroff6594a702008-10-27 11:34:16 +00002100 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002101 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002102 }
2103 case Expr::ConditionalOperatorClass: {
2104 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002105
2106 // If GNU extensions are disabled, we require all operands to be arithmetic
2107 // constant expressions.
2108 if (getLangOptions().NoExtensions) {
2109 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2110 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2111 CheckArithmeticConstantExpression(Exp->getRHS());
2112 }
2113
2114 // Otherwise, we have to emulate some of the behavior of fold here.
2115 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2116 // because it can constant fold things away. To retain compatibility with
2117 // GCC code, we see if we can fold the condition to a constant (which we
2118 // should always be able to do in theory). If so, we only require the
2119 // specified arm of the conditional to be a constant. This is a horrible
2120 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002121 Expr::EvalResult EvalResult;
2122 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2123 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002124 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002125 // won't be able to either. Use it to emit the diagnostic though.
2126 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002127 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002128 return Res;
2129 }
2130
2131 // Verify that the side following the condition is also a constant.
2132 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002133 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002134 std::swap(TrueSide, FalseSide);
2135
2136 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002137 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002138
2139 // Okay, the evaluated side evaluates to a constant, so we accept this.
2140 // Check to see if the other side is obviously not a constant. If so,
2141 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002142 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002143 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002144 diag::ext_typecheck_expression_not_constant_but_accepted)
2145 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002146 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002147 }
2148 }
2149}
2150
2151bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002152 Expr::EvalResult Result;
2153
Nuno Lopes9a979c32008-07-07 16:46:50 +00002154 Init = Init->IgnoreParens();
2155
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002156 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2157 return false;
2158
Eli Friedmanc594b322008-05-20 13:48:25 +00002159 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2160 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2161 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2162
Nuno Lopes9a979c32008-07-07 16:46:50 +00002163 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2164 return CheckForConstantInitializer(e->getInitializer(), DclT);
2165
Eli Friedmanc594b322008-05-20 13:48:25 +00002166 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2167 unsigned numInits = Exp->getNumInits();
2168 for (unsigned i = 0; i < numInits; i++) {
2169 // FIXME: Need to get the type of the declaration for C++,
2170 // because it could be a reference?
2171 if (CheckForConstantInitializer(Exp->getInit(i),
2172 Exp->getInit(i)->getType()))
2173 return true;
2174 }
2175 return false;
2176 }
2177
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002178 // FIXME: We can probably remove some of this code below, now that
2179 // Expr::Evaluate is doing the heavy lifting for scalars.
2180
Eli Friedmanc594b322008-05-20 13:48:25 +00002181 if (Init->isNullPointerConstant(Context))
2182 return false;
2183 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002184 QualType InitTy = Context.getCanonicalType(Init->getType())
2185 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002186 if (InitTy == Context.BoolTy) {
2187 // Special handling for pointers implicitly cast to bool;
2188 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2189 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2190 Expr* SubE = ICE->getSubExpr();
2191 if (SubE->getType()->isPointerType() ||
2192 SubE->getType()->isArrayType() ||
2193 SubE->getType()->isFunctionType()) {
2194 return CheckAddressConstantExpression(Init);
2195 }
2196 }
2197 } else if (InitTy->isIntegralType()) {
2198 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002199 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002200 SubE = CE->getSubExpr();
2201 // Special check for pointer cast to int; we allow as an extension
2202 // an address constant cast to an integer if the integer
2203 // is of an appropriate width (this sort of code is apparently used
2204 // in some places).
2205 // FIXME: Add pedwarn?
2206 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2207 if (SubE && (SubE->getType()->isPointerType() ||
2208 SubE->getType()->isArrayType() ||
2209 SubE->getType()->isFunctionType())) {
2210 unsigned IntWidth = Context.getTypeSize(Init->getType());
2211 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2212 if (IntWidth >= PointerWidth)
2213 return CheckAddressConstantExpression(Init);
2214 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002215 }
2216
2217 return CheckArithmeticConstantExpression(Init);
2218 }
2219
2220 if (Init->getType()->isPointerType())
2221 return CheckAddressConstantExpression(Init);
2222
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002223 // An array type at the top level that isn't an init-list must
2224 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002225 if (Init->getType()->isArrayType())
2226 return false;
2227
Nuno Lopes73419bf2008-09-01 18:42:41 +00002228 if (Init->getType()->isFunctionType())
2229 return false;
2230
Steve Naroff8af6a452008-10-02 17:12:56 +00002231 // Allow block exprs at top level.
2232 if (Init->getType()->isBlockPointerType())
2233 return false;
2234
Steve Naroff6594a702008-10-27 11:34:16 +00002235 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002236 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002237}
2238
Sebastian Redl798d1192008-12-13 16:23:55 +00002239void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002240 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002241 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002242 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002243
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002244 // If there is no declaration, there was an error parsing it. Just ignore
2245 // the initializer.
2246 if (RealDecl == 0) {
2247 delete Init;
2248 return;
2249 }
Steve Naroffbb204692007-09-12 14:07:44 +00002250
Steve Naroff410e3e22007-09-12 20:13:48 +00002251 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2252 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002253 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2254 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002255 RealDecl->setInvalidDecl();
2256 return;
2257 }
Steve Naroffbb204692007-09-12 14:07:44 +00002258 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002259 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002260 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002261 if (VDecl->isBlockVarDecl()) {
2262 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002263 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002264 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002265 VDecl->setInvalidDecl();
2266 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002267 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002268 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002269 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002270
2271 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2272 if (!getLangOptions().CPlusPlus) {
2273 if (SC == VarDecl::Static) // C99 6.7.8p4.
2274 CheckForConstantInitializer(Init, DclT);
2275 }
Steve Naroffbb204692007-09-12 14:07:44 +00002276 }
Steve Naroff248a7532008-04-15 22:42:06 +00002277 } else if (VDecl->isFileVarDecl()) {
2278 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002279 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002280 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002281 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002282 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002283 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002284
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002285 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2286 if (!getLangOptions().CPlusPlus) {
2287 // C99 6.7.8p4. All file scoped initializers need to be constant.
2288 CheckForConstantInitializer(Init, DclT);
2289 }
Steve Naroffbb204692007-09-12 14:07:44 +00002290 }
2291 // If the type changed, it means we had an incomplete type that was
2292 // completed by the initializer. For example:
2293 // int ary[] = { 1, 3, 5 };
2294 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002295 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002296 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002297 Init->setType(DclT);
2298 }
Steve Naroffbb204692007-09-12 14:07:44 +00002299
2300 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002301 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002302 return;
2303}
2304
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002305void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2306 Decl *RealDecl = static_cast<Decl *>(dcl);
2307
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002308 // If there is no declaration, there was an error parsing it. Just ignore it.
2309 if (RealDecl == 0)
2310 return;
2311
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002312 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2313 QualType Type = Var->getType();
2314 // C++ [dcl.init.ref]p3:
2315 // The initializer can be omitted for a reference only in a
2316 // parameter declaration (8.3.5), in the declaration of a
2317 // function return type, in the declaration of a class member
2318 // within its class declaration (9.2), and where the extern
2319 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002320 if (Type->isReferenceType() &&
2321 Var->getStorageClass() != VarDecl::Extern &&
2322 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002323 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002324 << Var->getDeclName()
2325 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002326 Var->setInvalidDecl();
2327 return;
2328 }
2329
2330 // C++ [dcl.init]p9:
2331 //
2332 // If no initializer is specified for an object, and the object
2333 // is of (possibly cv-qualified) non-POD class type (or array
2334 // thereof), the object shall be default-initialized; if the
2335 // object is of const-qualified type, the underlying class type
2336 // shall have a user-declared default constructor.
2337 if (getLangOptions().CPlusPlus) {
2338 QualType InitType = Type;
2339 if (const ArrayType *Array = Context.getAsArrayType(Type))
2340 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002341 if (Var->getStorageClass() != VarDecl::Extern &&
2342 Var->getStorageClass() != VarDecl::PrivateExtern &&
2343 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002344 const CXXConstructorDecl *Constructor
2345 = PerformInitializationByConstructor(InitType, 0, 0,
2346 Var->getLocation(),
2347 SourceRange(Var->getLocation(),
2348 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002349 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002350 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002351 if (!Constructor)
2352 Var->setInvalidDecl();
2353 }
2354 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002355
Douglas Gregor818ce482008-10-29 13:50:18 +00002356#if 0
2357 // FIXME: Temporarily disabled because we are not properly parsing
2358 // linkage specifications on declarations, e.g.,
2359 //
2360 // extern "C" const CGPoint CGPointerZero;
2361 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002362 // C++ [dcl.init]p9:
2363 //
2364 // If no initializer is specified for an object, and the
2365 // object is of (possibly cv-qualified) non-POD class type (or
2366 // array thereof), the object shall be default-initialized; if
2367 // the object is of const-qualified type, the underlying class
2368 // type shall have a user-declared default
2369 // constructor. Otherwise, if no initializer is specified for
2370 // an object, the object and its subobjects, if any, have an
2371 // indeterminate initial value; if the object or any of its
2372 // subobjects are of const-qualified type, the program is
2373 // ill-formed.
2374 //
2375 // This isn't technically an error in C, so we don't diagnose it.
2376 //
2377 // FIXME: Actually perform the POD/user-defined default
2378 // constructor check.
2379 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002380 Context.getCanonicalType(Type).isConstQualified() &&
2381 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002382 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2383 << Var->getName()
2384 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002385#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002386 }
2387}
2388
Reid Spencer5f016e22007-07-11 17:01:13 +00002389/// The declarators are chained together backwards, reverse the list.
2390Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2391 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002392 Decl *GroupDecl = static_cast<Decl*>(group);
2393 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002394 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002395
2396 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2397 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002398 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002400 else { // reverse the list.
2401 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002402 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002403 Group->setNextDeclarator(NewGroup);
2404 NewGroup = Group;
2405 Group = Next;
2406 }
2407 }
2408 // Perform semantic analysis that depends on having fully processed both
2409 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002410 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002411 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2412 if (!IDecl)
2413 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002414 QualType T = IDecl->getType();
2415
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002416 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002417 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002418
2419 // FIXME: This won't give the correct result for
2420 // int a[10][n];
2421 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002422 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002423 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2424 SizeRange;
2425
Eli Friedmanc5773c42008-02-15 18:16:39 +00002426 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002427 } else {
2428 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2429 // static storage duration, it shall not have a variable length array.
2430 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002431 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2432 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002433 IDecl->setInvalidDecl();
2434 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002435 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2436 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002437 IDecl->setInvalidDecl();
2438 }
2439 }
2440 } else if (T->isVariablyModifiedType()) {
2441 if (IDecl->isFileVarDecl()) {
2442 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2443 IDecl->setInvalidDecl();
2444 } else {
2445 if (IDecl->getStorageClass() == VarDecl::Extern) {
2446 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2447 IDecl->setInvalidDecl();
2448 }
Steve Naroffbb204692007-09-12 14:07:44 +00002449 }
2450 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002451
Steve Naroffbb204692007-09-12 14:07:44 +00002452 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2453 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002454 if (IDecl->isBlockVarDecl() &&
2455 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002456 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002457 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002458 IDecl->setInvalidDecl();
2459 }
2460 }
2461 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2462 // object that has file scope without an initializer, and without a
2463 // storage-class specifier or with the storage-class specifier "static",
2464 // constitutes a tentative definition. Note: A tentative definition with
2465 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002466 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002467 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002468 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2469 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002470 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002471 // C99 6.9.2p3: If the declaration of an identifier for an object is
2472 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2473 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002474 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002475 IDecl->setInvalidDecl();
2476 }
2477 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002478 if (IDecl->isFileVarDecl())
2479 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002480 }
2481 return NewGroup;
2482}
Steve Naroffe1223f72007-08-28 03:03:08 +00002483
Chris Lattner04421082008-04-08 04:40:51 +00002484/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2485/// to introduce parameters into function prototype scope.
2486Sema::DeclTy *
2487Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002488 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002489
Chris Lattner04421082008-04-08 04:40:51 +00002490 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002491 VarDecl::StorageClass StorageClass = VarDecl::None;
2492 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2493 StorageClass = VarDecl::Register;
2494 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002495 Diag(DS.getStorageClassSpecLoc(),
2496 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002497 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002498 }
2499 if (DS.isThreadSpecified()) {
2500 Diag(DS.getThreadSpecLoc(),
2501 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002502 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002503 }
2504
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002505 // Check that there are no default arguments inside the type of this
2506 // parameter (C++ only).
2507 if (getLangOptions().CPlusPlus)
2508 CheckExtraCXXDefaultArguments(D);
2509
Chris Lattner04421082008-04-08 04:40:51 +00002510 // In this context, we *do not* check D.getInvalidType(). If the declarator
2511 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2512 // though it will not reflect the user specified type.
2513 QualType parmDeclType = GetTypeForDeclarator(D, S);
2514
2515 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2516
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2518 // Can this happen for params? We already checked that they don't conflict
2519 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002520 IdentifierInfo *II = D.getIdentifier();
2521 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002522 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002523 // Maybe we will complain about the shadowed template parameter.
2524 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2525 // Just pretend that we didn't see the previous declaration.
2526 PrevDecl = 0;
2527 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002528 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002529
2530 // Recover by removing the name
2531 II = 0;
2532 D.SetIdentifier(0, D.getIdentifierLoc());
2533 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002535
2536 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2537 // Doing the promotion here has a win and a loss. The win is the type for
2538 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2539 // code generator). The loss is the orginal type isn't preserved. For example:
2540 //
2541 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2542 // int blockvardecl[5];
2543 // sizeof(parmvardecl); // size == 4
2544 // sizeof(blockvardecl); // size == 20
2545 // }
2546 //
2547 // For expressions, all implicit conversions are captured using the
2548 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2549 //
2550 // FIXME: If a source translation tool needs to see the original type, then
2551 // we need to consider storing both types (in ParmVarDecl)...
2552 //
Chris Lattnere6327742008-04-02 05:18:44 +00002553 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002554 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002555 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002556 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002557 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002558
Chris Lattner04421082008-04-08 04:40:51 +00002559 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2560 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002561 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002562 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002563
Chris Lattner04421082008-04-08 04:40:51 +00002564 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002565 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002566
Douglas Gregor584049d2008-12-15 23:53:10 +00002567 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2568 if (D.getCXXScopeSpec().isSet()) {
2569 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2570 << D.getCXXScopeSpec().getRange();
2571 New->setInvalidDecl();
2572 }
2573
Douglas Gregor44b43212008-12-11 16:49:14 +00002574 // Add the parameter declaration into this scope.
2575 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002576 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002577 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002578
Chris Lattner3ff30c82008-06-29 00:02:00 +00002579 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002581
Reid Spencer5f016e22007-07-11 17:01:13 +00002582}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002583
Chris Lattnerb652cea2007-10-09 17:14:05 +00002584Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002585 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2587 "Not a function declarator!");
2588 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002589
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2591 // for a K&R function.
2592 if (!FTI.hasPrototype) {
2593 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002594 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002595 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2596 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // Implicitly declare the argument as type 'int' for lack of a better
2598 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002599 DeclSpec DS;
2600 const char* PrevSpec; // unused
2601 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2602 PrevSpec);
2603 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2604 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2605 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 }
2607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002608 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002609 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 }
2611
Douglas Gregor584049d2008-12-15 23:53:10 +00002612 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002613
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002614 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002615 ActOnDeclarator(ParentScope, D, 0,
2616 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002617}
2618
2619Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2620 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002621 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002622
2623 // See if this is a redefinition.
2624 const FunctionDecl *Definition;
2625 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002626 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002627 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002628 }
2629
Douglas Gregor44b43212008-12-11 16:49:14 +00002630 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002631
Chris Lattner04421082008-04-08 04:40:51 +00002632 // Check the validity of our function parameters
2633 CheckParmsForFunctionDef(FD);
2634
2635 // Introduce our parameters into the function scope
2636 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2637 ParmVarDecl *Param = FD->getParamDecl(p);
2638 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002639 if (Param->getIdentifier())
2640 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 }
Chris Lattner04421082008-04-08 04:40:51 +00002642
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002643 // Checking attributes of current function definition
2644 // dllimport attribute.
2645 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2646 // dllimport attribute cannot be applied to definition.
2647 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2648 Diag(FD->getLocation(),
2649 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2650 << "dllimport";
2651 FD->setInvalidDecl();
2652 return FD;
2653 } else {
2654 // If a symbol previously declared dllimport is later defined, the
2655 // attribute is ignored in subsequent references, and a warning is
2656 // emitted.
2657 Diag(FD->getLocation(),
2658 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2659 << FD->getNameAsCString() << "dllimport";
2660 }
2661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 return FD;
2663}
2664
Sebastian Redl798d1192008-12-13 16:23:55 +00002665Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002666 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002667 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002668 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002669 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002670 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002671 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002672 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002673 } else
2674 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002675 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 // Verify and clean out per-function state.
2677
2678 // Check goto/label use.
2679 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2680 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2681 // Verify that we have no forward references left. If so, there was a goto
2682 // or address of a label taken, but no definition of it. Label fwd
2683 // definitions are indicated with a null substmt.
2684 if (I->second->getSubStmt() == 0) {
2685 LabelStmt *L = I->second;
2686 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002687 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002688
2689 // At this point, we have gotos that use the bogus label. Stitch it into
2690 // the function body so that they aren't leaked and that the AST is well
2691 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002692 if (Body) {
2693 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002694 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002695 } else {
2696 // The whole function wasn't parsed correctly, just delete this.
2697 delete L;
2698 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
2700 }
2701 LabelMap.clear();
2702
Steve Naroffd6d054d2007-11-11 23:20:51 +00002703 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002704}
2705
Reid Spencer5f016e22007-07-11 17:01:13 +00002706/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2707/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002708ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2709 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002710 // Extension in C99. Legal in C90, but warn about it.
2711 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002712 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002713 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002714 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002715
2716 // FIXME: handle stuff like:
2717 // void foo() { extern float X(); }
2718 // void bar() { X(); } <-- implicit decl for X in another scope.
2719
2720 // Set a Declarator for the implicit definition: int foo();
2721 const char *Dummy;
2722 DeclSpec DS;
2723 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2724 Error = Error; // Silence warning.
2725 assert(!Error && "Error setting up implicit decl!");
2726 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002727 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 D.SetIdentifier(&II, Loc);
2729
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002730 // Insert this function into translation-unit scope.
2731
2732 DeclContext *PrevDC = CurContext;
2733 CurContext = Context.getTranslationUnitDecl();
2734
Steve Naroffe2ef8152008-04-04 14:32:09 +00002735 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002736 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002737 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002738
2739 CurContext = PrevDC;
2740
Steve Naroffe2ef8152008-04-04 14:32:09 +00002741 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002742}
2743
2744
Chris Lattner41af0932007-11-14 06:34:38 +00002745TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002746 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002748 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002749
2750 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002751 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2752 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002753 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002754 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002755 if (D.getInvalidType())
2756 NewTD->setInvalidDecl();
2757 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002758}
2759
Steve Naroff08d92e42007-09-15 18:49:24 +00002760/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002761/// former case, Name will be non-null. In the later case, Name will be null.
2762/// TagType indicates what kind of tag this is. TK indicates whether this is a
2763/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002764Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002765 SourceLocation KWLoc, const CXXScopeSpec &SS,
2766 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002767 AttributeList *Attr,
2768 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002769 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 assert((Name != 0 || TK == TK_Definition) &&
2771 "Nameless record must be a definition!");
2772
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002773 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 switch (TagType) {
2775 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002776 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2777 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2778 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2779 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002780 }
2781
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002782 DeclContext *DC = CurContext;
2783 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002784
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002785 if (Name && SS.isNotEmpty()) {
2786 // We have a nested-name tag ('struct foo::bar').
2787
2788 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002789 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002790 Name = 0;
2791 goto CreateNewDecl;
2792 }
2793
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002794 DC = static_cast<DeclContext*>(SS.getScopeRep());
2795 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002796 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2797
2798 // A tag 'foo::bar' must already exist.
2799 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002800 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002801 Name = 0;
2802 goto CreateNewDecl;
2803 }
2804 } else {
2805 // If this is a named struct, check to see if there was a previous forward
2806 // declaration or definition.
2807 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2808 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2809 }
2810
Douglas Gregorf57172b2008-12-08 18:40:42 +00002811 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002812 // Maybe we will complain about the shadowed template parameter.
2813 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2814 // Just pretend that we didn't see the previous declaration.
2815 PrevDecl = 0;
2816 }
2817
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002818 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002819 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2820 "unexpected Decl type");
2821 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002822 // If this is a use of a previous tag, or if the tag is already declared
2823 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002824 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002825 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002826 // Make sure that this wasn't declared as an enum and now used as a
2827 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002828 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002829 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002830 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002831 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002832 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002833 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002834 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002835 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002836
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002837 // FIXME: In the future, return a variant or some other clue
2838 // for the consumer of this Decl to know it doesn't own it.
2839 // For our current ASTs this shouldn't be a problem, but will
2840 // need to be changed with DeclGroups.
2841 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002842 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002843
2844 // Diagnose attempts to redefine a tag.
2845 if (TK == TK_Definition) {
2846 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2847 Diag(NameLoc, diag::err_redefinition) << Name;
2848 Diag(Def->getLocation(), diag::note_previous_definition);
2849 // If this is a redefinition, recover by making this struct be
2850 // anonymous, which will make any later references get the previous
2851 // definition.
2852 Name = 0;
2853 PrevDecl = 0;
2854 }
2855 // Okay, this is definition of a previously declared or referenced
2856 // tag PrevDecl. We're going to create a new Decl for it.
2857 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002858 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002859 // If we get here we have (another) forward declaration or we
2860 // have a definition. Just create a new decl.
2861 } else {
2862 // If we get here, this is a definition of a new tag type in a nested
2863 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2864 // new decl/type. We set PrevDecl to NULL so that the entities
2865 // have distinct types.
2866 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002868 // If we get here, we're going to create a new Decl. If PrevDecl
2869 // is non-NULL, it's a definition of the tag declared by
2870 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002871 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002872 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002873 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002874 // The tag name clashes with a namespace name, issue an error and
2875 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002876 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002877 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002878 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002879 PrevDecl = 0;
2880 } else {
2881 // The existing declaration isn't relevant to us; we're in a
2882 // new scope, so clear out the previous declaration.
2883 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002884 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002886 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002887
Chris Lattnercc98eac2008-12-17 07:13:27 +00002888CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002889
2890 // If there is an identifier, use the location of the identifier as the
2891 // location of the decl, otherwise use the location of the struct/union
2892 // keyword.
2893 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2894
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002895 // Otherwise, create a new declaration. If there is a previous
2896 // declaration of the same entity, the two will be linked via
2897 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002898 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002899
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002900 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002901 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2902 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002903 New = EnumDecl::Create(Context, DC, Loc, Name,
2904 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 // If this is an undefined enum, warn.
2906 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002907 } else {
2908 // struct/union/class
2909
Reid Spencer5f016e22007-07-11 17:01:13 +00002910 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2911 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002912 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002913 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002914 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2915 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002916 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002917 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2918 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002919 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002920
2921 if (Kind != TagDecl::TK_enum) {
2922 // Handle #pragma pack: if the #pragma pack stack has non-default
2923 // alignment, make up a packed attribute for this decl. These
2924 // attributes are checked when the ASTContext lays out the
2925 // structure.
2926 //
2927 // It is important for implementing the correct semantics that this
2928 // happen here (in act on tag decl). The #pragma pack stack is
2929 // maintained as a result of parser callbacks which can occur at
2930 // many points during the parsing of a struct declaration (because
2931 // the #pragma tokens are effectively skipped over during the
2932 // parsing of the struct).
2933 if (unsigned Alignment = PackContext.getAlignment())
2934 New->addAttr(new PackedAttr(Alignment * 8));
2935 }
2936
2937 if (Attr)
2938 ProcessDeclAttributeList(New, Attr);
2939
2940 // Set the lexical context. If the tag has a C++ scope specifier, the
2941 // lexical context will be different from the semantic context.
2942 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002943
2944 // If this has an identifier, add it to the scope stack.
2945 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002946 // The scope passed in may not be a decl scope. Zip up the scope tree until
2947 // we find one that is.
2948 while ((S->getFlags() & Scope::DeclScope) == 0)
2949 S = S->getParent();
2950
2951 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002952 PushOnScopeChains(New, S);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002953 } else if (getLangOptions().CPlusPlus) {
2954 // FIXME: We also want to do this for C, but if this tag is
2955 // defined within a structure CurContext will point to the context
2956 // enclosing the structure, and we would end up inserting the tag
2957 // type into the wrong place.
2958 CurContext->addDecl(Context, New);
Reid Spencer5f016e22007-07-11 17:01:13 +00002959 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002960
Reid Spencer5f016e22007-07-11 17:01:13 +00002961 return New;
2962}
2963
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002964
Chris Lattner1d353ba2008-11-12 21:17:48 +00002965/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2966/// types into constant array types in certain situations which would otherwise
2967/// be errors (for GCC compatibility).
2968static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2969 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002970 // This method tries to turn a variable array into a constant
2971 // array even when the size isn't an ICE. This is necessary
2972 // for compatibility with code that depends on gcc's buggy
2973 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002974 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2975 if (!VLATy) return QualType();
2976
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002977 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002978 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002979 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002980 return QualType();
2981
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002982 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2983 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002984 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2985 return Context.getConstantArrayType(VLATy->getElementType(),
2986 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002987 return QualType();
2988}
2989
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002990bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002991 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002992 // FIXME: 6.7.2.1p4 - verify the field type.
2993
2994 llvm::APSInt Value;
2995 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2996 return true;
2997
Chris Lattnercd087072008-12-12 04:56:04 +00002998 // Zero-width bitfield is ok for anonymous field.
2999 if (Value == 0 && FieldName)
3000 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3001
3002 if (Value.isNegative())
3003 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003004
3005 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3006 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003007 if (TypeSize && Value.getZExtValue() > TypeSize)
3008 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3009 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003010
3011 return false;
3012}
3013
Steve Naroff08d92e42007-09-15 18:49:24 +00003014/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003015/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003016Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003017 SourceLocation DeclStart,
3018 Declarator &D, ExprTy *BitfieldWidth) {
3019 IdentifierInfo *II = D.getIdentifier();
3020 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003022 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 if (II) Loc = D.getIdentifierLoc();
3024
3025 // FIXME: Unnamed fields can be handled in various different ways, for
3026 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003027
Reid Spencer5f016e22007-07-11 17:01:13 +00003028 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003029 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3030 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003031
Reid Spencer5f016e22007-07-11 17:01:13 +00003032 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3033 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003034 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003035 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003036 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003037 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003038 T = FixedTy;
3039 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003040 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003041 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003042 InvalidDecl = true;
3043 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003044 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003045
3046 if (BitWidth) {
3047 if (VerifyBitField(Loc, II, T, BitWidth))
3048 InvalidDecl = true;
3049 } else {
3050 // Not a bitfield.
3051
3052 // validate II.
3053
3054 }
3055
Reid Spencer5f016e22007-07-11 17:01:13 +00003056 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003057 FieldDecl *NewFD;
3058
Douglas Gregor44b43212008-12-11 16:49:14 +00003059 NewFD = FieldDecl::Create(Context, Record,
3060 Loc, II, T, BitWidth,
3061 D.getDeclSpec().getStorageClassSpec() ==
3062 DeclSpec::SCS_mutable,
3063 /*PrevDecl=*/0);
3064
Sebastian Redl64b45f72009-01-05 20:52:13 +00003065 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003066 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003067 if (!T->isPODType())
3068 cast<CXXRecordDecl>(Record)->setPOD(false);
3069 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003070
Chris Lattner3ff30c82008-06-29 00:02:00 +00003071 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003072
Steve Naroff5912a352007-08-28 20:14:24 +00003073 if (D.getInvalidType() || InvalidDecl)
3074 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003075
3076 if (II && getLangOptions().CPlusPlus)
3077 PushOnScopeChains(NewFD, S);
3078 else
3079 Record->addDecl(Context, NewFD);
3080
Steve Naroff5912a352007-08-28 20:14:24 +00003081 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003082}
3083
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003084/// TranslateIvarVisibility - Translate visibility from a token ID to an
3085/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003086static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003087TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003088 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003089 default: assert(0 && "Unknown visitibility kind");
3090 case tok::objc_private: return ObjCIvarDecl::Private;
3091 case tok::objc_public: return ObjCIvarDecl::Public;
3092 case tok::objc_protected: return ObjCIvarDecl::Protected;
3093 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003094 }
3095}
3096
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003097/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3098/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003099Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003100 SourceLocation DeclStart,
3101 Declarator &D, ExprTy *BitfieldWidth,
3102 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003103 IdentifierInfo *II = D.getIdentifier();
3104 Expr *BitWidth = (Expr*)BitfieldWidth;
3105 SourceLocation Loc = DeclStart;
3106 if (II) Loc = D.getIdentifierLoc();
3107
3108 // FIXME: Unnamed fields can be handled in various different ways, for
3109 // example, unnamed unions inject all members into the struct namespace!
3110
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003111 QualType T = GetTypeForDeclarator(D, S);
3112 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3113 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003114
3115 if (BitWidth) {
3116 // TODO: Validate.
3117 //printf("WARNING: BITFIELDS IGNORED!\n");
3118
3119 // 6.7.2.1p3
3120 // 6.7.2.1p4
3121
3122 } else {
3123 // Not a bitfield.
3124
3125 // validate II.
3126
3127 }
3128
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003129 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3130 // than a variably modified type.
3131 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003132 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003133 InvalidDecl = true;
3134 }
3135
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003136 // Get the visibility (access control) for this ivar.
3137 ObjCIvarDecl::AccessControl ac =
3138 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3139 : ObjCIvarDecl::None;
3140
3141 // Construct the decl.
3142 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003143 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003144
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003145 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003146 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003147
3148 if (D.getInvalidType() || InvalidDecl)
3149 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003150
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003151 return NewID;
3152}
3153
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003154void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003155 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003156 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003157 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003158 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003159 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3160 assert(EnclosingDecl && "missing record or interface decl");
3161 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3162
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003163 if (Record)
3164 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
3165 // Diagnose code like:
3166 // struct S { struct S {} X; };
3167 // We discover this when we complete the outer S. Reject and ignore the
3168 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003169 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003170 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003171 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003172 Record->setInvalidDecl();
3173 return;
3174 }
3175
Reid Spencer5f016e22007-07-11 17:01:13 +00003176 // Verify that all the fields are okay.
3177 unsigned NumNamedMembers = 0;
3178 llvm::SmallVector<FieldDecl*, 32> RecFields;
3179 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00003180
Reid Spencer5f016e22007-07-11 17:01:13 +00003181 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003182
Steve Naroff74216642007-09-14 22:20:54 +00003183 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3184 assert(FD && "missing field decl");
3185
3186 // Remember all fields.
3187 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003188
3189 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003190 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00003191
Reid Spencer5f016e22007-07-11 17:01:13 +00003192 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003193 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003194 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003195 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003196 FD->setInvalidDecl();
3197 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 continue;
3199 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3201 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003202 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003203 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003204 FD->setInvalidDecl();
3205 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003206 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003207 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003208 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003209 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003210 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003211 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003212 FD->setInvalidDecl();
3213 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003214 continue;
3215 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003216 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003217 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003218 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003219 FD->setInvalidDecl();
3220 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 continue;
3222 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003223 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003224 if (Record)
3225 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003226 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003227 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3228 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003229 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003230 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3231 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003232 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003233 Record->setHasFlexibleArrayMember(true);
3234 } else {
3235 // If this is a struct/class and this is not the last element, reject
3236 // it. Note that GCC supports variable sized arrays in the middle of
3237 // structures.
3238 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003239 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003240 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003241 FD->setInvalidDecl();
3242 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003243 continue;
3244 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 // We support flexible arrays at the end of structs in other structs
3246 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003247 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003248 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003249 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003250 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 }
3252 }
3253 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003254 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003255 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003256 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003257 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003258 FD->setInvalidDecl();
3259 EnclosingDecl->setInvalidDecl();
3260 continue;
3261 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003262 // Keep track of the number of named members.
3263 if (IdentifierInfo *II = FD->getIdentifier()) {
3264 // Detect duplicate member names.
3265 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003266 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003267 // Find the previous decl.
3268 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003269 for (unsigned i = 0; ; ++i) {
3270 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003271 if (RecFields[i]->getIdentifier() == II) {
3272 PrevLoc = RecFields[i]->getLocation();
3273 break;
3274 }
3275 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003276 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003277 FD->setInvalidDecl();
3278 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003279 continue;
3280 }
3281 ++NumNamedMembers;
3282 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003283 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003284
Reid Spencer5f016e22007-07-11 17:01:13 +00003285 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003286 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003287 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003288 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3289 // Sema::ActOnFinishCXXClassDef.
3290 if (!isa<CXXRecordDecl>(Record))
3291 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003292 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003293 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003294 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003295 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003296 // Must enforce the rule that ivars in the base classes may not be
3297 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003298 if (ID->getSuperClass()) {
3299 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3300 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3301 ObjCIvarDecl* Ivar = (*IVI);
3302 IdentifierInfo *II = Ivar->getIdentifier();
3303 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3304 if (prevIvar) {
3305 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3306 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003307 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003308 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003309 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003310 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003311 else if (ObjCImplementationDecl *IMPDecl =
3312 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003313 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3314 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003315 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003316 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003317 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003318
3319 if (Attr)
3320 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003321}
3322
Douglas Gregor074149e2009-01-05 19:45:36 +00003323void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003324 EnumDecl *Enum = cast<EnumDecl>((Decl *)EnumD);
Douglas Gregor074149e2009-01-05 19:45:36 +00003325
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003326 // Enter the enumeration context.
3327 PushDeclContext(S, Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003328}
3329
Steve Naroff08d92e42007-09-15 18:49:24 +00003330Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003331 DeclTy *lastEnumConst,
3332 SourceLocation IdLoc, IdentifierInfo *Id,
3333 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003334 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003335 EnumConstantDecl *LastEnumConst =
3336 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3337 Expr *Val = static_cast<Expr*>(val);
3338
Chris Lattner31e05722007-08-26 06:24:45 +00003339 // The scope passed in may not be a decl scope. Zip up the scope tree until
3340 // we find one that is.
3341 while ((S->getFlags() & Scope::DeclScope) == 0)
3342 S = S->getParent();
3343
Reid Spencer5f016e22007-07-11 17:01:13 +00003344 // Verify that there isn't already something declared with this name in this
3345 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003346 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003347 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003348 // Maybe we will complain about the shadowed template parameter.
3349 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3350 // Just pretend that we didn't see the previous declaration.
3351 PrevDecl = 0;
3352 }
3353
3354 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003355 // When in C++, we may get a TagDecl with the same name; in this case the
3356 // enum constant will 'hide' the tag.
3357 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3358 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003359 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003360 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003361 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003362 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003363 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003364 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003365 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003366 return 0;
3367 }
3368 }
3369
3370 llvm::APSInt EnumVal(32);
3371 QualType EltTy;
3372 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003373 // Make sure to promote the operand type to int.
3374 UsualUnaryConversions(Val);
3375
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3377 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003378 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003379 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003380 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003381 } else {
3382 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003384 }
3385
3386 if (!Val) {
3387 if (LastEnumConst) {
3388 // Assign the last value + 1.
3389 EnumVal = LastEnumConst->getInitVal();
3390 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003391
3392 // Check for overflow on increment.
3393 if (EnumVal < LastEnumConst->getInitVal())
3394 Diag(IdLoc, diag::warn_enum_value_overflow);
3395
Chris Lattnerb7416f92007-08-27 17:37:24 +00003396 EltTy = LastEnumConst->getType();
3397 } else {
3398 // First value, set to zero.
3399 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003400 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003402 }
3403
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003404 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003405 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3406 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003407 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003408
3409 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003410 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003411
3412 // Add this enumerator into the enum itself.
3413 // FIXME: This means that the enumerator is stored in two
3414 // DeclContexts. This is not a long-term solution.
3415 New->setLexicalDeclContext(TheEnumDecl);
3416 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 return New;
3418}
3419
Steve Naroff02408c62008-08-07 14:08:16 +00003420// FIXME: For consistency with ActOnFields(), we should have the parser
3421// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003422void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003423 DeclTy **Elements, unsigned NumElements) {
3424 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003425 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003426
Douglas Gregor074149e2009-01-05 19:45:36 +00003427 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3428 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3429 // Diagnose code like:
3430 // enum e0 {
3431 // E0 = sizeof(enum e0 { E1 })
3432 // };
3433 Diag(Def->getLocation(), diag::err_nested_redefinition)
3434 << Enum->getDeclName();
3435 Diag(Enum->getLocation(), diag::note_previous_definition);
3436 Enum->setInvalidDecl();
3437 PopDeclContext();
3438 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003439 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003440
Chris Lattnere37f0be2007-08-28 05:10:31 +00003441 // TODO: If the result value doesn't fit in an int, it must be a long or long
3442 // long value. ISO C does not support this, but GCC does as an extension,
3443 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003444 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003445
Chris Lattnerac609682007-08-28 06:15:15 +00003446 // Verify that all the values are okay, compute the size of the values, and
3447 // reverse the list.
3448 unsigned NumNegativeBits = 0;
3449 unsigned NumPositiveBits = 0;
3450
3451 // Keep track of whether all elements have type int.
3452 bool AllElementsInt = true;
3453
Reid Spencer5f016e22007-07-11 17:01:13 +00003454 EnumConstantDecl *EltList = 0;
3455 for (unsigned i = 0; i != NumElements; ++i) {
3456 EnumConstantDecl *ECD =
3457 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3458 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003459
3460 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003461 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003462 assert(InitVal.getBitWidth() >= IntWidth &&
3463 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003464 if (InitVal.getBitWidth() > IntWidth) {
3465 llvm::APSInt V(InitVal);
3466 V.trunc(IntWidth);
3467 V.extend(InitVal.getBitWidth());
3468 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003469 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3470 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003471 }
Chris Lattnerac609682007-08-28 06:15:15 +00003472
3473 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003474 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003475 NumPositiveBits = std::max(NumPositiveBits,
3476 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003477 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003478 NumNegativeBits = std::max(NumNegativeBits,
3479 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003480
Chris Lattnerac609682007-08-28 06:15:15 +00003481 // Keep track of whether every enum element has type int (very commmon).
3482 if (AllElementsInt)
3483 AllElementsInt = ECD->getType() == Context.IntTy;
3484
Reid Spencer5f016e22007-07-11 17:01:13 +00003485 ECD->setNextDeclarator(EltList);
3486 EltList = ECD;
3487 }
3488
Chris Lattnerac609682007-08-28 06:15:15 +00003489 // Figure out the type that should be used for this enum.
3490 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3491 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003492 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003493
3494 if (NumNegativeBits) {
3495 // If there is a negative value, figure out the smallest integer type (of
3496 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003497 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003498 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003499 BestWidth = IntWidth;
3500 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003501 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003502
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003503 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003504 BestType = Context.LongTy;
3505 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003506 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003507
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003508 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003509 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3510 BestType = Context.LongLongTy;
3511 }
3512 }
3513 } else {
3514 // If there is no negative value, figure out which of uint, ulong, ulonglong
3515 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003516 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003517 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003518 BestWidth = IntWidth;
3519 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003520 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003521 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003522 } else {
3523 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003524 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003525 "How could an initializer get larger than ULL?");
3526 BestType = Context.UnsignedLongLongTy;
3527 }
3528 }
3529
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003530 // Loop over all of the enumerator constants, changing their types to match
3531 // the type of the enum if needed.
3532 for (unsigned i = 0; i != NumElements; ++i) {
3533 EnumConstantDecl *ECD =
3534 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3535 if (!ECD) continue; // Already issued a diagnostic.
3536
3537 // Standard C says the enumerators have int type, but we allow, as an
3538 // extension, the enumerators to be larger than int size. If each
3539 // enumerator value fits in an int, type it as an int, otherwise type it the
3540 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3541 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003542 if (ECD->getType() == Context.IntTy) {
3543 // Make sure the init value is signed.
3544 llvm::APSInt IV = ECD->getInitVal();
3545 IV.setIsSigned(true);
3546 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003547
3548 if (getLangOptions().CPlusPlus)
3549 // C++ [dcl.enum]p4: Following the closing brace of an
3550 // enum-specifier, each enumerator has the type of its
3551 // enumeration.
3552 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003553 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003554 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003555
3556 // Determine whether the value fits into an int.
3557 llvm::APSInt InitVal = ECD->getInitVal();
3558 bool FitsInInt;
3559 if (InitVal.isUnsigned() || !InitVal.isNegative())
3560 FitsInInt = InitVal.getActiveBits() < IntWidth;
3561 else
3562 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3563
3564 // If it fits into an integer type, force it. Otherwise force it to match
3565 // the enum decl type.
3566 QualType NewTy;
3567 unsigned NewWidth;
3568 bool NewSign;
3569 if (FitsInInt) {
3570 NewTy = Context.IntTy;
3571 NewWidth = IntWidth;
3572 NewSign = true;
3573 } else if (ECD->getType() == BestType) {
3574 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003575 if (getLangOptions().CPlusPlus)
3576 // C++ [dcl.enum]p4: Following the closing brace of an
3577 // enum-specifier, each enumerator has the type of its
3578 // enumeration.
3579 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003580 continue;
3581 } else {
3582 NewTy = BestType;
3583 NewWidth = BestWidth;
3584 NewSign = BestType->isSignedIntegerType();
3585 }
3586
3587 // Adjust the APSInt value.
3588 InitVal.extOrTrunc(NewWidth);
3589 InitVal.setIsSigned(NewSign);
3590 ECD->setInitVal(InitVal);
3591
3592 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003593 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3594 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003595 if (getLangOptions().CPlusPlus)
3596 // C++ [dcl.enum]p4: Following the closing brace of an
3597 // enum-specifier, each enumerator has the type of its
3598 // enumeration.
3599 ECD->setType(EnumType);
3600 else
3601 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003602 }
Chris Lattnerac609682007-08-28 06:15:15 +00003603
Douglas Gregor44b43212008-12-11 16:49:14 +00003604 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003605 Consumer.HandleTagDeclDefinition(Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003606
3607 // Leave the context of the enumeration.
3608 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00003609}
3610
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003611Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003612 ExprArg expr) {
3613 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3614
Chris Lattner8e25d862008-03-16 00:16:02 +00003615 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003616}
3617
Douglas Gregorf44515a2008-12-16 22:23:02 +00003618
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003619void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3620 ExprTy *alignment, SourceLocation PragmaLoc,
3621 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3622 Expr *Alignment = static_cast<Expr *>(alignment);
3623
3624 // If specified then alignment must be a "small" power of two.
3625 unsigned AlignmentVal = 0;
3626 if (Alignment) {
3627 llvm::APSInt Val;
3628 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3629 !Val.isPowerOf2() ||
3630 Val.getZExtValue() > 16) {
3631 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3632 delete Alignment;
3633 return; // Ignore
3634 }
3635
3636 AlignmentVal = (unsigned) Val.getZExtValue();
3637 }
3638
3639 switch (Kind) {
3640 case Action::PPK_Default: // pack([n])
3641 PackContext.setAlignment(AlignmentVal);
3642 break;
3643
3644 case Action::PPK_Show: // pack(show)
3645 // Show the current alignment, making sure to show the right value
3646 // for the default.
3647 AlignmentVal = PackContext.getAlignment();
3648 // FIXME: This should come from the target.
3649 if (AlignmentVal == 0)
3650 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003651 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003652 break;
3653
3654 case Action::PPK_Push: // pack(push [, id] [, [n])
3655 PackContext.push(Name);
3656 // Set the new alignment if specified.
3657 if (Alignment)
3658 PackContext.setAlignment(AlignmentVal);
3659 break;
3660
3661 case Action::PPK_Pop: // pack(pop [, id] [, n])
3662 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3663 // "#pragma pack(pop, identifier, n) is undefined"
3664 if (Alignment && Name)
3665 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3666
3667 // Do the pop.
3668 if (!PackContext.pop(Name)) {
3669 // If a name was specified then failure indicates the name
3670 // wasn't found. Otherwise failure indicates the stack was
3671 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003672 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3673 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003674
3675 // FIXME: Warn about popping named records as MSVC does.
3676 } else {
3677 // Pop succeeded, set the new alignment if specified.
3678 if (Alignment)
3679 PackContext.setAlignment(AlignmentVal);
3680 }
3681 break;
3682
3683 default:
3684 assert(0 && "Invalid #pragma pack kind.");
3685 }
3686}
3687
3688bool PragmaPackStack::pop(IdentifierInfo *Name) {
3689 if (Stack.empty())
3690 return false;
3691
3692 // If name is empty just pop top.
3693 if (!Name) {
3694 Alignment = Stack.back().first;
3695 Stack.pop_back();
3696 return true;
3697 }
3698
3699 // Otherwise, find the named record.
3700 for (unsigned i = Stack.size(); i != 0; ) {
3701 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003702 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003703 // Found it, pop up to and including this record.
3704 Alignment = Stack[i].first;
3705 Stack.erase(Stack.begin() + i, Stack.end());
3706 return true;
3707 }
3708 }
3709
3710 return false;
3711}