blob: ea2ea074aadbcf9b018e21c5591d72aa4d0fc465 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000031
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Douglas Gregorb0212bd2008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-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 Naroff6384a012008-04-02 14:35:35 +000043
Douglas Gregor1d661552008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregordd861062008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000049 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000050}
51
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-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
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-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
Argiris Kirtzidis881964b2008-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();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000077
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000079}
80
Douglas Gregor8acb7272008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Chris Lattnerf3874bc2008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000090
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000092}
93
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-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
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104
Douglas Gregor6e71edc2008-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
Argiris Kirtzidis59a9afb2008-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 Gregor8acb7272008-12-11 16:49:14 +0000119 if (CurContext == TD->getDeclContext()) {
120 // We're pushing the tag into the current context, which might
121 // require some reshuffling in the identifier resolver.
122 IdentifierResolver::iterator
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000123 I = IdResolver.begin(TD->getDeclName(), CurContext,
124 false/*LookInParentCtx*/),
125 IEnd = IdResolver.end();
126 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
127 NamedDecl *PrevDecl = *I;
128 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
129 PrevDecl = *I, ++I) {
130 if (TD->declarationReplaces(*I)) {
131 // This is a redeclaration. Remove it from the chain and
132 // break out, so that we'll add in the shadowed
133 // declaration.
134 S->RemoveDecl(*I);
135 if (PrevDecl == *I) {
136 IdResolver.RemoveDecl(*I);
137 IdResolver.AddDecl(TD);
138 return;
139 } else {
140 IdResolver.RemoveDecl(*I);
141 break;
142 }
143 }
144 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000145
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000146 // There is already a declaration with the same name in the same
147 // scope, which is not a tag declaration. It must be found
148 // before we find the new declaration, so insert the new
149 // declaration at the end of the chain.
150 IdResolver.AddShadowedDecl(TD, PrevDecl);
151
152 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000153 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000154 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000155 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000156 // We are pushing the name of a function, which might be an
157 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000158 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000159 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000160 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000161 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000162 false/*LookInParentCtx*/),
163 IdResolver.end(),
164 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
165 FD));
166 if (Redecl != IdResolver.end()) {
167 // There is already a declaration of a function on our
168 // IdResolver chain. Replace it with this declaration.
169 S->RemoveDecl(*Redecl);
170 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000171 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000172 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000173
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000174 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000175}
176
Steve Naroff9637a9b2007-10-09 22:01:59 +0000177void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000178 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000179 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
180 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000181
Chris Lattner4b009652007-07-25 00:24:17 +0000182 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
183 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000184 Decl *TmpD = static_cast<Decl*>(*I);
185 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000186
Douglas Gregor8acb7272008-12-11 16:49:14 +0000187 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
188 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000189
Douglas Gregor8acb7272008-12-11 16:49:14 +0000190 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000191
Douglas Gregor8acb7272008-12-11 16:49:14 +0000192 // Remove this name from our lexical scope.
193 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000194 }
195}
196
Steve Naroffe57c21a2008-04-01 23:04:06 +0000197/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
198/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000199ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000200 // The third "scope" argument is 0 since we aren't enabling lazy built-in
201 // creation from this context.
202 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000203
Steve Naroff6384a012008-04-02 14:35:35 +0000204 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000205}
206
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000207/// MaybeConstructOverloadSet - Name lookup has determined that the
208/// elements in [I, IEnd) have the name that we are looking for, and
209/// *I is a match for the namespace. This routine returns an
210/// appropriate Decl for name lookup, which may either be *I or an
211/// OverloadeFunctionDecl that represents the overloaded functions in
212/// [I, IEnd).
213///
214/// The existance of this routine is temporary; LookupDecl should
215/// probably be able to return multiple results, to deal with cases of
216/// ambiguity and overloaded functions without needing to create a
217/// Decl node.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000218template<typename DeclIterator>
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000219static Decl *
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000220MaybeConstructOverloadSet(ASTContext &Context,
221 DeclIterator I, DeclIterator IEnd) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000222 assert(I != IEnd && "Iterator range cannot be empty");
223 assert(!isa<OverloadedFunctionDecl>(*I) &&
224 "Cannot have an overloaded function");
225
226 if (isa<FunctionDecl>(*I)) {
227 // If we found a function, there might be more functions. If
228 // so, collect them into an overload set.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000229 DeclIterator Last = I;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000230 OverloadedFunctionDecl *Ovl = 0;
231 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
232 if (!Ovl) {
233 // FIXME: We leak this overload set. Eventually, we want to
234 // stop building the declarations for these overload sets, so
235 // there will be nothing to leak.
236 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000237 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000238 (*I)->getDeclName());
239 Ovl->addOverload(cast<FunctionDecl>(*I));
240 }
241 Ovl->addOverload(cast<FunctionDecl>(*Last));
242 }
243
244 // If we had more than one function, we built an overload
245 // set. Return it.
246 if (Ovl)
247 return Ovl;
248 }
249
250 return *I;
251}
252
Steve Naroffe57c21a2008-04-01 23:04:06 +0000253/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000254/// namespace. NamespaceNameOnly - during lookup only namespace names
255/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
256/// 'When looking up a namespace-name in a using-directive or
257/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000258Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000259 const DeclContext *LookupCtx,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000260 bool enableLazyBuiltinCreation,
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000261 bool LookInParent,
262 bool NamespaceNameOnly) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000263 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000264 unsigned NS = NSI;
265 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
266 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000267
Douglas Gregor39677622008-12-11 20:41:00 +0000268 if (LookupCtx == 0 &&
269 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
270 // Unqualified name lookup in C/Objective-C and name lookup for
271 // labels in C++ is purely lexical, so search in the
272 // declarations attached to the name.
273 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000274 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregor39677622008-12-11 20:41:00 +0000275 IdentifierResolver::iterator I
276 = IdResolver.begin(Name, CurContext, LookInParent);
277
278 // Scan up the scope chain looking for a decl that matches this
279 // identifier that is in the appropriate namespace. This search
280 // should not take long, as shadowing of names is uncommon, and
281 // deep shadowing is extremely uncommon.
282 for (; I != IdResolver.end(); ++I)
Chris Lattner093e31b2009-01-06 07:20:03 +0000283 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000284 return *I;
Douglas Gregor39677622008-12-11 20:41:00 +0000285 } else if (LookupCtx) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000286 // Perform qualified name lookup into the LookupCtx.
287 // FIXME: Will need to look into base classes and such.
Douglas Gregor39677622008-12-11 20:41:00 +0000288 DeclContext::lookup_const_iterator I, E;
289 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Chris Lattner093e31b2009-01-06 07:20:03 +0000290 if ((*I)->isInIdentifierNamespace(NS)) {
291 // Ignore non-namespace names if we're only looking for namespaces.
292 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
293
294 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000295 }
Douglas Gregor39677622008-12-11 20:41:00 +0000296 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000297 // Name lookup for ordinary names and tag names in C++ requires
298 // looking into scopes that aren't strictly lexical, and
299 // therefore we walk through the context as well as walking
300 // through the scopes.
301 IdentifierResolver::iterator
302 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
303 IEnd = IdResolver.end();
304 for (; S; S = S->getParent()) {
305 // Check whether the IdResolver has anything in this scope.
306 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000307 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner093e31b2009-01-06 07:20:03 +0000308 if ((*I)->isInIdentifierNamespace(NS)) {
309 // Ignore non-namespace names if we're only looking for namespaces.
310 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
311 continue;
312
313 // We found something. Look for anything else in our scope
314 // with this same name and in an acceptable identifier
315 // namespace, so that we can construct an overload set if we
316 // need to.
317 IdentifierResolver::iterator LastI = I;
318 for (++LastI; LastI != IEnd; ++LastI) {
319 if (!(*LastI)->isInIdentifierNamespace(NS) ||
320 !S->isDeclScope(*LastI))
321 break;
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000322 }
Chris Lattner093e31b2009-01-06 07:20:03 +0000323 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000324 }
325 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000326
327 // If there is an entity associated with this scope, it's a
328 // DeclContext. We might need to perform qualified lookup into
329 // it.
330 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
331 while (Ctx && Ctx->isFunctionOrMethod())
332 Ctx = Ctx->getParent();
Douglas Gregor723d3332009-01-07 00:43:41 +0000333 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000334 // Look for declarations of this name in this scope.
Douglas Gregor39677622008-12-11 20:41:00 +0000335 DeclContext::lookup_const_iterator I, E;
336 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000337 // FIXME: Cache this result in the IdResolver
Chris Lattner093e31b2009-01-06 07:20:03 +0000338 if ((*I)->isInIdentifierNamespace(NS)) {
339 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
340 continue;
341 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000342 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000343 }
344
345 Ctx = Ctx->getParent();
346 }
347
Douglas Gregord8028382009-01-05 19:45:36 +0000348 if (!LookInParent && !Ctx->isTransparentContext())
Douglas Gregor8acb7272008-12-11 16:49:14 +0000349 return 0;
350 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000351 }
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000352
Chris Lattner4b009652007-07-25 00:24:17 +0000353 // If we didn't find a use of this identifier, and if the identifier
354 // corresponds to a compiler builtin, create the decl object for the builtin
355 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000356 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000357 IdentifierInfo *II = Name.getAsIdentifierInfo();
358 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000359 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000360 // If this is a builtin on this (or all) targets, create the decl.
361 if (unsigned BuiltinID = II->getBuiltinID())
362 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
363 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000364 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000365 // @interface and @compatibility_alias introduce typedef-like names.
366 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000367 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000368 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000369 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
370 if (IDI != ObjCInterfaceDecls.end())
371 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000372 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
373 if (I != ObjCAliasDecls.end())
374 return I->second->getClassInterface();
375 }
Chris Lattner4b009652007-07-25 00:24:17 +0000376 }
377 return 0;
378}
379
Chris Lattnera9c87f22008-05-05 22:18:14 +0000380void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000381 if (!Context.getBuiltinVaListType().isNull())
382 return;
383
384 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000385 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000386 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000387 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
388}
389
Chris Lattner4b009652007-07-25 00:24:17 +0000390/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
391/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000392ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
393 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000394 Builtin::ID BID = (Builtin::ID)bid;
395
Chris Lattnerb23469f2008-09-28 05:54:29 +0000396 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000397 InitBuiltinVaListType();
398
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000399 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000400 FunctionDecl *New = FunctionDecl::Create(Context,
401 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000402 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000403 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000404
Chris Lattnera9c87f22008-05-05 22:18:14 +0000405 // Create Decl objects for each parameter, adding them to the
406 // FunctionDecl.
407 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
408 llvm::SmallVector<ParmVarDecl*, 16> Params;
409 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
410 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
411 FT->getArgType(i), VarDecl::None, 0,
412 0));
413 New->setParams(&Params[0], Params.size());
414 }
415
416
417
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000418 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000419 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000420 return New;
421}
422
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000423/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
424/// everything from the standard library is defined.
425NamespaceDecl *Sema::GetStdNamespace() {
426 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000427 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000428 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattnerf0939602008-11-20 05:45:14 +0000429 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000430 0, Global, /*enableLazyBuiltinCreation=*/false);
431 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
432 }
433 return StdNamespace;
434}
435
Chris Lattner4b009652007-07-25 00:24:17 +0000436/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
437/// and scope as a previous declaration 'Old'. Figure out how to resolve this
438/// situation, merging decls or emitting diagnostics as appropriate.
439///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000440TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000441 // Allow multiple definitions for ObjC built-in typedefs.
442 // FIXME: Verify the underlying types are equivalent!
443 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000444 const IdentifierInfo *TypeID = New->getIdentifier();
445 switch (TypeID->getLength()) {
446 default: break;
447 case 2:
448 if (!TypeID->isStr("id"))
449 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000450 Context.setObjCIdType(New);
451 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000452 case 5:
453 if (!TypeID->isStr("Class"))
454 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000455 Context.setObjCClassType(New);
456 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000457 case 3:
458 if (!TypeID->isStr("SEL"))
459 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000460 Context.setObjCSelType(New);
461 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000462 case 8:
463 if (!TypeID->isStr("Protocol"))
464 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000465 Context.setObjCProtoType(New->getUnderlyingType());
466 return New;
467 }
468 // Fall through - the typedef name was not a builtin type.
469 }
Chris Lattner4b009652007-07-25 00:24:17 +0000470 // Verify the old decl was also a typedef.
471 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
472 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000473 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000474 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000475 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000476 return New;
477 }
478
Chris Lattnerbef8d622008-07-25 18:44:27 +0000479 // If the typedef types are not identical, reject them in all languages and
480 // with any extensions enabled.
481 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
482 Context.getCanonicalType(Old->getUnderlyingType()) !=
483 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000484 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000485 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner1336cab2008-11-23 23:12:31 +0000486 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerbef8d622008-07-25 18:44:27 +0000487 return Old;
488 }
489
Eli Friedman324d5032008-06-11 06:20:39 +0000490 if (getLangOptions().Microsoft) return New;
491
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000492 // C++ [dcl.typedef]p2:
493 // In a given non-class scope, a typedef specifier can be used to
494 // redefine the name of any type declared in that scope to refer
495 // to the type to which it already refers.
496 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
497 return New;
498
499 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000500 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
501 // *either* declaration is in a system header. The code below implements
502 // this adhoc compatibility rule. FIXME: The following code will not
503 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000504 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
505 SourceManager &SrcMgr = Context.getSourceManager();
506 if (SrcMgr.isInSystemHeader(Old->getLocation()))
507 return New;
508 if (SrcMgr.isInSystemHeader(New->getLocation()))
509 return New;
510 }
Eli Friedman324d5032008-06-11 06:20:39 +0000511
Chris Lattnerb1753422008-11-23 21:45:46 +0000512 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000513 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000514 return New;
515}
516
Chris Lattner6953a072008-06-26 18:38:35 +0000517/// DeclhasAttr - returns true if decl Declaration already has the target
518/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000519static bool DeclHasAttr(const Decl *decl, const Attr *target) {
520 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
521 if (attr->getKind() == target->getKind())
522 return true;
523
524 return false;
525}
526
527/// MergeAttributes - append attributes from the Old decl to the New one.
528static void MergeAttributes(Decl *New, Decl *Old) {
529 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
530
Chris Lattner402b3372008-03-03 03:28:21 +0000531 while (attr) {
532 tmp = attr;
533 attr = attr->getNext();
534
535 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000536 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000537 New->addAttr(tmp);
538 } else {
539 tmp->setNext(0);
540 delete(tmp);
541 }
542 }
Nuno Lopes77654342008-06-01 22:53:53 +0000543
544 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000545}
546
Chris Lattner3e254fb2008-04-08 04:40:51 +0000547/// MergeFunctionDecl - We just parsed a function 'New' from
548/// declarator D which has the same name and scope as a previous
549/// declaration 'Old'. Figure out how to resolve this situation,
550/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000551/// Redeclaration will be set true if this New is a redeclaration OldD.
552///
553/// In C++, New and Old must be declarations that are not
554/// overloaded. Use IsOverload to determine whether New and Old are
555/// overloaded, and to select the Old declaration that New should be
556/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000557FunctionDecl *
558Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 assert(!isa<OverloadedFunctionDecl>(OldD) &&
560 "Cannot merge with an overloaded function declaration");
561
Douglas Gregor42214c52008-04-21 02:02:58 +0000562 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000563 // Verify the old decl was also a function.
564 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
565 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000566 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000567 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000568 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000569 return New;
570 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571
572 // Determine whether the previous declaration was a definition,
573 // implicit declaration, or a declaration.
574 diag::kind PrevDiag;
575 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000576 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000577 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000578 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000579 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000580 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000581
Chris Lattner42a21742008-04-06 23:10:54 +0000582 QualType OldQType = Context.getCanonicalType(Old->getType());
583 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000584
Douglas Gregord2baafd2008-10-21 16:13:35 +0000585 if (getLangOptions().CPlusPlus) {
586 // (C++98 13.1p2):
587 // Certain function declarations cannot be overloaded:
588 // -- Function declarations that differ only in the return type
589 // cannot be overloaded.
590 QualType OldReturnType
591 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
592 QualType NewReturnType
593 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
594 if (OldReturnType != NewReturnType) {
595 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
596 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000597 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000598 return New;
599 }
600
601 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
602 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
603 if (OldMethod && NewMethod) {
604 // -- Member function declarations with the same name and the
605 // same parameter types cannot be overloaded if any of them
606 // is a static member function declaration.
607 if (OldMethod->isStatic() || NewMethod->isStatic()) {
608 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
609 Diag(Old->getLocation(), PrevDiag);
610 return New;
611 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000612
613 // C++ [class.mem]p1:
614 // [...] A member shall not be declared twice in the
615 // member-specification, except that a nested class or member
616 // class template can be declared and then later defined.
617 if (OldMethod->getLexicalDeclContext() ==
618 NewMethod->getLexicalDeclContext()) {
619 unsigned NewDiag;
620 if (isa<CXXConstructorDecl>(OldMethod))
621 NewDiag = diag::err_constructor_redeclared;
622 else if (isa<CXXDestructorDecl>(NewMethod))
623 NewDiag = diag::err_destructor_redeclared;
624 else if (isa<CXXConversionDecl>(NewMethod))
625 NewDiag = diag::err_conv_function_redeclared;
626 else
627 NewDiag = diag::err_member_redeclared;
628
629 Diag(New->getLocation(), NewDiag);
630 Diag(Old->getLocation(), PrevDiag);
631 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000632 }
633
634 // (C++98 8.3.5p3):
635 // All declarations for a function shall agree exactly in both the
636 // return type and the parameter-type-list.
637 if (OldQType == NewQType) {
638 // We have a redeclaration.
639 MergeAttributes(New, Old);
640 Redeclaration = true;
641 return MergeCXXFunctionDecl(New, Old);
642 }
643
644 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000645 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000646
647 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000648 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000649 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000650 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000651 MergeAttributes(New, Old);
652 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000653 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000654 }
Chris Lattner1470b072007-11-06 06:07:26 +0000655
Steve Naroff6c9e7922008-01-16 15:01:34 +0000656 // A function that has already been declared has been redeclared or defined
657 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000658
Chris Lattner4b009652007-07-25 00:24:17 +0000659 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
660 // TODO: This is totally simplistic. It should handle merging functions
661 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000662 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000663 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000664 return New;
665}
666
Steve Naroffb5e78152008-08-08 17:50:35 +0000667/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000668static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000669 if (VD->isFileVarDecl())
670 return (!VD->getInit() &&
671 (VD->getStorageClass() == VarDecl::None ||
672 VD->getStorageClass() == VarDecl::Static));
673 return false;
674}
675
676/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
677/// when dealing with C "tentative" external object definitions (C99 6.9.2).
678void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
679 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000680 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000681
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000682 // FIXME: I don't this will actually see all of the
683 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000684 for (IdentifierResolver::iterator
685 I = IdResolver.begin(VD->getIdentifier(),
686 VD->getDeclContext(), false/*LookInParentCtx*/),
687 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000688 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000689 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
690
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000691 // Handle the following case:
692 // int a[10];
693 // int a[]; - the code below makes sure we set the correct type.
694 // int a[11]; - this is an error, size isn't 10.
695 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
696 OldDecl->getType()->isConstantArrayType())
697 VD->setType(OldDecl->getType());
698
Steve Naroffb5e78152008-08-08 17:50:35 +0000699 // Check for "tentative" definitions. We can't accomplish this in
700 // MergeVarDecl since the initializer hasn't been attached.
701 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
702 continue;
703
704 // Handle __private_extern__ just like extern.
705 if (OldDecl->getStorageClass() != VarDecl::Extern &&
706 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
707 VD->getStorageClass() != VarDecl::Extern &&
708 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000709 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000710 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000711 }
712 }
713 }
714}
715
Chris Lattner4b009652007-07-25 00:24:17 +0000716/// MergeVarDecl - We just parsed a variable 'New' which has the same name
717/// and scope as a previous declaration 'Old'. Figure out how to resolve this
718/// situation, merging decls or emitting diagnostics as appropriate.
719///
Steve Naroffb5e78152008-08-08 17:50:35 +0000720/// Tentative definition rules (C99 6.9.2p2) are checked by
721/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
722/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000723///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000724VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000725 // Verify the old decl was also a variable.
726 VarDecl *Old = dyn_cast<VarDecl>(OldD);
727 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000728 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000729 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000730 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000731 return New;
732 }
Chris Lattner402b3372008-03-03 03:28:21 +0000733
734 MergeAttributes(New, Old);
735
Chris Lattner4b009652007-07-25 00:24:17 +0000736 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000737 QualType OldCType = Context.getCanonicalType(Old->getType());
738 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000739 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000740 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000741 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000742 return New;
743 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000744 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
745 if (New->getStorageClass() == VarDecl::Static &&
746 (Old->getStorageClass() == VarDecl::None ||
747 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000748 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000749 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000750 return New;
751 }
752 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
753 if (New->getStorageClass() != VarDecl::Static &&
754 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000755 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000756 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000757 return New;
758 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000759 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
760 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000761 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000762 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000763 }
764 return New;
765}
766
Chris Lattner3e254fb2008-04-08 04:40:51 +0000767/// CheckParmsForFunctionDef - Check that the parameters of the given
768/// function are appropriate for the definition of a function. This
769/// takes care of any checks that cannot be performed on the
770/// declaration itself, e.g., that the types of each of the function
771/// parameters are complete.
772bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
773 bool HasInvalidParm = false;
774 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
775 ParmVarDecl *Param = FD->getParamDecl(p);
776
777 // C99 6.7.5.3p4: the parameters in a parameter type list in a
778 // function declarator that is part of a function definition of
779 // that function shall not have incomplete type.
780 if (Param->getType()->isIncompleteType() &&
781 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000782 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000783 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000784 Param->setInvalidDecl();
785 HasInvalidParm = true;
786 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000787
788 // C99 6.9.1p5: If the declarator includes a parameter type list, the
789 // declaration of each parameter shall include an identifier.
790 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
791 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000792 }
793
794 return HasInvalidParm;
795}
796
Chris Lattner4b009652007-07-25 00:24:17 +0000797/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
798/// no declarator (e.g. "struct foo;") is parsed.
799Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redlb7605e82008-12-28 15:28:59 +0000800 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
801 if (!DS.isMissingDeclaratorOk()) {
802 // FIXME: This diagnostic is emitted even when various previous
803 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
804 // DeclSpec has no means of communicating this information, and the
805 // responsible parser functions are quite far apart.
806 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
807 << DS.getSourceRange();
808 return 0;
809 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000810
811 TagDecl *Tag
812 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
813 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
814 if (!Record->getDeclName() && Record->isDefinition() &&
815 !Record->isInvalidDecl())
816 return BuildAnonymousStructOrUnion(S, DS, Record);
817 }
Sebastian Redlb7605e82008-12-28 15:28:59 +0000818
Douglas Gregor723d3332009-01-07 00:43:41 +0000819 return Tag;
820}
821
822/// InjectAnonymousStructOrUnionMembers - Inject the members of the
823/// anonymous struct or union AnonRecord into the owning context Owner
824/// and scope S. This routine will be invoked just after we realize
825/// that an unnamed union or struct is actually an anonymous union or
826/// struct, e.g.,
827///
828/// @code
829/// union {
830/// int i;
831/// float f;
832/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
833/// // f into the surrounding scope.x
834/// @endcode
835///
836/// This routine is recursive, injecting the names of nested anonymous
837/// structs/unions into the owning context and scope as well.
838bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
839 RecordDecl *AnonRecord) {
840 bool Invalid = false;
841 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
842 FEnd = AnonRecord->field_end();
843 F != FEnd; ++F) {
844 if ((*F)->getDeclName()) {
845 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
846 S, Owner, false, false, false);
847 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
848 // C++ [class.union]p2:
849 // The names of the members of an anonymous union shall be
850 // distinct from the names of any other entity in the
851 // scope in which the anonymous union is declared.
852 unsigned diagKind
853 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
854 : diag::err_anonymous_struct_member_redecl;
855 Diag((*F)->getLocation(), diagKind)
856 << (*F)->getDeclName();
857 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
858 Invalid = true;
859 } else {
860 // C++ [class.union]p2:
861 // For the purpose of name lookup, after the anonymous union
862 // definition, the members of the anonymous union are
863 // considered to have been defined in the scope in which the
864 // anonymous union is declared.
865 Owner->insert(Context, *F);
866 S->AddDecl(*F);
867 IdResolver.AddDecl(*F);
868 }
869 } else if (const RecordType *InnerRecordType
870 = (*F)->getType()->getAsRecordType()) {
871 RecordDecl *InnerRecord = InnerRecordType->getDecl();
872 if (InnerRecord->isAnonymousStructOrUnion())
873 Invalid = Invalid ||
874 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
875 }
876 }
877
878 return Invalid;
879}
880
881/// ActOnAnonymousStructOrUnion - Handle the declaration of an
882/// anonymous structure or union. Anonymous unions are a C++ feature
883/// (C++ [class.union]) and a GNU C extension; anonymous structures
884/// are a GNU C and GNU C++ extension.
885Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
886 RecordDecl *Record) {
887 DeclContext *Owner = Record->getDeclContext();
888
889 // Diagnose whether this anonymous struct/union is an extension.
890 if (Record->isUnion() && !getLangOptions().CPlusPlus)
891 Diag(Record->getLocation(), diag::ext_anonymous_union);
892 else if (!Record->isUnion())
893 Diag(Record->getLocation(), diag::ext_anonymous_struct);
894
895 // C and C++ require different kinds of checks for anonymous
896 // structs/unions.
897 bool Invalid = false;
898 if (getLangOptions().CPlusPlus) {
899 const char* PrevSpec = 0;
900 // C++ [class.union]p3:
901 // Anonymous unions declared in a named namespace or in the
902 // global namespace shall be declared static.
903 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
904 (isa<TranslationUnitDecl>(Owner) ||
905 (isa<NamespaceDecl>(Owner) &&
906 cast<NamespaceDecl>(Owner)->getDeclName()))) {
907 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
908 Invalid = true;
909
910 // Recover by adding 'static'.
911 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
912 }
913 // C++ [class.union]p3:
914 // A storage class is not allowed in a declaration of an
915 // anonymous union in a class scope.
916 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
917 isa<RecordDecl>(Owner)) {
918 Diag(DS.getStorageClassSpecLoc(),
919 diag::err_anonymous_union_with_storage_spec);
920 Invalid = true;
921
922 // Recover by removing the storage specifier.
923 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
924 PrevSpec);
925 }
926 } else {
927 // FIXME: Check GNU C semantics
928 }
929
930 if (!Record->isUnion() && !Owner->isRecord()) {
931 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
932 Invalid = true;
933 }
934
935 // Create a declaration for this anonymous struct/union.
936 ScopedDecl *Anon = 0;
937 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
938 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
939 /*IdentifierInfo=*/0,
940 Context.getTypeDeclType(Record),
941 /*BitWidth=*/0, /*Mutable=*/false,
942 /*PrevDecl=*/0);
943 } else {
944 VarDecl::StorageClass SC;
945 switch (DS.getStorageClassSpec()) {
946 default: assert(0 && "Unknown storage class!");
947 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
948 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
949 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
950 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
951 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
952 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
953 case DeclSpec::SCS_mutable:
954 // mutable can only appear on non-static class members, so it's always
955 // an error here
956 Diag(Record->getLocation(), diag::err_mutable_nonmember);
957 Invalid = true;
958 SC = VarDecl::None;
959 break;
960 }
961
962 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
963 /*IdentifierInfo=*/0,
964 Context.getTypeDeclType(Record),
965 SC, /*FIXME:LastDeclarator=*/0,
966 DS.getSourceRange().getBegin());
967 }
968
969 // Add the anonymous struct/union object to the current
970 // context. We'll be referencing this object when we refer to one of
971 // its members.
972 Owner->addDecl(Context, Anon);
973
974 // Inject the members of the anonymous struct/union into the owning
975 // context and into the identifier resolver chain for name lookup
976 // purposes.
977 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
978
979 // Mark this as an anonymous struct/union type. Note that we do not
980 // do this until after we have already checked and injected the
981 // members of this anonymous struct/union type, because otherwise
982 // the members could be injected twice: once by DeclContext when it
983 // builds its lookup table, and once by
984 // InjectAnonymousStructOrUnionMembers.
985 Record->setAnonymousStructOrUnion(true);
986
987 if (Invalid)
988 Anon->setInvalidDecl();
989
990 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000991}
992
Steve Narofff0b23542008-01-10 22:15:12 +0000993bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000994 // Get the type before calling CheckSingleAssignmentConstraints(), since
995 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000996 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000997
998 if (getLangOptions().CPlusPlus)
999 return PerformCopyInitialization(Init, DeclType, "initializing");
1000
Chris Lattner005ed752008-01-04 18:04:52 +00001001 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1002 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1003 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001004}
1005
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001006bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001007 const ArrayType *AT = Context.getAsArrayType(DeclT);
1008
1009 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001010 // C99 6.7.8p14. We have an array of character type with unknown size
1011 // being initialized to a string literal.
1012 llvm::APSInt ConstVal(32);
1013 ConstVal = strLiteral->getByteLength() + 1;
1014 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001015 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001016 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001017 } else {
1018 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001019 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001020 // FIXME: Avoid truncation for 64-bit length strings.
1021 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001022 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001023 diag::warn_initializer_string_for_char_array_too_long)
1024 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001025 }
1026 // Set type from "char *" to "constant array of char".
1027 strLiteral->setType(DeclT);
1028 // For now, we always return false (meaning success).
1029 return false;
1030}
1031
1032StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001033 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001034 if (AT && AT->getElementType()->isCharType()) {
1035 return dyn_cast<StringLiteral>(Init);
1036 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001037 return 0;
1038}
1039
Douglas Gregor6428e762008-11-05 15:29:30 +00001040bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1041 SourceLocation InitLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001042 DeclarationName InitEntity) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001043 if (DeclType->isDependentType() || Init->isTypeDependent())
1044 return false;
1045
Douglas Gregor81c29152008-10-29 00:13:59 +00001046 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001047 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001048 // (8.3.2), shall be initialized by an object, or function, of
1049 // type T or by an object that can be converted into a T.
1050 if (DeclType->isReferenceType())
1051 return CheckReferenceInit(Init, DeclType);
1052
Steve Naroff8e9337f2008-01-21 23:53:58 +00001053 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1054 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001055 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001056 return Diag(InitLoc, diag::err_variable_object_no_init)
1057 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001058
Steve Naroffcb69fb72007-12-10 22:44:33 +00001059 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1060 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001061 // FIXME: Handle wide strings
1062 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1063 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001064
Douglas Gregor6428e762008-11-05 15:29:30 +00001065 // C++ [dcl.init]p14:
1066 // -- If the destination type is a (possibly cv-qualified) class
1067 // type:
1068 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1069 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1070 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1071
1072 // -- If the initialization is direct-initialization, or if it is
1073 // copy-initialization where the cv-unqualified version of the
1074 // source type is the same class as, or a derived class of, the
1075 // class of the destination, constructors are considered.
1076 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1077 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1078 CXXConstructorDecl *Constructor
1079 = PerformInitializationByConstructor(DeclType, &Init, 1,
1080 InitLoc, Init->getSourceRange(),
1081 InitEntity, IK_Copy);
1082 return Constructor == 0;
1083 }
1084
1085 // -- Otherwise (i.e., for the remaining copy-initialization
1086 // cases), user-defined conversion sequences that can
1087 // convert from the source type to the destination type or
1088 // (when a conversion function is used) to a derived class
1089 // thereof are enumerated as described in 13.3.1.4, and the
1090 // best one is chosen through overload resolution
1091 // (13.3). If the conversion cannot be done or is
1092 // ambiguous, the initialization is ill-formed. The
1093 // function selected is called with the initializer
1094 // expression as its argument; if the function is a
1095 // constructor, the call initializes a temporary of the
1096 // destination type.
1097 // FIXME: We're pretending to do copy elision here; return to
1098 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001099 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001100 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001101
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001102 if (InitEntity)
1103 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1104 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1105 << Init->getType() << Init->getSourceRange();
1106 else
1107 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1108 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1109 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001110 }
1111
Steve Naroffb2f72412008-09-29 20:07:05 +00001112 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001113 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001114 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1115 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001116
Steve Narofff0b23542008-01-10 22:15:12 +00001117 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +00001118 } else if (getLangOptions().CPlusPlus) {
1119 // C++ [dcl.init]p14:
1120 // [...] If the class is an aggregate (8.5.1), and the initializer
1121 // is a brace-enclosed list, see 8.5.1.
1122 //
1123 // Note: 8.5.1 is handled below; here, we diagnose the case where
1124 // we have an initializer list and a destination type that is not
1125 // an aggregate.
1126 // FIXME: In C++0x, this is yet another form of initialization.
1127 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1128 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1129 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001130 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001131 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001132 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001133 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001134
Steve Naroffc4d4a482008-05-01 22:18:59 +00001135 InitListChecker CheckInitList(this, InitList, DeclType);
1136 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +00001137}
1138
Douglas Gregor6704b312008-11-17 22:58:34 +00001139/// GetNameForDeclarator - Determine the full declaration name for the
1140/// given Declarator.
1141DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1142 switch (D.getKind()) {
1143 case Declarator::DK_Abstract:
1144 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1145 return DeclarationName();
1146
1147 case Declarator::DK_Normal:
1148 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1149 return DeclarationName(D.getIdentifier());
1150
1151 case Declarator::DK_Constructor: {
1152 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1153 Ty = Context.getCanonicalType(Ty);
1154 return Context.DeclarationNames.getCXXConstructorName(Ty);
1155 }
1156
1157 case Declarator::DK_Destructor: {
1158 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1159 Ty = Context.getCanonicalType(Ty);
1160 return Context.DeclarationNames.getCXXDestructorName(Ty);
1161 }
1162
1163 case Declarator::DK_Conversion: {
1164 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1165 Ty = Context.getCanonicalType(Ty);
1166 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1167 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001168
1169 case Declarator::DK_Operator:
1170 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1171 return Context.DeclarationNames.getCXXOperatorName(
1172 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001173 }
1174
1175 assert(false && "Unknown name kind");
1176 return DeclarationName();
1177}
1178
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001179/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1180/// functions Declaration and Definition are "nearly" matching. This
1181/// heuristic is used to improve diagnostics in the case where an
1182/// out-of-line member function definition doesn't match any
1183/// declaration within the class.
1184static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1185 FunctionDecl *Declaration,
1186 FunctionDecl *Definition) {
1187 if (Declaration->param_size() != Definition->param_size())
1188 return false;
1189 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1190 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1191 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1192
1193 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1194 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1195 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1196 return false;
1197 }
1198
1199 return true;
1200}
1201
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001202Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001203Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1204 bool IsFunctionDefinition) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001205 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001206 DeclarationName Name = GetNameForDeclarator(D);
1207
Chris Lattner4b009652007-07-25 00:24:17 +00001208 // All of these full declarators require an identifier. If it doesn't have
1209 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001210 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001211 if (!D.getInvalidType()) // Reject this if we think it is valid.
1212 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001213 diag::err_declarator_need_ident)
1214 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001215 return 0;
1216 }
1217
Chris Lattnera7549902007-08-26 06:24:45 +00001218 // The scope passed in may not be a decl scope. Zip up the scope tree until
1219 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001220 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1221 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001222 S = S->getParent();
1223
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001224 DeclContext *DC;
1225 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001226 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001227 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001228
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001229 // See if this is a redefinition of a variable in the same scope.
1230 if (!D.getCXXScopeSpec().isSet()) {
1231 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +00001232 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001233 } else { // Something like "int foo::x;"
1234 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +00001235 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001236
1237 // C++ 7.3.1.2p2:
1238 // Members (including explicit specializations of templates) of a named
1239 // namespace can also be defined outside that namespace by explicit
1240 // qualification of the name being defined, provided that the entity being
1241 // defined was already declared in the namespace and the definition appears
1242 // after the point of declaration in a namespace that encloses the
1243 // declarations namespace.
1244 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001245 // Note that we only check the context at this point. We don't yet
1246 // have enough information to make sure that PrevDecl is actually
1247 // the declaration we want to match. For example, given:
1248 //
Douglas Gregor98341042008-12-12 08:25:50 +00001249 // class X {
1250 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001251 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001252 // };
1253 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001254 // void X::f(int) { } // ill-formed
1255 //
1256 // In this case, PrevDecl will point to the overload set
1257 // containing the two f's declared in X, but neither of them
1258 // matches.
1259 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001260 // The qualifying scope doesn't enclose the original declaration.
1261 // Emit diagnostic based on current scope.
1262 SourceLocation L = D.getIdentifierLoc();
1263 SourceRange R = D.getCXXScopeSpec().getRange();
1264 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001265 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001266 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001267 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001268 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001269 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001270 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001271 }
1272 }
1273
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001274 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001275 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001276 InvalidDecl = InvalidDecl
1277 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001278 // Just pretend that we didn't see the previous declaration.
1279 PrevDecl = 0;
1280 }
1281
Douglas Gregor1d661552008-04-13 21:07:44 +00001282 // In C++, the previous declaration we find might be a tag type
1283 // (class or enum). In this case, the new declaration will hide the
1284 // tag type.
1285 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1286 PrevDecl = 0;
1287
Chris Lattner82bb4792007-11-14 06:34:38 +00001288 QualType R = GetTypeForDeclarator(D, S);
1289 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1290
Chris Lattner4b009652007-07-25 00:24:17 +00001291 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001292 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1293 if (D.getCXXScopeSpec().isSet()) {
1294 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1295 << D.getCXXScopeSpec().getRange();
1296 InvalidDecl = true;
1297 // Pretend we didn't see the scope specifier.
1298 DC = 0;
1299 }
1300
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001301 // Check that there are no default arguments (C++ only).
1302 if (getLangOptions().CPlusPlus)
1303 CheckExtraCXXDefaultArguments(D);
1304
Chris Lattner82bb4792007-11-14 06:34:38 +00001305 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +00001306 if (!NewTD) return 0;
1307
1308 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001309 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +00001310 // Merge the decl with the existing one if appropriate. If the decl is
1311 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001312 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001313 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1314 if (NewTD == 0) return 0;
1315 }
1316 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001317 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001318 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1319 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +00001320 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00001321 if (NewTD->getUnderlyingType()->isVariableArrayType())
1322 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1323 else
1324 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1325
Steve Naroff5eb879b2007-08-31 17:20:07 +00001326 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001327 }
1328 }
Chris Lattner82bb4792007-11-14 06:34:38 +00001329 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +00001330 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +00001331 switch (D.getDeclSpec().getStorageClassSpec()) {
1332 default: assert(0 && "Unknown storage class!");
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001333 case DeclSpec::SCS_auto:
Chris Lattner4b009652007-07-25 00:24:17 +00001334 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001335 case DeclSpec::SCS_mutable:
Chris Lattner4bfd2232008-11-24 06:25:27 +00001336 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001337 InvalidDecl = true;
1338 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001339 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1340 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1341 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +00001342 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +00001343 }
1344
Chris Lattner4c7802b2008-03-15 21:24:04 +00001345 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001346 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001347 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1348
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001349 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001350 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001351 // This is a C++ constructor declaration.
Douglas Gregor723d3332009-01-07 00:43:41 +00001352 assert(DC->isRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001353 "Constructors can only be declared in a member context");
1354
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001355 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001356
1357 // Create the new declaration
1358 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001359 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001360 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001361 isExplicit, isInline,
1362 /*isImplicitlyDeclared=*/false);
1363
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001364 if (InvalidDecl)
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001365 NewFD->setInvalidDecl();
1366 } else if (D.getKind() == Declarator::DK_Destructor) {
1367 // This is a C++ destructor declaration.
Douglas Gregor723d3332009-01-07 00:43:41 +00001368 if (DC->isRecord()) {
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001369 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001370
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001371 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001372 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001373 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001374 isInline,
1375 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001376
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001377 if (InvalidDecl)
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001378 NewFD->setInvalidDecl();
1379 } else {
1380 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001381
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001382 // Create a FunctionDecl to satisfy the function definition parsing
1383 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001384 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001385 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001386 // FIXME: Move to DeclGroup...
1387 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001388 InvalidDecl = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001389 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001390 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001391 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001392 if (!DC->isRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001393 Diag(D.getIdentifierLoc(),
1394 diag::err_conv_function_not_member);
1395 return 0;
1396 } else {
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001397 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001398
Douglas Gregor853dd392008-12-26 15:00:45 +00001399 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001400 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001401 isInline, isExplicit);
1402
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001403 if (InvalidDecl)
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001404 NewFD->setInvalidDecl();
1405 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001406 } else if (DC->isRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001407 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001408 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001409 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001410 (SC == FunctionDecl::Static), isInline,
1411 LastDeclarator);
1412 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001413 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001414 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001415 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +00001416 // FIXME: Move to DeclGroup...
1417 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001418 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001419
Douglas Gregorb9213832008-12-15 21:24:18 +00001420 // Set the lexical context. If the declarator has a C++
1421 // scope specifier, the lexical context will be different
1422 // from the semantic context.
1423 NewFD->setLexicalDeclContext(CurContext);
1424
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001425 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001426 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001427 // The parser guarantees this is a string.
1428 StringLiteral *SE = cast<StringLiteral>(E);
1429 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1430 SE->getByteLength())));
1431 }
1432
Chris Lattner3e254fb2008-04-08 04:40:51 +00001433 // Copy the parameter declarations from the declarator D to
1434 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +00001435 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001436 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1437
1438 // Create Decl objects for each parameter, adding them to the
1439 // FunctionDecl.
1440 llvm::SmallVector<ParmVarDecl*, 16> Params;
1441
1442 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1443 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001444 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001445 // We let through "const void" here because Sema::GetTypeForDeclarator
1446 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001447 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1448 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001449 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1450 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001451 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1452
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001453 // In C++, the empty parameter-type-list must be spelled "void"; a
1454 // typedef of void is not permitted.
1455 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001456 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001457 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1458 }
Eli Friedman769e7302008-08-25 21:31:01 +00001459 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001460 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1461 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1462 }
1463
1464 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001465 } else if (R->getAsTypedefType()) {
1466 // When we're declaring a function with a typedef, as in the
1467 // following example, we'll need to synthesize (unnamed)
1468 // parameters for use in the declaration.
1469 //
1470 // @code
1471 // typedef void fn(int);
1472 // fn f;
1473 // @endcode
1474 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1475 if (!FT) {
1476 // This is a typedef of a function with no prototype, so we
1477 // don't need to do anything.
1478 } else if ((FT->getNumArgs() == 0) ||
1479 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1480 FT->getArgType(0)->isVoidType())) {
1481 // This is a zero-argument function. We don't need to do anything.
1482 } else {
1483 // Synthesize a parameter for each argument type.
1484 llvm::SmallVector<ParmVarDecl*, 16> Params;
1485 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1486 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001487 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001488 SourceLocation(), 0,
1489 *ArgType, VarDecl::None,
1490 0, 0));
1491 }
1492
1493 NewFD->setParams(&Params[0], Params.size());
1494 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001495 }
1496
Douglas Gregor605de8d2008-12-16 21:30:33 +00001497 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1498 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001499 else if (isa<CXXDestructorDecl>(NewFD)) {
1500 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1501 Record->setUserDeclaredDestructor(true);
1502 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1503 // user-defined destructor.
1504 Record->setPOD(false);
1505 } else if (CXXConversionDecl *Conversion =
1506 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001507 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001508
Douglas Gregore60e5d32008-11-06 22:13:31 +00001509 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1510 if (NewFD->isOverloadedOperator() &&
1511 CheckOverloadedOperatorDeclaration(NewFD))
1512 NewFD->setInvalidDecl();
1513
Steve Narofff8a09432008-01-09 23:34:55 +00001514 // Merge the decl with the existing one if appropriate. Since C functions
1515 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001516 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001517 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001518 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001519
1520 // If C++, determine whether NewFD is an overload of PrevDecl or
1521 // a declaration that requires merging. If it's an overload,
1522 // there's no more work to do here; we'll just add the new
1523 // function to the scope.
1524 OverloadedFunctionDecl::function_iterator MatchedDecl;
1525 if (!getLangOptions().CPlusPlus ||
1526 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1527 Decl *OldDecl = PrevDecl;
1528
1529 // If PrevDecl was an overloaded function, extract the
1530 // FunctionDecl that matched.
1531 if (isa<OverloadedFunctionDecl>(PrevDecl))
1532 OldDecl = *MatchedDecl;
1533
1534 // NewFD and PrevDecl represent declarations that need to be
1535 // merged.
1536 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1537
1538 if (NewFD == 0) return 0;
1539 if (Redeclaration) {
1540 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1541
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001542 // An out-of-line member function declaration must also be a
1543 // definition (C++ [dcl.meaning]p1).
1544 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1545 !InvalidDecl) {
1546 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1547 << D.getCXXScopeSpec().getRange();
1548 NewFD->setInvalidDecl();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001549 }
1550 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001551 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001552
1553 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1554 // The user tried to provide an out-of-line definition for a
1555 // member function, but there was no such member function
1556 // declared (C++ [class.mfct]p2). For example:
1557 //
1558 // class X {
1559 // void f() const;
1560 // };
1561 //
1562 // void X::f() { } // ill-formed
1563 //
1564 // Complain about this problem, and attempt to suggest close
1565 // matches (e.g., those that differ only in cv-qualifiers and
1566 // whether the parameter types are references).
1567 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1568 << cast<CXXRecordDecl>(DC)->getDeclName()
1569 << D.getCXXScopeSpec().getRange();
1570 InvalidDecl = true;
1571
1572 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1573 if (!PrevDecl) {
1574 // Nothing to suggest.
1575 } else if (OverloadedFunctionDecl *Ovl
1576 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1577 for (OverloadedFunctionDecl::function_iterator
1578 Func = Ovl->function_begin(),
1579 FuncEnd = Ovl->function_end();
1580 Func != FuncEnd; ++Func) {
1581 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1582 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1583
1584 }
1585 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1586 // Suggest this no matter how mismatched it is; it's the only
1587 // thing we have.
1588 unsigned diag;
1589 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1590 diag = diag::note_member_def_close_match;
1591 else if (Method->getBody())
1592 diag = diag::note_previous_definition;
1593 else
1594 diag = diag::note_previous_declaration;
1595 Diag(Method->getLocation(), diag);
1596 }
1597
1598 PrevDecl = 0;
1599 }
Chris Lattner4b009652007-07-25 00:24:17 +00001600 }
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00001601 // Handle attributes. We need to have merged decls when handling attributes
1602 // (for example to check for conflicts, etc).
1603 ProcessDeclAttributes(NewFD, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001604 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001605
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001606 if (getLangOptions().CPlusPlus) {
1607 // In C++, check default arguments now that we have merged decls.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001608 CheckCXXDefaultArguments(NewFD);
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001609
1610 // An out-of-line member function declaration must also be a
1611 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001612 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001613 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1614 << D.getCXXScopeSpec().getRange();
1615 InvalidDecl = true;
1616 }
1617 }
Chris Lattner4b009652007-07-25 00:24:17 +00001618 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001619 // Check that there are no default arguments (C++ only).
1620 if (getLangOptions().CPlusPlus)
1621 CheckExtraCXXDefaultArguments(D);
1622
Ted Kremenek42730c52008-01-07 19:49:32 +00001623 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner65cae292008-11-19 08:23:25 +00001624 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1625 << D.getIdentifier();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001626 InvalidDecl = true;
1627 }
Chris Lattner4b009652007-07-25 00:24:17 +00001628
1629 VarDecl *NewVD;
1630 VarDecl::StorageClass SC;
1631 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001632 default: assert(0 && "Unknown storage class!");
1633 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1634 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1635 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1636 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1637 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1638 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001639 case DeclSpec::SCS_mutable:
1640 // mutable can only appear on non-static class members, so it's always
1641 // an error here
1642 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1643 InvalidDecl = true;
Douglas Gregor538754e2008-12-01 22:46:22 +00001644 SC = VarDecl::None;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001645 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001646 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001647
1648 IdentifierInfo *II = Name.getAsIdentifierInfo();
1649 if (!II) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001650 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1651 << Name.getAsString();
Douglas Gregor6704b312008-11-17 22:58:34 +00001652 return 0;
1653 }
1654
Douglas Gregor723d3332009-01-07 00:43:41 +00001655 if (DC->isRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001656 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001657 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001658 D.getIdentifierLoc(), II,
1659 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001660 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001661 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001662 if (S->getFnParent() == 0) {
1663 // C99 6.9p2: The storage-class specifiers auto and register shall not
1664 // appear in the declaration specifiers in an external declaration.
1665 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattner4bfd2232008-11-24 06:25:27 +00001666 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001667 InvalidDecl = true;
1668 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001669 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001670 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1671 II, R, SC, LastDeclarator,
1672 // FIXME: Move to DeclGroup...
1673 D.getDeclSpec().getSourceRange().getBegin());
1674 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001675 }
Chris Lattner4b009652007-07-25 00:24:17 +00001676 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001677 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001678
Daniel Dunbarced89142008-08-06 00:03:29 +00001679 // Handle GNU asm-label extension (encoded as an attribute).
1680 if (Expr *E = (Expr*) D.getAsmLabel()) {
1681 // The parser guarantees this is a string.
1682 StringLiteral *SE = cast<StringLiteral>(E);
1683 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1684 SE->getByteLength())));
1685 }
1686
Nate Begemanea583262008-03-14 18:07:10 +00001687 // Emit an error if an address space was applied to decl with local storage.
1688 // This includes arrays of objects with address space qualifiers, but not
1689 // automatic variables that point to other address spaces.
1690 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001691 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1692 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1693 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001694 }
Steve Narofff8a09432008-01-09 23:34:55 +00001695 // Merge the decl with the existing one if appropriate. If the decl is
1696 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001697 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001698 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1699 // The user tried to define a non-static data member
1700 // out-of-line (C++ [dcl.meaning]p1).
1701 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1702 << D.getCXXScopeSpec().getRange();
1703 NewVD->Destroy(Context);
1704 return 0;
1705 }
1706
Chris Lattner4b009652007-07-25 00:24:17 +00001707 NewVD = MergeVarDecl(NewVD, PrevDecl);
1708 if (NewVD == 0) return 0;
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001709
1710 if (D.getCXXScopeSpec().isSet()) {
1711 // No previous declaration in the qualifying scope.
1712 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1713 << Name << D.getCXXScopeSpec().getRange();
1714 InvalidDecl = true;
1715 }
Chris Lattner4b009652007-07-25 00:24:17 +00001716 }
Chris Lattner4b009652007-07-25 00:24:17 +00001717 New = NewVD;
1718 }
1719
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001720 // Set the lexical context. If the declarator has a C++ scope specifier, the
1721 // lexical context will be different from the semantic context.
1722 New->setLexicalDeclContext(CurContext);
1723
Chris Lattner4b009652007-07-25 00:24:17 +00001724 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001725 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001726 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001727 // If any semantic error occurred, mark the decl as invalid.
1728 if (D.getInvalidType() || InvalidDecl)
1729 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001730
1731 return New;
1732}
1733
Steve Narofffc08f5e2008-10-27 11:34:16 +00001734void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001735 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1736 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001737}
1738
Eli Friedman02c22ce2008-05-20 13:48:25 +00001739bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1740 switch (Init->getStmtClass()) {
1741 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001742 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001743 return true;
1744 case Expr::ParenExprClass: {
1745 const ParenExpr* PE = cast<ParenExpr>(Init);
1746 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1747 }
1748 case Expr::CompoundLiteralExprClass:
1749 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001750 case Expr::DeclRefExprClass:
1751 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001752 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001753 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1754 if (VD->hasGlobalStorage())
1755 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001756 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001757 return true;
1758 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001759 if (isa<FunctionDecl>(D))
1760 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001761 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001762 return true;
1763 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001764 case Expr::MemberExprClass: {
1765 const MemberExpr *M = cast<MemberExpr>(Init);
1766 if (M->isArrow())
1767 return CheckAddressConstantExpression(M->getBase());
1768 return CheckAddressConstantExpressionLValue(M->getBase());
1769 }
1770 case Expr::ArraySubscriptExprClass: {
1771 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1772 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1773 return CheckAddressConstantExpression(ASE->getBase()) ||
1774 CheckArithmeticConstantExpression(ASE->getIdx());
1775 }
1776 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001777 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001778 return false;
1779 case Expr::UnaryOperatorClass: {
1780 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1781
1782 // C99 6.6p9
1783 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001784 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001785
Steve Narofffc08f5e2008-10-27 11:34:16 +00001786 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001787 return true;
1788 }
1789 }
1790}
1791
1792bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1793 switch (Init->getStmtClass()) {
1794 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001795 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001796 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001797 case Expr::ParenExprClass:
1798 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001799 case Expr::StringLiteralClass:
1800 case Expr::ObjCStringLiteralClass:
1801 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001802 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001803 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001804 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1805 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1806 Builtin::BI__builtin___CFStringMakeConstantString)
1807 return false;
1808
Steve Narofffc08f5e2008-10-27 11:34:16 +00001809 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001810 return true;
1811
Eli Friedman02c22ce2008-05-20 13:48:25 +00001812 case Expr::UnaryOperatorClass: {
1813 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1814
1815 // C99 6.6p9
1816 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1817 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1818
1819 if (Exp->getOpcode() == UnaryOperator::Extension)
1820 return CheckAddressConstantExpression(Exp->getSubExpr());
1821
Steve Narofffc08f5e2008-10-27 11:34:16 +00001822 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001823 return true;
1824 }
1825 case Expr::BinaryOperatorClass: {
1826 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1827 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1828
1829 Expr *PExp = Exp->getLHS();
1830 Expr *IExp = Exp->getRHS();
1831 if (IExp->getType()->isPointerType())
1832 std::swap(PExp, IExp);
1833
1834 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1835 return CheckAddressConstantExpression(PExp) ||
1836 CheckArithmeticConstantExpression(IExp);
1837 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001838 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001839 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001840 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001841 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1842 // Check for implicit promotion
1843 if (SubExpr->getType()->isFunctionType() ||
1844 SubExpr->getType()->isArrayType())
1845 return CheckAddressConstantExpressionLValue(SubExpr);
1846 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001847
1848 // Check for pointer->pointer cast
1849 if (SubExpr->getType()->isPointerType())
1850 return CheckAddressConstantExpression(SubExpr);
1851
Eli Friedman1fad3c62008-08-25 20:46:57 +00001852 if (SubExpr->getType()->isIntegralType()) {
1853 // Check for the special-case of a pointer->int->pointer cast;
1854 // this isn't standard, but some code requires it. See
1855 // PR2720 for an example.
1856 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1857 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1858 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1859 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1860 if (IntWidth >= PointerWidth) {
1861 return CheckAddressConstantExpression(SubCast->getSubExpr());
1862 }
1863 }
1864 }
1865 }
1866 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001867 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001868 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001869
Steve Narofffc08f5e2008-10-27 11:34:16 +00001870 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001871 return true;
1872 }
1873 case Expr::ConditionalOperatorClass: {
1874 // FIXME: Should we pedwarn here?
1875 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1876 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001877 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001878 return true;
1879 }
1880 if (CheckArithmeticConstantExpression(Exp->getCond()))
1881 return true;
1882 if (Exp->getLHS() &&
1883 CheckAddressConstantExpression(Exp->getLHS()))
1884 return true;
1885 return CheckAddressConstantExpression(Exp->getRHS());
1886 }
1887 case Expr::AddrLabelExprClass:
1888 return false;
1889 }
1890}
1891
Eli Friedman998dffb2008-06-09 05:05:07 +00001892static const Expr* FindExpressionBaseAddress(const Expr* E);
1893
1894static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1895 switch (E->getStmtClass()) {
1896 default:
1897 return E;
1898 case Expr::ParenExprClass: {
1899 const ParenExpr* PE = cast<ParenExpr>(E);
1900 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1901 }
1902 case Expr::MemberExprClass: {
1903 const MemberExpr *M = cast<MemberExpr>(E);
1904 if (M->isArrow())
1905 return FindExpressionBaseAddress(M->getBase());
1906 return FindExpressionBaseAddressLValue(M->getBase());
1907 }
1908 case Expr::ArraySubscriptExprClass: {
1909 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1910 return FindExpressionBaseAddress(ASE->getBase());
1911 }
1912 case Expr::UnaryOperatorClass: {
1913 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1914
1915 if (Exp->getOpcode() == UnaryOperator::Deref)
1916 return FindExpressionBaseAddress(Exp->getSubExpr());
1917
1918 return E;
1919 }
1920 }
1921}
1922
1923static const Expr* FindExpressionBaseAddress(const Expr* E) {
1924 switch (E->getStmtClass()) {
1925 default:
1926 return E;
1927 case Expr::ParenExprClass: {
1928 const ParenExpr* PE = cast<ParenExpr>(E);
1929 return FindExpressionBaseAddress(PE->getSubExpr());
1930 }
1931 case Expr::UnaryOperatorClass: {
1932 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1933
1934 // C99 6.6p9
1935 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1936 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1937
1938 if (Exp->getOpcode() == UnaryOperator::Extension)
1939 return FindExpressionBaseAddress(Exp->getSubExpr());
1940
1941 return E;
1942 }
1943 case Expr::BinaryOperatorClass: {
1944 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1945
1946 Expr *PExp = Exp->getLHS();
1947 Expr *IExp = Exp->getRHS();
1948 if (IExp->getType()->isPointerType())
1949 std::swap(PExp, IExp);
1950
1951 return FindExpressionBaseAddress(PExp);
1952 }
1953 case Expr::ImplicitCastExprClass: {
1954 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1955
1956 // Check for implicit promotion
1957 if (SubExpr->getType()->isFunctionType() ||
1958 SubExpr->getType()->isArrayType())
1959 return FindExpressionBaseAddressLValue(SubExpr);
1960
1961 // Check for pointer->pointer cast
1962 if (SubExpr->getType()->isPointerType())
1963 return FindExpressionBaseAddress(SubExpr);
1964
1965 // We assume that we have an arithmetic expression here;
1966 // if we don't, we'll figure it out later
1967 return 0;
1968 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001969 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001970 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1971
1972 // Check for pointer->pointer cast
1973 if (SubExpr->getType()->isPointerType())
1974 return FindExpressionBaseAddress(SubExpr);
1975
1976 // We assume that we have an arithmetic expression here;
1977 // if we don't, we'll figure it out later
1978 return 0;
1979 }
1980 }
1981}
1982
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001983bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001984 switch (Init->getStmtClass()) {
1985 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001986 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001987 return true;
1988 case Expr::ParenExprClass: {
1989 const ParenExpr* PE = cast<ParenExpr>(Init);
1990 return CheckArithmeticConstantExpression(PE->getSubExpr());
1991 }
1992 case Expr::FloatingLiteralClass:
1993 case Expr::IntegerLiteralClass:
1994 case Expr::CharacterLiteralClass:
1995 case Expr::ImaginaryLiteralClass:
1996 case Expr::TypesCompatibleExprClass:
1997 case Expr::CXXBoolLiteralExprClass:
1998 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001999 case Expr::CallExprClass:
2000 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002001 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002002
2003 // Allow any constant foldable calls to builtins.
2004 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002005 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002006
Steve Narofffc08f5e2008-10-27 11:34:16 +00002007 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002008 return true;
2009 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002010 case Expr::DeclRefExprClass:
2011 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002012 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2013 if (isa<EnumConstantDecl>(D))
2014 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002015 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002016 return true;
2017 }
2018 case Expr::CompoundLiteralExprClass:
2019 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2020 // but vectors are allowed to be magic.
2021 if (Init->getType()->isVectorType())
2022 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002023 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002024 return true;
2025 case Expr::UnaryOperatorClass: {
2026 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2027
2028 switch (Exp->getOpcode()) {
2029 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2030 // See C99 6.6p3.
2031 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002032 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002033 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002034 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002035 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2036 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002037 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002038 return true;
2039 case UnaryOperator::Extension:
2040 case UnaryOperator::LNot:
2041 case UnaryOperator::Plus:
2042 case UnaryOperator::Minus:
2043 case UnaryOperator::Not:
2044 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2045 }
2046 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002047 case Expr::SizeOfAlignOfExprClass: {
2048 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002049 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002050 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002051 return false;
2052 // alignof always evaluates to a constant.
2053 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002054 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002055 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002056 return true;
2057 }
2058 return false;
2059 }
2060 case Expr::BinaryOperatorClass: {
2061 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2062
2063 if (Exp->getLHS()->getType()->isArithmeticType() &&
2064 Exp->getRHS()->getType()->isArithmeticType()) {
2065 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2066 CheckArithmeticConstantExpression(Exp->getRHS());
2067 }
2068
Eli Friedman998dffb2008-06-09 05:05:07 +00002069 if (Exp->getLHS()->getType()->isPointerType() &&
2070 Exp->getRHS()->getType()->isPointerType()) {
2071 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2072 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2073
2074 // Only allow a null (constant integer) base; we could
2075 // allow some additional cases if necessary, but this
2076 // is sufficient to cover offsetof-like constructs.
2077 if (!LHSBase && !RHSBase) {
2078 return CheckAddressConstantExpression(Exp->getLHS()) ||
2079 CheckAddressConstantExpression(Exp->getRHS());
2080 }
2081 }
2082
Steve Narofffc08f5e2008-10-27 11:34:16 +00002083 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002084 return true;
2085 }
2086 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002087 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002088 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002089 if (SubExpr->getType()->isArithmeticType())
2090 return CheckArithmeticConstantExpression(SubExpr);
2091
Eli Friedman266df142008-09-02 09:37:00 +00002092 if (SubExpr->getType()->isPointerType()) {
2093 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2094 // If the pointer has a null base, this is an offsetof-like construct
2095 if (!Base)
2096 return CheckAddressConstantExpression(SubExpr);
2097 }
2098
Steve Narofffc08f5e2008-10-27 11:34:16 +00002099 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002100 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002101 }
2102 case Expr::ConditionalOperatorClass: {
2103 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002104
2105 // If GNU extensions are disabled, we require all operands to be arithmetic
2106 // constant expressions.
2107 if (getLangOptions().NoExtensions) {
2108 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2109 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2110 CheckArithmeticConstantExpression(Exp->getRHS());
2111 }
2112
2113 // Otherwise, we have to emulate some of the behavior of fold here.
2114 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2115 // because it can constant fold things away. To retain compatibility with
2116 // GCC code, we see if we can fold the condition to a constant (which we
2117 // should always be able to do in theory). If so, we only require the
2118 // specified arm of the conditional to be a constant. This is a horrible
2119 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002120 Expr::EvalResult EvalResult;
2121 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2122 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002123 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002124 // won't be able to either. Use it to emit the diagnostic though.
2125 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002126 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002127 return Res;
2128 }
2129
2130 // Verify that the side following the condition is also a constant.
2131 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002132 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002133 std::swap(TrueSide, FalseSide);
2134
2135 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002136 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002137
2138 // Okay, the evaluated side evaluates to a constant, so we accept this.
2139 // Check to see if the other side is obviously not a constant. If so,
2140 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002141 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002142 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002143 diag::ext_typecheck_expression_not_constant_but_accepted)
2144 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002145 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002146 }
2147 }
2148}
2149
2150bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlssonf6791c62008-12-05 05:09:56 +00002151 Expr::EvalResult Result;
2152
Nuno Lopese7280452008-07-07 16:46:50 +00002153 Init = Init->IgnoreParens();
2154
Anders Carlssonf6791c62008-12-05 05:09:56 +00002155 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2156 return false;
2157
Eli Friedman02c22ce2008-05-20 13:48:25 +00002158 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2159 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2160 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2161
Nuno Lopese7280452008-07-07 16:46:50 +00002162 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2163 return CheckForConstantInitializer(e->getInitializer(), DclT);
2164
Eli Friedman02c22ce2008-05-20 13:48:25 +00002165 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2166 unsigned numInits = Exp->getNumInits();
2167 for (unsigned i = 0; i < numInits; i++) {
2168 // FIXME: Need to get the type of the declaration for C++,
2169 // because it could be a reference?
2170 if (CheckForConstantInitializer(Exp->getInit(i),
2171 Exp->getInit(i)->getType()))
2172 return true;
2173 }
2174 return false;
2175 }
2176
Anders Carlssonf6791c62008-12-05 05:09:56 +00002177 // FIXME: We can probably remove some of this code below, now that
2178 // Expr::Evaluate is doing the heavy lifting for scalars.
2179
Eli Friedman02c22ce2008-05-20 13:48:25 +00002180 if (Init->isNullPointerConstant(Context))
2181 return false;
2182 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002183 QualType InitTy = Context.getCanonicalType(Init->getType())
2184 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002185 if (InitTy == Context.BoolTy) {
2186 // Special handling for pointers implicitly cast to bool;
2187 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2188 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2189 Expr* SubE = ICE->getSubExpr();
2190 if (SubE->getType()->isPointerType() ||
2191 SubE->getType()->isArrayType() ||
2192 SubE->getType()->isFunctionType()) {
2193 return CheckAddressConstantExpression(Init);
2194 }
2195 }
2196 } else if (InitTy->isIntegralType()) {
2197 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002198 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002199 SubE = CE->getSubExpr();
2200 // Special check for pointer cast to int; we allow as an extension
2201 // an address constant cast to an integer if the integer
2202 // is of an appropriate width (this sort of code is apparently used
2203 // in some places).
2204 // FIXME: Add pedwarn?
2205 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2206 if (SubE && (SubE->getType()->isPointerType() ||
2207 SubE->getType()->isArrayType() ||
2208 SubE->getType()->isFunctionType())) {
2209 unsigned IntWidth = Context.getTypeSize(Init->getType());
2210 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2211 if (IntWidth >= PointerWidth)
2212 return CheckAddressConstantExpression(Init);
2213 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002214 }
2215
2216 return CheckArithmeticConstantExpression(Init);
2217 }
2218
2219 if (Init->getType()->isPointerType())
2220 return CheckAddressConstantExpression(Init);
2221
Eli Friedman25086f02008-05-30 18:14:48 +00002222 // An array type at the top level that isn't an init-list must
2223 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002224 if (Init->getType()->isArrayType())
2225 return false;
2226
Nuno Lopes1dc26762008-09-01 18:42:41 +00002227 if (Init->getType()->isFunctionType())
2228 return false;
2229
Steve Naroffdff3fb22008-10-02 17:12:56 +00002230 // Allow block exprs at top level.
2231 if (Init->getType()->isBlockPointerType())
2232 return false;
2233
Steve Narofffc08f5e2008-10-27 11:34:16 +00002234 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002235 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002236}
2237
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002238void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002239 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002240 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002241 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002242
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002243 // If there is no declaration, there was an error parsing it. Just ignore
2244 // the initializer.
2245 if (RealDecl == 0) {
2246 delete Init;
2247 return;
2248 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002249
Steve Naroff420d0f52007-09-12 20:13:48 +00002250 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2251 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00002252 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2253 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002254 RealDecl->setInvalidDecl();
2255 return;
2256 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002257 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002258 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002259 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002260 if (VDecl->isBlockVarDecl()) {
2261 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002262 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002263 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002264 VDecl->setInvalidDecl();
2265 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002266 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002267 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002268 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002269
2270 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2271 if (!getLangOptions().CPlusPlus) {
2272 if (SC == VarDecl::Static) // C99 6.7.8p4.
2273 CheckForConstantInitializer(Init, DclT);
2274 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002275 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002276 } else if (VDecl->isFileVarDecl()) {
2277 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002278 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002279 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002280 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002281 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002282 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002283
Anders Carlssonea7140a2008-08-22 05:00:02 +00002284 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2285 if (!getLangOptions().CPlusPlus) {
2286 // C99 6.7.8p4. All file scoped initializers need to be constant.
2287 CheckForConstantInitializer(Init, DclT);
2288 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002289 }
2290 // If the type changed, it means we had an incomplete type that was
2291 // completed by the initializer. For example:
2292 // int ary[] = { 1, 3, 5 };
2293 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002294 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002295 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002296 Init->setType(DclT);
2297 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002298
2299 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002300 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002301 return;
2302}
2303
Douglas Gregor81c29152008-10-29 00:13:59 +00002304void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2305 Decl *RealDecl = static_cast<Decl *>(dcl);
2306
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002307 // If there is no declaration, there was an error parsing it. Just ignore it.
2308 if (RealDecl == 0)
2309 return;
2310
Douglas Gregor81c29152008-10-29 00:13:59 +00002311 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2312 QualType Type = Var->getType();
2313 // C++ [dcl.init.ref]p3:
2314 // The initializer can be omitted for a reference only in a
2315 // parameter declaration (8.3.5), in the declaration of a
2316 // function return type, in the declaration of a class member
2317 // within its class declaration (9.2), and where the extern
2318 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002319 if (Type->isReferenceType() &&
2320 Var->getStorageClass() != VarDecl::Extern &&
2321 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002322 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002323 << Var->getDeclName()
2324 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002325 Var->setInvalidDecl();
2326 return;
2327 }
2328
2329 // C++ [dcl.init]p9:
2330 //
2331 // If no initializer is specified for an object, and the object
2332 // is of (possibly cv-qualified) non-POD class type (or array
2333 // thereof), the object shall be default-initialized; if the
2334 // object is of const-qualified type, the underlying class type
2335 // shall have a user-declared default constructor.
2336 if (getLangOptions().CPlusPlus) {
2337 QualType InitType = Type;
2338 if (const ArrayType *Array = Context.getAsArrayType(Type))
2339 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002340 if (Var->getStorageClass() != VarDecl::Extern &&
2341 Var->getStorageClass() != VarDecl::PrivateExtern &&
2342 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002343 const CXXConstructorDecl *Constructor
2344 = PerformInitializationByConstructor(InitType, 0, 0,
2345 Var->getLocation(),
2346 SourceRange(Var->getLocation(),
2347 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002348 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002349 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002350 if (!Constructor)
2351 Var->setInvalidDecl();
2352 }
2353 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002354
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002355#if 0
2356 // FIXME: Temporarily disabled because we are not properly parsing
2357 // linkage specifications on declarations, e.g.,
2358 //
2359 // extern "C" const CGPoint CGPointerZero;
2360 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002361 // C++ [dcl.init]p9:
2362 //
2363 // If no initializer is specified for an object, and the
2364 // object is of (possibly cv-qualified) non-POD class type (or
2365 // array thereof), the object shall be default-initialized; if
2366 // the object is of const-qualified type, the underlying class
2367 // type shall have a user-declared default
2368 // constructor. Otherwise, if no initializer is specified for
2369 // an object, the object and its subobjects, if any, have an
2370 // indeterminate initial value; if the object or any of its
2371 // subobjects are of const-qualified type, the program is
2372 // ill-formed.
2373 //
2374 // This isn't technically an error in C, so we don't diagnose it.
2375 //
2376 // FIXME: Actually perform the POD/user-defined default
2377 // constructor check.
2378 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002379 Context.getCanonicalType(Type).isConstQualified() &&
2380 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002381 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2382 << Var->getName()
2383 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002384#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002385 }
2386}
2387
Chris Lattner4b009652007-07-25 00:24:17 +00002388/// The declarators are chained together backwards, reverse the list.
2389Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2390 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002391 Decl *GroupDecl = static_cast<Decl*>(group);
2392 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002393 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002394
2395 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2396 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002397 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002398 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002399 else { // reverse the list.
2400 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002401 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002402 Group->setNextDeclarator(NewGroup);
2403 NewGroup = Group;
2404 Group = Next;
2405 }
2406 }
2407 // Perform semantic analysis that depends on having fully processed both
2408 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002409 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002410 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2411 if (!IDecl)
2412 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002413 QualType T = IDecl->getType();
2414
Anders Carlsson68adbd12008-12-07 00:20:55 +00002415 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002416 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002417
2418 // FIXME: This won't give the correct result for
2419 // int a[10][n];
2420 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002421 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002422 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2423 SizeRange;
2424
Eli Friedman8ff07782008-02-15 18:16:39 +00002425 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002426 } else {
2427 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2428 // static storage duration, it shall not have a variable length array.
2429 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002430 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2431 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002432 IDecl->setInvalidDecl();
2433 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002434 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2435 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002436 IDecl->setInvalidDecl();
2437 }
2438 }
2439 } else if (T->isVariablyModifiedType()) {
2440 if (IDecl->isFileVarDecl()) {
2441 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2442 IDecl->setInvalidDecl();
2443 } else {
2444 if (IDecl->getStorageClass() == VarDecl::Extern) {
2445 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2446 IDecl->setInvalidDecl();
2447 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002448 }
2449 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002450
Steve Naroff6a0e2092007-09-12 14:07:44 +00002451 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2452 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002453 if (IDecl->isBlockVarDecl() &&
2454 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002455 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002456 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002457 IDecl->setInvalidDecl();
2458 }
2459 }
2460 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2461 // object that has file scope without an initializer, and without a
2462 // storage-class specifier or with the storage-class specifier "static",
2463 // constitutes a tentative definition. Note: A tentative definition with
2464 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002465 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002466 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002467 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2468 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002469 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002470 // C99 6.9.2p3: If the declaration of an identifier for an object is
2471 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2472 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002473 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002474 IDecl->setInvalidDecl();
2475 }
2476 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002477 if (IDecl->isFileVarDecl())
2478 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002479 }
2480 return NewGroup;
2481}
Steve Naroff91b03f72007-08-28 03:03:08 +00002482
Chris Lattner3e254fb2008-04-08 04:40:51 +00002483/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2484/// to introduce parameters into function prototype scope.
2485Sema::DeclTy *
2486Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002487 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002488
Chris Lattner3e254fb2008-04-08 04:40:51 +00002489 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002490 VarDecl::StorageClass StorageClass = VarDecl::None;
2491 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2492 StorageClass = VarDecl::Register;
2493 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002494 Diag(DS.getStorageClassSpecLoc(),
2495 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002496 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002497 }
2498 if (DS.isThreadSpecified()) {
2499 Diag(DS.getThreadSpecLoc(),
2500 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002501 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002502 }
2503
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002504 // Check that there are no default arguments inside the type of this
2505 // parameter (C++ only).
2506 if (getLangOptions().CPlusPlus)
2507 CheckExtraCXXDefaultArguments(D);
2508
Chris Lattner3e254fb2008-04-08 04:40:51 +00002509 // In this context, we *do not* check D.getInvalidType(). If the declarator
2510 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2511 // though it will not reflect the user specified type.
2512 QualType parmDeclType = GetTypeForDeclarator(D, S);
2513
2514 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2515
Chris Lattner4b009652007-07-25 00:24:17 +00002516 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2517 // Can this happen for params? We already checked that they don't conflict
2518 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002519 IdentifierInfo *II = D.getIdentifier();
2520 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002521 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002522 // Maybe we will complain about the shadowed template parameter.
2523 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2524 // Just pretend that we didn't see the previous declaration.
2525 PrevDecl = 0;
2526 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002527 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002528
2529 // Recover by removing the name
2530 II = 0;
2531 D.SetIdentifier(0, D.getIdentifierLoc());
2532 }
Chris Lattner4b009652007-07-25 00:24:17 +00002533 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002534
2535 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2536 // Doing the promotion here has a win and a loss. The win is the type for
2537 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2538 // code generator). The loss is the orginal type isn't preserved. For example:
2539 //
2540 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2541 // int blockvardecl[5];
2542 // sizeof(parmvardecl); // size == 4
2543 // sizeof(blockvardecl); // size == 20
2544 // }
2545 //
2546 // For expressions, all implicit conversions are captured using the
2547 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2548 //
2549 // FIXME: If a source translation tool needs to see the original type, then
2550 // we need to consider storing both types (in ParmVarDecl)...
2551 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002552 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002553 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002554 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002555 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002556 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002557
Chris Lattner3e254fb2008-04-08 04:40:51 +00002558 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2559 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002560 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002561 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002562
Chris Lattner3e254fb2008-04-08 04:40:51 +00002563 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002564 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002565
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002566 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2567 if (D.getCXXScopeSpec().isSet()) {
2568 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2569 << D.getCXXScopeSpec().getRange();
2570 New->setInvalidDecl();
2571 }
2572
Douglas Gregor8acb7272008-12-11 16:49:14 +00002573 // Add the parameter declaration into this scope.
2574 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002575 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002576 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002577
Chris Lattner9b384ca2008-06-29 00:02:00 +00002578 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002579 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002580
Chris Lattner4b009652007-07-25 00:24:17 +00002581}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002582
Chris Lattnerea148702007-10-09 17:14:05 +00002583Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002584 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002585 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2586 "Not a function declarator!");
2587 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002588
Chris Lattner4b009652007-07-25 00:24:17 +00002589 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2590 // for a K&R function.
2591 if (!FTI.hasPrototype) {
2592 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002593 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002594 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2595 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002596 // Implicitly declare the argument as type 'int' for lack of a better
2597 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002598 DeclSpec DS;
2599 const char* PrevSpec; // unused
2600 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2601 PrevSpec);
2602 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2603 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2604 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002605 }
2606 }
Chris Lattner4b009652007-07-25 00:24:17 +00002607 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002608 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002609 }
2610
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002611 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002612
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002613 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002614 ActOnDeclarator(ParentScope, D, 0,
2615 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002616}
2617
2618Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2619 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002620 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002621
2622 // See if this is a redefinition.
2623 const FunctionDecl *Definition;
2624 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002625 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002626 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002627 }
2628
Douglas Gregor8acb7272008-12-11 16:49:14 +00002629 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002630
Chris Lattner3e254fb2008-04-08 04:40:51 +00002631 // Check the validity of our function parameters
2632 CheckParmsForFunctionDef(FD);
2633
2634 // Introduce our parameters into the function scope
2635 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2636 ParmVarDecl *Param = FD->getParamDecl(p);
2637 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002638 if (Param->getIdentifier())
2639 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002640 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002641
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002642 // Checking attributes of current function definition
2643 // dllimport attribute.
2644 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2645 // dllimport attribute cannot be applied to definition.
2646 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2647 Diag(FD->getLocation(),
2648 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2649 << "dllimport";
2650 FD->setInvalidDecl();
2651 return FD;
2652 } else {
2653 // If a symbol previously declared dllimport is later defined, the
2654 // attribute is ignored in subsequent references, and a warning is
2655 // emitted.
2656 Diag(FD->getLocation(),
2657 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2658 << FD->getNameAsCString() << "dllimport";
2659 }
2660 }
Chris Lattner4b009652007-07-25 00:24:17 +00002661 return FD;
2662}
2663
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002664Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002665 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002666 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002667 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002668 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002669 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002670 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002671 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002672 } else
2673 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002674 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002675 // Verify and clean out per-function state.
2676
2677 // Check goto/label use.
2678 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2679 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2680 // Verify that we have no forward references left. If so, there was a goto
2681 // or address of a label taken, but no definition of it. Label fwd
2682 // definitions are indicated with a null substmt.
2683 if (I->second->getSubStmt() == 0) {
2684 LabelStmt *L = I->second;
2685 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002686 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002687
2688 // At this point, we have gotos that use the bogus label. Stitch it into
2689 // the function body so that they aren't leaked and that the AST is well
2690 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002691 if (Body) {
2692 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002693 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002694 } else {
2695 // The whole function wasn't parsed correctly, just delete this.
2696 delete L;
2697 }
Chris Lattner4b009652007-07-25 00:24:17 +00002698 }
2699 }
2700 LabelMap.clear();
2701
Steve Naroff99ee4302007-11-11 23:20:51 +00002702 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002703}
2704
Chris Lattner4b009652007-07-25 00:24:17 +00002705/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2706/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002707ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2708 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002709 // Extension in C99. Legal in C90, but warn about it.
2710 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002711 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002712 else
Chris Lattner65cae292008-11-19 08:23:25 +00002713 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002714
2715 // FIXME: handle stuff like:
2716 // void foo() { extern float X(); }
2717 // void bar() { X(); } <-- implicit decl for X in another scope.
2718
2719 // Set a Declarator for the implicit definition: int foo();
2720 const char *Dummy;
2721 DeclSpec DS;
2722 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2723 Error = Error; // Silence warning.
2724 assert(!Error && "Error setting up implicit decl!");
2725 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002726 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002727 D.SetIdentifier(&II, Loc);
2728
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002729 // Insert this function into translation-unit scope.
2730
2731 DeclContext *PrevDC = CurContext;
2732 CurContext = Context.getTranslationUnitDecl();
2733
Steve Naroff9104f3c2008-04-04 14:32:09 +00002734 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002735 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002736 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002737
2738 CurContext = PrevDC;
2739
Steve Naroff9104f3c2008-04-04 14:32:09 +00002740 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002741}
2742
2743
Chris Lattner82bb4792007-11-14 06:34:38 +00002744TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002745 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002746 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002747 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002748
2749 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002750 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2751 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002752 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002753 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002754 if (D.getInvalidType())
2755 NewTD->setInvalidDecl();
2756 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002757}
2758
Steve Naroff0acc9c92007-09-15 18:49:24 +00002759/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002760/// former case, Name will be non-null. In the later case, Name will be null.
2761/// TagType indicates what kind of tag this is. TK indicates whether this is a
2762/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002763Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002764 SourceLocation KWLoc, const CXXScopeSpec &SS,
2765 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002766 AttributeList *Attr,
2767 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002768 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002769 assert((Name != 0 || TK == TK_Definition) &&
2770 "Nameless record must be a definition!");
2771
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002772 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002773 switch (TagType) {
2774 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002775 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2776 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2777 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2778 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002779 }
2780
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002781 DeclContext *DC = CurContext;
2782 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002783
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002784 if (Name && SS.isNotEmpty()) {
2785 // We have a nested-name tag ('struct foo::bar').
2786
2787 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002788 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002789 Name = 0;
2790 goto CreateNewDecl;
2791 }
2792
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002793 DC = static_cast<DeclContext*>(SS.getScopeRep());
2794 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002795 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2796
2797 // A tag 'foo::bar' must already exist.
2798 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002799 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002800 Name = 0;
2801 goto CreateNewDecl;
2802 }
2803 } else {
2804 // If this is a named struct, check to see if there was a previous forward
2805 // declaration or definition.
2806 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2807 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2808 }
2809
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002810 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002811 // Maybe we will complain about the shadowed template parameter.
2812 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2813 // Just pretend that we didn't see the previous declaration.
2814 PrevDecl = 0;
2815 }
2816
Ted Kremenekd4434152008-09-02 21:26:19 +00002817 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002818 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2819 "unexpected Decl type");
2820 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002821 // If this is a use of a previous tag, or if the tag is already declared
2822 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002823 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002824 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002825 // Make sure that this wasn't declared as an enum and now used as a
2826 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002827 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002828 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002829 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002830 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002831 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002832 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002833 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002834 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002835
Douglas Gregorae644892008-12-15 16:32:14 +00002836 // FIXME: In the future, return a variant or some other clue
2837 // for the consumer of this Decl to know it doesn't own it.
2838 // For our current ASTs this shouldn't be a problem, but will
2839 // need to be changed with DeclGroups.
2840 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002841 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002842
2843 // Diagnose attempts to redefine a tag.
2844 if (TK == TK_Definition) {
2845 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2846 Diag(NameLoc, diag::err_redefinition) << Name;
2847 Diag(Def->getLocation(), diag::note_previous_definition);
2848 // If this is a redefinition, recover by making this struct be
2849 // anonymous, which will make any later references get the previous
2850 // definition.
2851 Name = 0;
2852 PrevDecl = 0;
2853 }
2854 // Okay, this is definition of a previously declared or referenced
2855 // tag PrevDecl. We're going to create a new Decl for it.
2856 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002857 }
Douglas Gregorae644892008-12-15 16:32:14 +00002858 // If we get here we have (another) forward declaration or we
2859 // have a definition. Just create a new decl.
2860 } else {
2861 // If we get here, this is a definition of a new tag type in a nested
2862 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2863 // new decl/type. We set PrevDecl to NULL so that the entities
2864 // have distinct types.
2865 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002866 }
Douglas Gregorae644892008-12-15 16:32:14 +00002867 // If we get here, we're going to create a new Decl. If PrevDecl
2868 // is non-NULL, it's a definition of the tag declared by
2869 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002870 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002871 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002872 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002873 // The tag name clashes with a namespace name, issue an error and
2874 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002875 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002876 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002877 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002878 PrevDecl = 0;
2879 } else {
2880 // The existing declaration isn't relevant to us; we're in a
2881 // new scope, so clear out the previous declaration.
2882 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002883 }
Chris Lattner4b009652007-07-25 00:24:17 +00002884 }
Chris Lattner4b009652007-07-25 00:24:17 +00002885 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002886
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002887CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002888
2889 // If there is an identifier, use the location of the identifier as the
2890 // location of the decl, otherwise use the location of the struct/union
2891 // keyword.
2892 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2893
Douglas Gregorae644892008-12-15 16:32:14 +00002894 // Otherwise, create a new declaration. If there is a previous
2895 // declaration of the same entity, the two will be linked via
2896 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00002897 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00002898
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002899 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002900 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2901 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00002902 New = EnumDecl::Create(Context, DC, Loc, Name,
2903 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002904 // If this is an undefined enum, warn.
2905 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002906 } else {
2907 // struct/union/class
2908
Chris Lattner4b009652007-07-25 00:24:17 +00002909 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2910 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002911 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002912 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00002913 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2914 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002915 else
Douglas Gregorae644892008-12-15 16:32:14 +00002916 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2917 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002918 }
Douglas Gregorae644892008-12-15 16:32:14 +00002919
2920 if (Kind != TagDecl::TK_enum) {
2921 // Handle #pragma pack: if the #pragma pack stack has non-default
2922 // alignment, make up a packed attribute for this decl. These
2923 // attributes are checked when the ASTContext lays out the
2924 // structure.
2925 //
2926 // It is important for implementing the correct semantics that this
2927 // happen here (in act on tag decl). The #pragma pack stack is
2928 // maintained as a result of parser callbacks which can occur at
2929 // many points during the parsing of a struct declaration (because
2930 // the #pragma tokens are effectively skipped over during the
2931 // parsing of the struct).
2932 if (unsigned Alignment = PackContext.getAlignment())
2933 New->addAttr(new PackedAttr(Alignment * 8));
2934 }
2935
2936 if (Attr)
2937 ProcessDeclAttributeList(New, Attr);
2938
2939 // Set the lexical context. If the tag has a C++ scope specifier, the
2940 // lexical context will be different from the semantic context.
2941 New->setLexicalDeclContext(CurContext);
Chris Lattner4b009652007-07-25 00:24:17 +00002942
2943 // If this has an identifier, add it to the scope stack.
2944 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002945 // The scope passed in may not be a decl scope. Zip up the scope tree until
2946 // we find one that is.
2947 while ((S->getFlags() & Scope::DeclScope) == 0)
2948 S = S->getParent();
2949
2950 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002951 PushOnScopeChains(New, S);
Douglas Gregor723d3332009-01-07 00:43:41 +00002952 } else if (getLangOptions().CPlusPlus) {
2953 // FIXME: We also want to do this for C, but if this tag is
2954 // defined within a structure CurContext will point to the context
2955 // enclosing the structure, and we would end up inserting the tag
2956 // type into the wrong place.
2957 CurContext->addDecl(Context, New);
Chris Lattner4b009652007-07-25 00:24:17 +00002958 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002959
Chris Lattner4b009652007-07-25 00:24:17 +00002960 return New;
2961}
2962
Chris Lattner1bf58f62008-06-21 19:39:06 +00002963
Chris Lattnera73e2202008-11-12 21:17:48 +00002964/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2965/// types into constant array types in certain situations which would otherwise
2966/// be errors (for GCC compatibility).
2967static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2968 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002969 // This method tries to turn a variable array into a constant
2970 // array even when the size isn't an ICE. This is necessary
2971 // for compatibility with code that depends on gcc's buggy
2972 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002973 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2974 if (!VLATy) return QualType();
2975
Anders Carlsson8c3de802008-12-19 20:58:05 +00002976 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002977 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00002978 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002979 return QualType();
2980
Anders Carlsson8c3de802008-12-19 20:58:05 +00002981 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2982 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002983 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2984 return Context.getConstantArrayType(VLATy->getElementType(),
2985 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002986 return QualType();
2987}
2988
Anders Carlsson108229a2008-12-06 20:33:04 +00002989bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00002990 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00002991 // FIXME: 6.7.2.1p4 - verify the field type.
2992
2993 llvm::APSInt Value;
2994 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2995 return true;
2996
Chris Lattner8464c372008-12-12 04:56:04 +00002997 // Zero-width bitfield is ok for anonymous field.
2998 if (Value == 0 && FieldName)
2999 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3000
3001 if (Value.isNegative())
3002 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003003
3004 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3005 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003006 if (TypeSize && Value.getZExtValue() > TypeSize)
3007 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3008 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003009
3010 return false;
3011}
3012
Steve Naroff0acc9c92007-09-15 18:49:24 +00003013/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003014/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003015Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003016 SourceLocation DeclStart,
3017 Declarator &D, ExprTy *BitfieldWidth) {
3018 IdentifierInfo *II = D.getIdentifier();
3019 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003020 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003021 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003022 if (II) Loc = D.getIdentifierLoc();
3023
3024 // FIXME: Unnamed fields can be handled in various different ways, for
3025 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003026
Chris Lattner4b009652007-07-25 00:24:17 +00003027 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003028 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3029 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003030
Chris Lattner4b009652007-07-25 00:24:17 +00003031 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3032 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003033 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003034 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003035 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003036 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003037 T = FixedTy;
3038 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003039 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003040 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003041 InvalidDecl = true;
3042 }
Chris Lattner4b009652007-07-25 00:24:17 +00003043 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003044
3045 if (BitWidth) {
3046 if (VerifyBitField(Loc, II, T, BitWidth))
3047 InvalidDecl = true;
3048 } else {
3049 // Not a bitfield.
3050
3051 // validate II.
3052
3053 }
3054
Chris Lattner4b009652007-07-25 00:24:17 +00003055 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003056 FieldDecl *NewFD;
3057
Douglas Gregor8acb7272008-12-11 16:49:14 +00003058 NewFD = FieldDecl::Create(Context, Record,
3059 Loc, II, T, BitWidth,
3060 D.getDeclSpec().getStorageClassSpec() ==
3061 DeclSpec::SCS_mutable,
3062 /*PrevDecl=*/0);
3063
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003064 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003065 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003066 if (!T->isPODType())
3067 cast<CXXRecordDecl>(Record)->setPOD(false);
3068 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003069
Chris Lattner9b384ca2008-06-29 00:02:00 +00003070 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003071
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003072 if (D.getInvalidType() || InvalidDecl)
3073 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003074
3075 if (II && getLangOptions().CPlusPlus)
3076 PushOnScopeChains(NewFD, S);
3077 else
3078 Record->addDecl(Context, NewFD);
3079
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003080 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003081}
3082
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003083/// TranslateIvarVisibility - Translate visibility from a token ID to an
3084/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003085static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003086TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003087 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003088 default: assert(0 && "Unknown visitibility kind");
3089 case tok::objc_private: return ObjCIvarDecl::Private;
3090 case tok::objc_public: return ObjCIvarDecl::Public;
3091 case tok::objc_protected: return ObjCIvarDecl::Protected;
3092 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003093 }
3094}
3095
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003096/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3097/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003098Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003099 SourceLocation DeclStart,
3100 Declarator &D, ExprTy *BitfieldWidth,
3101 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003102 IdentifierInfo *II = D.getIdentifier();
3103 Expr *BitWidth = (Expr*)BitfieldWidth;
3104 SourceLocation Loc = DeclStart;
3105 if (II) Loc = D.getIdentifierLoc();
3106
3107 // FIXME: Unnamed fields can be handled in various different ways, for
3108 // example, unnamed unions inject all members into the struct namespace!
3109
Anders Carlsson108229a2008-12-06 20:33:04 +00003110 QualType T = GetTypeForDeclarator(D, S);
3111 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3112 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003113
3114 if (BitWidth) {
3115 // TODO: Validate.
3116 //printf("WARNING: BITFIELDS IGNORED!\n");
3117
3118 // 6.7.2.1p3
3119 // 6.7.2.1p4
3120
3121 } else {
3122 // Not a bitfield.
3123
3124 // validate II.
3125
3126 }
3127
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003128 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3129 // than a variably modified type.
3130 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003131 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003132 InvalidDecl = true;
3133 }
3134
Ted Kremenek173dd312008-07-23 18:04:17 +00003135 // Get the visibility (access control) for this ivar.
3136 ObjCIvarDecl::AccessControl ac =
3137 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3138 : ObjCIvarDecl::None;
3139
3140 // Construct the decl.
3141 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003142 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003143
Ted Kremenek173dd312008-07-23 18:04:17 +00003144 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003145 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003146
3147 if (D.getInvalidType() || InvalidDecl)
3148 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003149
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003150 return NewID;
3151}
3152
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003153void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003154 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003155 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003156 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003157 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003158 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3159 assert(EnclosingDecl && "missing record or interface decl");
3160 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3161
Ted Kremenek46a837c2008-09-05 17:16:31 +00003162 if (Record)
3163 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
3164 // Diagnose code like:
3165 // struct S { struct S {} X; };
3166 // We discover this when we complete the outer S. Reject and ignore the
3167 // outer S.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003168 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattner271d4c22008-11-24 05:29:24 +00003169 << DefRecord->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00003170 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00003171 Record->setInvalidDecl();
3172 return;
3173 }
3174
Chris Lattner4b009652007-07-25 00:24:17 +00003175 // Verify that all the fields are okay.
3176 unsigned NumNamedMembers = 0;
3177 llvm::SmallVector<FieldDecl*, 32> RecFields;
3178 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00003179
Chris Lattner4b009652007-07-25 00:24:17 +00003180 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003181
Steve Naroff9bb759f2007-09-14 22:20:54 +00003182 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3183 assert(FD && "missing field decl");
3184
3185 // Remember all fields.
3186 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00003187
3188 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003189 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00003190
Chris Lattner4b009652007-07-25 00:24:17 +00003191 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003192 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003193 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003194 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003195 FD->setInvalidDecl();
3196 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003197 continue;
3198 }
Chris Lattner4b009652007-07-25 00:24:17 +00003199 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3200 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003201 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00003202 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003203 FD->setInvalidDecl();
3204 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003205 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003206 }
Chris Lattner4b009652007-07-25 00:24:17 +00003207 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003208 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003209 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00003210 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003211 FD->setInvalidDecl();
3212 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003213 continue;
3214 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003215 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003216 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003217 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003218 FD->setInvalidDecl();
3219 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003220 continue;
3221 }
Chris Lattner4b009652007-07-25 00:24:17 +00003222 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003223 if (Record)
3224 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003225 }
Chris Lattner4b009652007-07-25 00:24:17 +00003226 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3227 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003228 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003229 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3230 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003231 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003232 Record->setHasFlexibleArrayMember(true);
3233 } else {
3234 // If this is a struct/class and this is not the last element, reject
3235 // it. Note that GCC supports variable sized arrays in the middle of
3236 // structures.
3237 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003238 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003239 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003240 FD->setInvalidDecl();
3241 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003242 continue;
3243 }
Chris Lattner4b009652007-07-25 00:24:17 +00003244 // We support flexible arrays at the end of structs in other structs
3245 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003246 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003247 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003248 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003249 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003250 }
3251 }
3252 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003253 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003254 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003255 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003256 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003257 FD->setInvalidDecl();
3258 EnclosingDecl->setInvalidDecl();
3259 continue;
3260 }
Chris Lattner4b009652007-07-25 00:24:17 +00003261 // Keep track of the number of named members.
3262 if (IdentifierInfo *II = FD->getIdentifier()) {
3263 // Detect duplicate member names.
3264 if (!FieldIDs.insert(II)) {
Chris Lattner65cae292008-11-19 08:23:25 +00003265 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Chris Lattner4b009652007-07-25 00:24:17 +00003266 // Find the previous decl.
3267 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00003268 for (unsigned i = 0; ; ++i) {
3269 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00003270 if (RecFields[i]->getIdentifier() == II) {
3271 PrevLoc = RecFields[i]->getLocation();
3272 break;
3273 }
3274 }
Chris Lattner1336cab2008-11-23 23:12:31 +00003275 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003276 FD->setInvalidDecl();
3277 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003278 continue;
3279 }
3280 ++NumNamedMembers;
3281 }
Chris Lattner4b009652007-07-25 00:24:17 +00003282 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003283
Chris Lattner4b009652007-07-25 00:24:17 +00003284 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003285 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003286 Record->completeDefinition(Context);
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00003287 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3288 // Sema::ActOnFinishCXXClassDef.
3289 if (!isa<CXXRecordDecl>(Record))
3290 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003291 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003292 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003293 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003294 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003295 // Must enforce the rule that ivars in the base classes may not be
3296 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003297 if (ID->getSuperClass()) {
3298 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3299 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3300 ObjCIvarDecl* Ivar = (*IVI);
3301 IdentifierInfo *II = Ivar->getIdentifier();
3302 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3303 if (prevIvar) {
3304 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3305 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003306 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003307 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003308 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003309 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003310 else if (ObjCImplementationDecl *IMPDecl =
3311 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003312 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3313 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003314 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003315 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003316 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003317
3318 if (Attr)
3319 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003320}
3321
Douglas Gregord8028382009-01-05 19:45:36 +00003322void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
Douglas Gregorf0464ec2009-01-06 07:17:58 +00003323 EnumDecl *Enum = cast<EnumDecl>((Decl *)EnumD);
Douglas Gregord8028382009-01-05 19:45:36 +00003324
Douglas Gregorf0464ec2009-01-06 07:17:58 +00003325 // Enter the enumeration context.
3326 PushDeclContext(S, Enum);
Douglas Gregord8028382009-01-05 19:45:36 +00003327}
3328
Steve Naroff0acc9c92007-09-15 18:49:24 +00003329Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003330 DeclTy *lastEnumConst,
3331 SourceLocation IdLoc, IdentifierInfo *Id,
3332 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003333 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003334 EnumConstantDecl *LastEnumConst =
3335 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3336 Expr *Val = static_cast<Expr*>(val);
3337
Chris Lattnera7549902007-08-26 06:24:45 +00003338 // The scope passed in may not be a decl scope. Zip up the scope tree until
3339 // we find one that is.
3340 while ((S->getFlags() & Scope::DeclScope) == 0)
3341 S = S->getParent();
3342
Chris Lattner4b009652007-07-25 00:24:17 +00003343 // Verify that there isn't already something declared with this name in this
3344 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003345 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003346 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003347 // Maybe we will complain about the shadowed template parameter.
3348 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3349 // Just pretend that we didn't see the previous declaration.
3350 PrevDecl = 0;
3351 }
3352
3353 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003354 // When in C++, we may get a TagDecl with the same name; in this case the
3355 // enum constant will 'hide' the tag.
3356 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3357 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003358 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003359 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003360 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003361 else
Chris Lattner65cae292008-11-19 08:23:25 +00003362 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003363 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003364 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003365 return 0;
3366 }
3367 }
3368
3369 llvm::APSInt EnumVal(32);
3370 QualType EltTy;
3371 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003372 // Make sure to promote the operand type to int.
3373 UsualUnaryConversions(Val);
3374
Chris Lattner4b009652007-07-25 00:24:17 +00003375 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3376 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003377 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003378 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003379 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003380 } else {
3381 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003382 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003383 }
3384
3385 if (!Val) {
3386 if (LastEnumConst) {
3387 // Assign the last value + 1.
3388 EnumVal = LastEnumConst->getInitVal();
3389 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003390
3391 // Check for overflow on increment.
3392 if (EnumVal < LastEnumConst->getInitVal())
3393 Diag(IdLoc, diag::warn_enum_value_overflow);
3394
Chris Lattnere7f53a42007-08-27 17:37:24 +00003395 EltTy = LastEnumConst->getType();
3396 } else {
3397 // First value, set to zero.
3398 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003399 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003400 }
Chris Lattner4b009652007-07-25 00:24:17 +00003401 }
3402
Chris Lattnere4650482008-03-15 06:12:44 +00003403 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003404 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3405 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003406 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003407
3408 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003409 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003410
3411 // Add this enumerator into the enum itself.
3412 // FIXME: This means that the enumerator is stored in two
3413 // DeclContexts. This is not a long-term solution.
3414 New->setLexicalDeclContext(TheEnumDecl);
3415 TheEnumDecl->addDecl(Context, New, true);
Chris Lattner4b009652007-07-25 00:24:17 +00003416 return New;
3417}
3418
Steve Naroffb0726b82008-08-07 14:08:16 +00003419// FIXME: For consistency with ActOnFields(), we should have the parser
3420// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003421void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003422 DeclTy **Elements, unsigned NumElements) {
3423 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003424 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003425
Douglas Gregord8028382009-01-05 19:45:36 +00003426 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3427 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3428 // Diagnose code like:
3429 // enum e0 {
3430 // E0 = sizeof(enum e0 { E1 })
3431 // };
3432 Diag(Def->getLocation(), diag::err_nested_redefinition)
3433 << Enum->getDeclName();
3434 Diag(Enum->getLocation(), diag::note_previous_definition);
3435 Enum->setInvalidDecl();
3436 PopDeclContext();
3437 return;
Steve Naroffb0726b82008-08-07 14:08:16 +00003438 }
Douglas Gregord8028382009-01-05 19:45:36 +00003439
Chris Lattner435c3fd2007-08-28 05:10:31 +00003440 // TODO: If the result value doesn't fit in an int, it must be a long or long
3441 // long value. ISO C does not support this, but GCC does as an extension,
3442 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003443 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003444
Chris Lattner206754a2007-08-28 06:15:15 +00003445 // Verify that all the values are okay, compute the size of the values, and
3446 // reverse the list.
3447 unsigned NumNegativeBits = 0;
3448 unsigned NumPositiveBits = 0;
3449
3450 // Keep track of whether all elements have type int.
3451 bool AllElementsInt = true;
3452
Chris Lattner4b009652007-07-25 00:24:17 +00003453 EnumConstantDecl *EltList = 0;
3454 for (unsigned i = 0; i != NumElements; ++i) {
3455 EnumConstantDecl *ECD =
3456 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3457 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003458
3459 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003460 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003461 assert(InitVal.getBitWidth() >= IntWidth &&
3462 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003463 if (InitVal.getBitWidth() > IntWidth) {
3464 llvm::APSInt V(InitVal);
3465 V.trunc(IntWidth);
3466 V.extend(InitVal.getBitWidth());
3467 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003468 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3469 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003470 }
Chris Lattner206754a2007-08-28 06:15:15 +00003471
3472 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003473 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003474 NumPositiveBits = std::max(NumPositiveBits,
3475 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003476 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003477 NumNegativeBits = std::max(NumNegativeBits,
3478 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003479
Chris Lattner206754a2007-08-28 06:15:15 +00003480 // Keep track of whether every enum element has type int (very commmon).
3481 if (AllElementsInt)
3482 AllElementsInt = ECD->getType() == Context.IntTy;
3483
Chris Lattner4b009652007-07-25 00:24:17 +00003484 ECD->setNextDeclarator(EltList);
3485 EltList = ECD;
3486 }
3487
Chris Lattner206754a2007-08-28 06:15:15 +00003488 // Figure out the type that should be used for this enum.
3489 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3490 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003491 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003492
3493 if (NumNegativeBits) {
3494 // If there is a negative value, figure out the smallest integer type (of
3495 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003496 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003497 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003498 BestWidth = IntWidth;
3499 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003500 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003501
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003502 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003503 BestType = Context.LongTy;
3504 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003505 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003506
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003507 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003508 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3509 BestType = Context.LongLongTy;
3510 }
3511 }
3512 } else {
3513 // If there is no negative value, figure out which of uint, ulong, ulonglong
3514 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003515 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003516 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003517 BestWidth = IntWidth;
3518 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003519 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003520 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003521 } else {
3522 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003523 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003524 "How could an initializer get larger than ULL?");
3525 BestType = Context.UnsignedLongLongTy;
3526 }
3527 }
3528
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003529 // Loop over all of the enumerator constants, changing their types to match
3530 // the type of the enum if needed.
3531 for (unsigned i = 0; i != NumElements; ++i) {
3532 EnumConstantDecl *ECD =
3533 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3534 if (!ECD) continue; // Already issued a diagnostic.
3535
3536 // Standard C says the enumerators have int type, but we allow, as an
3537 // extension, the enumerators to be larger than int size. If each
3538 // enumerator value fits in an int, type it as an int, otherwise type it the
3539 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3540 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003541 if (ECD->getType() == Context.IntTy) {
3542 // Make sure the init value is signed.
3543 llvm::APSInt IV = ECD->getInitVal();
3544 IV.setIsSigned(true);
3545 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003546
3547 if (getLangOptions().CPlusPlus)
3548 // C++ [dcl.enum]p4: Following the closing brace of an
3549 // enum-specifier, each enumerator has the type of its
3550 // enumeration.
3551 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003552 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003553 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003554
3555 // Determine whether the value fits into an int.
3556 llvm::APSInt InitVal = ECD->getInitVal();
3557 bool FitsInInt;
3558 if (InitVal.isUnsigned() || !InitVal.isNegative())
3559 FitsInInt = InitVal.getActiveBits() < IntWidth;
3560 else
3561 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3562
3563 // If it fits into an integer type, force it. Otherwise force it to match
3564 // the enum decl type.
3565 QualType NewTy;
3566 unsigned NewWidth;
3567 bool NewSign;
3568 if (FitsInInt) {
3569 NewTy = Context.IntTy;
3570 NewWidth = IntWidth;
3571 NewSign = true;
3572 } else if (ECD->getType() == BestType) {
3573 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003574 if (getLangOptions().CPlusPlus)
3575 // C++ [dcl.enum]p4: Following the closing brace of an
3576 // enum-specifier, each enumerator has the type of its
3577 // enumeration.
3578 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003579 continue;
3580 } else {
3581 NewTy = BestType;
3582 NewWidth = BestWidth;
3583 NewSign = BestType->isSignedIntegerType();
3584 }
3585
3586 // Adjust the APSInt value.
3587 InitVal.extOrTrunc(NewWidth);
3588 InitVal.setIsSigned(NewSign);
3589 ECD->setInitVal(InitVal);
3590
3591 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003592 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3593 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003594 if (getLangOptions().CPlusPlus)
3595 // C++ [dcl.enum]p4: Following the closing brace of an
3596 // enum-specifier, each enumerator has the type of its
3597 // enumeration.
3598 ECD->setType(EnumType);
3599 else
3600 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003601 }
Chris Lattner206754a2007-08-28 06:15:15 +00003602
Douglas Gregor8acb7272008-12-11 16:49:14 +00003603 Enum->completeDefinition(Context, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003604 Consumer.HandleTagDeclDefinition(Enum);
Douglas Gregord8028382009-01-05 19:45:36 +00003605
3606 // Leave the context of the enumeration.
3607 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00003608}
3609
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003610Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003611 ExprArg expr) {
3612 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3613
Chris Lattner81db64a2008-03-16 00:16:02 +00003614 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003615}
3616
Douglas Gregorad17e372008-12-16 22:23:02 +00003617
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003618void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3619 ExprTy *alignment, SourceLocation PragmaLoc,
3620 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3621 Expr *Alignment = static_cast<Expr *>(alignment);
3622
3623 // If specified then alignment must be a "small" power of two.
3624 unsigned AlignmentVal = 0;
3625 if (Alignment) {
3626 llvm::APSInt Val;
3627 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3628 !Val.isPowerOf2() ||
3629 Val.getZExtValue() > 16) {
3630 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3631 delete Alignment;
3632 return; // Ignore
3633 }
3634
3635 AlignmentVal = (unsigned) Val.getZExtValue();
3636 }
3637
3638 switch (Kind) {
3639 case Action::PPK_Default: // pack([n])
3640 PackContext.setAlignment(AlignmentVal);
3641 break;
3642
3643 case Action::PPK_Show: // pack(show)
3644 // Show the current alignment, making sure to show the right value
3645 // for the default.
3646 AlignmentVal = PackContext.getAlignment();
3647 // FIXME: This should come from the target.
3648 if (AlignmentVal == 0)
3649 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003650 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003651 break;
3652
3653 case Action::PPK_Push: // pack(push [, id] [, [n])
3654 PackContext.push(Name);
3655 // Set the new alignment if specified.
3656 if (Alignment)
3657 PackContext.setAlignment(AlignmentVal);
3658 break;
3659
3660 case Action::PPK_Pop: // pack(pop [, id] [, n])
3661 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3662 // "#pragma pack(pop, identifier, n) is undefined"
3663 if (Alignment && Name)
3664 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3665
3666 // Do the pop.
3667 if (!PackContext.pop(Name)) {
3668 // If a name was specified then failure indicates the name
3669 // wasn't found. Otherwise failure indicates the stack was
3670 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003671 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3672 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003673
3674 // FIXME: Warn about popping named records as MSVC does.
3675 } else {
3676 // Pop succeeded, set the new alignment if specified.
3677 if (Alignment)
3678 PackContext.setAlignment(AlignmentVal);
3679 }
3680 break;
3681
3682 default:
3683 assert(0 && "Invalid #pragma pack kind.");
3684 }
3685}
3686
3687bool PragmaPackStack::pop(IdentifierInfo *Name) {
3688 if (Stack.empty())
3689 return false;
3690
3691 // If name is empty just pop top.
3692 if (!Name) {
3693 Alignment = Stack.back().first;
3694 Stack.pop_back();
3695 return true;
3696 }
3697
3698 // Otherwise, find the named record.
3699 for (unsigned i = Stack.size(); i != 0; ) {
3700 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003701 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003702 // Found it, pop up to and including this record.
3703 Alignment = Stack[i].first;
3704 Stack.erase(Stack.begin() + i, Stack.end());
3705 return true;
3706 }
3707 }
3708
3709 return false;
3710}