blob: 54f84cf40ee58a5896012e14b934ba676303e601 [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"
Chris Lattner52a425b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.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
Steve Naroff7b36a1b2009-01-28 19:39:02 +000034Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S,
35 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000036 DeclContext *DC = 0;
Steve Naroffc349ee22009-01-29 00:07:50 +000037
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000038 if (SS) {
39 if (SS->isInvalid())
40 return 0;
41 DC = static_cast<DeclContext*>(SS->getScopeRep());
42 }
Steve Naroffc349ee22009-01-29 00:07:50 +000043 LookupResult Result = DC ?
44 LookupDeclInContext(&II, Decl::IDNS_Ordinary, DC) :
45 LookupDeclInScope(&II, Decl::IDNS_Ordinary, S);
46
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000047 Decl *IIDecl = 0;
48 switch (Result.getKind()) {
49 case LookupResult::NotFound:
50 case LookupResult::FoundOverloaded:
51 case LookupResult::AmbiguousBaseSubobjectTypes:
52 case LookupResult::AmbiguousBaseSubobjects:
53 // FIXME: In the event of an ambiguous lookup, we could visit all of
54 // the entities found to determine whether they are all types. This
55 // might provide better diagnostics.
56 return 0;
57
58 case LookupResult::Found:
59 IIDecl = Result.getAsDecl();
60 break;
61 }
62
63 if (isa<TypedefDecl>(IIDecl) ||
64 isa<ObjCInterfaceDecl>(IIDecl) ||
65 isa<TagDecl>(IIDecl) ||
66 isa<TemplateTypeParmDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000067 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000068 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000069}
70
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000071DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000072 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000074 if (MD->isOutOfLineDefinition())
75 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000076
77 // A C++ inline method is parsed *after* the topmost class it was declared in
78 // is fully parsed (it's "complete").
79 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000080 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000081 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
82 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000083 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000084 DC = RD;
85
86 // Return the declaration context of the topmost class the inline method is
87 // declared in.
88 return DC;
89 }
90
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000091 if (isa<ObjCMethodDecl>(DC))
92 return Context.getTranslationUnitDecl();
93
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000094 if (Decl *D = dyn_cast<Decl>(DC))
95 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000096
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000097 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000098}
99
Douglas Gregor8acb7272008-12-11 16:49:14 +0000100void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000101 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +0000102 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000103 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000104 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000105}
106
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000107void Sema::PopDeclContext() {
108 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000109
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000110 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000111}
112
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000113/// Add this decl to the scope shadowed decl chains.
114void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000115 // Move up the scope chain until we find the nearest enclosing
116 // non-transparent context. The declaration will be introduced into this
117 // scope.
118 while (S->getEntity() &&
119 ((DeclContext *)S->getEntity())->isTransparentContext())
120 S = S->getParent();
121
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000122 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000123
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000124 // Add scoped declarations into their context, so that they can be
125 // found later. Declarations without a context won't be inserted
126 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000127 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000128
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000129 // C++ [basic.scope]p4:
130 // -- exactly one declaration shall declare a class name or
131 // enumeration name that is not a typedef name and the other
132 // declarations shall all refer to the same object or
133 // enumerator, or all refer to functions and function templates;
134 // in this case the class name or enumeration name is hidden.
135 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
136 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000137 if (CurContext->getLookupContext()
138 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000139 // We're pushing the tag into the current context, which might
140 // require some reshuffling in the identifier resolver.
141 IdentifierResolver::iterator
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000142 I = IdResolver.begin(TD->getDeclName(), CurContext,
143 false/*LookInParentCtx*/),
144 IEnd = IdResolver.end();
145 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
146 NamedDecl *PrevDecl = *I;
147 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
148 PrevDecl = *I, ++I) {
149 if (TD->declarationReplaces(*I)) {
150 // This is a redeclaration. Remove it from the chain and
151 // break out, so that we'll add in the shadowed
152 // declaration.
153 S->RemoveDecl(*I);
154 if (PrevDecl == *I) {
155 IdResolver.RemoveDecl(*I);
156 IdResolver.AddDecl(TD);
157 return;
158 } else {
159 IdResolver.RemoveDecl(*I);
160 break;
161 }
162 }
163 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000164
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000165 // There is already a declaration with the same name in the same
166 // scope, which is not a tag declaration. It must be found
167 // before we find the new declaration, so insert the new
168 // declaration at the end of the chain.
169 IdResolver.AddShadowedDecl(TD, PrevDecl);
170
171 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000172 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000173 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000174 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000175 // We are pushing the name of a function, which might be an
176 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000177 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000178 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000179 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000180 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000181 false/*LookInParentCtx*/),
182 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000192
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000194}
195
Steve Naroff9637a9b2007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000200
Chris Lattner4b009652007-07-25 00:24:17 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000205
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000210
Douglas Gregor8acb7272008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000213 }
214}
215
Steve Naroffe57c21a2008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Steve Naroffc349ee22009-01-29 00:07:50 +0000221 Decl *IDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, 0);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222
Steve Naroff6384a012008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000224}
225
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Steve Naroffc349ee22009-01-29 00:07:50 +0000258/// LookupDeclInScope - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000259/// namespace. NamespaceNameOnly - during lookup only namespace names
260/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
261/// 'When looking up a namespace-name in a using-directive or
262/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor78d70132009-01-14 22:20:51 +0000263///
264/// Note: The use of this routine is deprecated. Please use
265/// LookupName, LookupQualifiedName, or LookupParsedName instead.
266Sema::LookupResult
Steve Naroffc349ee22009-01-29 00:07:50 +0000267Sema::LookupDeclInScope(DeclarationName Name, unsigned NSI, Scope *S,
268 bool LookInParent) {
Douglas Gregor78d70132009-01-14 22:20:51 +0000269 LookupCriteria::NameKind Kind;
270 if (NSI == Decl::IDNS_Ordinary) {
Steve Naroff98446332009-01-28 16:09:22 +0000271 Kind = LookupCriteria::Ordinary;
Douglas Gregor78d70132009-01-14 22:20:51 +0000272 } else if (NSI == Decl::IDNS_Tag)
273 Kind = LookupCriteria::Tag;
Chris Lattner50500f62009-01-16 19:44:00 +0000274 else {
275 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregor78d70132009-01-14 22:20:51 +0000276 Kind = LookupCriteria::Member;
Chris Lattner50500f62009-01-16 19:44:00 +0000277 }
Douglas Gregor78d70132009-01-14 22:20:51 +0000278 // Unqualified lookup
279 return LookupName(S, Name,
280 LookupCriteria(Kind, !LookInParent,
281 getLangOptions().CPlusPlus));
Chris Lattner4b009652007-07-25 00:24:17 +0000282}
283
Steve Naroffc349ee22009-01-29 00:07:50 +0000284Sema::LookupResult
285Sema::LookupDeclInContext(DeclarationName Name, unsigned NSI,
286 const DeclContext *LookupCtx,
287 bool LookInParent) {
288 assert(LookupCtx && "LookupDeclInContext(): Missing DeclContext");
289 LookupCriteria::NameKind Kind;
290 if (NSI == Decl::IDNS_Ordinary) {
291 Kind = LookupCriteria::Ordinary;
292 } else if (NSI == Decl::IDNS_Tag)
293 Kind = LookupCriteria::Tag;
294 else {
295 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
296 Kind = LookupCriteria::Member;
297 }
298 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
299 LookupCriteria(Kind, !LookInParent,
300 getLangOptions().CPlusPlus));
301}
302
Chris Lattnera9c87f22008-05-05 22:18:14 +0000303void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000304 if (!Context.getBuiltinVaListType().isNull())
305 return;
306
307 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffc349ee22009-01-29 00:07:50 +0000308 Decl *VaDecl = LookupDeclInScope(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000309 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000310 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
311}
312
Chris Lattner4b009652007-07-25 00:24:17 +0000313/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
314/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000315NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
316 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000317 Builtin::ID BID = (Builtin::ID)bid;
318
Chris Lattnerb23469f2008-09-28 05:54:29 +0000319 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000320 InitBuiltinVaListType();
321
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000322 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000323 FunctionDecl *New = FunctionDecl::Create(Context,
324 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000325 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000326 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000327
Chris Lattnera9c87f22008-05-05 22:18:14 +0000328 // Create Decl objects for each parameter, adding them to the
329 // FunctionDecl.
330 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
331 llvm::SmallVector<ParmVarDecl*, 16> Params;
332 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
333 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000334 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000335 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000336 }
337
338
339
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000340 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000341 // FIXME: This is hideous. We need to teach PushOnScopeChains to
342 // relate Scopes to DeclContexts, and probably eliminate CurContext
343 // entirely, but we're not there yet.
344 DeclContext *SavedContext = CurContext;
345 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000346 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000347 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000348 return New;
349}
350
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000351/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
352/// everything from the standard library is defined.
353NamespaceDecl *Sema::GetStdNamespace() {
354 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000355 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000356 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroffc349ee22009-01-29 00:07:50 +0000357 Decl *Std = LookupDeclInContext(StdIdent, Decl::IDNS_Ordinary, Global);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000358 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
359 }
360 return StdNamespace;
361}
362
Chris Lattner4b009652007-07-25 00:24:17 +0000363/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
364/// and scope as a previous declaration 'Old'. Figure out how to resolve this
365/// situation, merging decls or emitting diagnostics as appropriate.
366///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000367TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000368 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000369 // Allow multiple definitions for ObjC built-in typedefs.
370 // FIXME: Verify the underlying types are equivalent!
371 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000372 const IdentifierInfo *TypeID = New->getIdentifier();
373 switch (TypeID->getLength()) {
374 default: break;
375 case 2:
376 if (!TypeID->isStr("id"))
377 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000378 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000379 objc_types = true;
380 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000381 case 5:
382 if (!TypeID->isStr("Class"))
383 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000384 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000385 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000386 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000387 case 3:
388 if (!TypeID->isStr("SEL"))
389 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000390 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000391 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000392 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000393 case 8:
394 if (!TypeID->isStr("Protocol"))
395 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000396 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000397 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000398 return New;
399 }
400 // Fall through - the typedef name was not a builtin type.
401 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000402 // Verify the old decl was also a type.
403 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000404 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000405 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000406 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000407 if (!objc_types)
408 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000409 return New;
410 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000411
412 // Determine the "old" type we'll use for checking and diagnostics.
413 QualType OldType;
414 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
415 OldType = OldTypedef->getUnderlyingType();
416 else
417 OldType = Context.getTypeDeclType(Old);
418
Chris Lattnerbef8d622008-07-25 18:44:27 +0000419 // If the typedef types are not identical, reject them in all languages and
420 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000421
422 if (OldType != New->getUnderlyingType() &&
423 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000424 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000425 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000426 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000427 if (!objc_types)
428 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000429 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000430 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000431 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000432 if (getLangOptions().Microsoft) return New;
433
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000434 // C++ [dcl.typedef]p2:
435 // In a given non-class scope, a typedef specifier can be used to
436 // redefine the name of any type declared in that scope to refer
437 // to the type to which it already refers.
438 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
439 return New;
440
441 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000442 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
443 // *either* declaration is in a system header. The code below implements
444 // this adhoc compatibility rule. FIXME: The following code will not
445 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000446 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
447 SourceManager &SrcMgr = Context.getSourceManager();
448 if (SrcMgr.isInSystemHeader(Old->getLocation()))
449 return New;
450 if (SrcMgr.isInSystemHeader(New->getLocation()))
451 return New;
452 }
Eli Friedman324d5032008-06-11 06:20:39 +0000453
Chris Lattnerb1753422008-11-23 21:45:46 +0000454 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000455 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000456 return New;
457}
458
Chris Lattner6953a072008-06-26 18:38:35 +0000459/// DeclhasAttr - returns true if decl Declaration already has the target
460/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000461static bool DeclHasAttr(const Decl *decl, const Attr *target) {
462 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
463 if (attr->getKind() == target->getKind())
464 return true;
465
466 return false;
467}
468
469/// MergeAttributes - append attributes from the Old decl to the New one.
470static void MergeAttributes(Decl *New, Decl *Old) {
471 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
472
Chris Lattner402b3372008-03-03 03:28:21 +0000473 while (attr) {
474 tmp = attr;
475 attr = attr->getNext();
476
477 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000478 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000479 New->addAttr(tmp);
480 } else {
481 tmp->setNext(0);
482 delete(tmp);
483 }
484 }
Nuno Lopes77654342008-06-01 22:53:53 +0000485
486 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000487}
488
Chris Lattner3e254fb2008-04-08 04:40:51 +0000489/// MergeFunctionDecl - We just parsed a function 'New' from
490/// declarator D which has the same name and scope as a previous
491/// declaration 'Old'. Figure out how to resolve this situation,
492/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000493/// Redeclaration will be set true if this New is a redeclaration OldD.
494///
495/// In C++, New and Old must be declarations that are not
496/// overloaded. Use IsOverload to determine whether New and Old are
497/// overloaded, and to select the Old declaration that New should be
498/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000499FunctionDecl *
500Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000501 assert(!isa<OverloadedFunctionDecl>(OldD) &&
502 "Cannot merge with an overloaded function declaration");
503
Douglas Gregor42214c52008-04-21 02:02:58 +0000504 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000505 // Verify the old decl was also a function.
506 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
507 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000508 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000509 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000510 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000511 return New;
512 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000513
514 // Determine whether the previous declaration was a definition,
515 // implicit declaration, or a declaration.
516 diag::kind PrevDiag;
517 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000518 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000519 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000520 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000521 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000522 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000523
Chris Lattner42a21742008-04-06 23:10:54 +0000524 QualType OldQType = Context.getCanonicalType(Old->getType());
525 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000526
Douglas Gregord2baafd2008-10-21 16:13:35 +0000527 if (getLangOptions().CPlusPlus) {
528 // (C++98 13.1p2):
529 // Certain function declarations cannot be overloaded:
530 // -- Function declarations that differ only in the return type
531 // cannot be overloaded.
532 QualType OldReturnType
533 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
534 QualType NewReturnType
535 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
536 if (OldReturnType != NewReturnType) {
537 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
538 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000539 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000540 return New;
541 }
542
543 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
544 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
545 if (OldMethod && NewMethod) {
546 // -- Member function declarations with the same name and the
547 // same parameter types cannot be overloaded if any of them
548 // is a static member function declaration.
549 if (OldMethod->isStatic() || NewMethod->isStatic()) {
550 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
551 Diag(Old->getLocation(), PrevDiag);
552 return New;
553 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000554
555 // C++ [class.mem]p1:
556 // [...] A member shall not be declared twice in the
557 // member-specification, except that a nested class or member
558 // class template can be declared and then later defined.
559 if (OldMethod->getLexicalDeclContext() ==
560 NewMethod->getLexicalDeclContext()) {
561 unsigned NewDiag;
562 if (isa<CXXConstructorDecl>(OldMethod))
563 NewDiag = diag::err_constructor_redeclared;
564 else if (isa<CXXDestructorDecl>(NewMethod))
565 NewDiag = diag::err_destructor_redeclared;
566 else if (isa<CXXConversionDecl>(NewMethod))
567 NewDiag = diag::err_conv_function_redeclared;
568 else
569 NewDiag = diag::err_member_redeclared;
570
571 Diag(New->getLocation(), NewDiag);
572 Diag(Old->getLocation(), PrevDiag);
573 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000574 }
575
576 // (C++98 8.3.5p3):
577 // All declarations for a function shall agree exactly in both the
578 // return type and the parameter-type-list.
579 if (OldQType == NewQType) {
580 // We have a redeclaration.
581 MergeAttributes(New, Old);
582 Redeclaration = true;
583 return MergeCXXFunctionDecl(New, Old);
584 }
585
586 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000587 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000588
589 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000590 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000591 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000592 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000593 MergeAttributes(New, Old);
594 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000595 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000596 }
Chris Lattner1470b072007-11-06 06:07:26 +0000597
Steve Naroff6c9e7922008-01-16 15:01:34 +0000598 // A function that has already been declared has been redeclared or defined
599 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000600
Chris Lattner4b009652007-07-25 00:24:17 +0000601 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
602 // TODO: This is totally simplistic. It should handle merging functions
603 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000604 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000605 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000606 return New;
607}
608
Steve Naroffb5e78152008-08-08 17:50:35 +0000609/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000610static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000611 if (VD->isFileVarDecl())
612 return (!VD->getInit() &&
613 (VD->getStorageClass() == VarDecl::None ||
614 VD->getStorageClass() == VarDecl::Static));
615 return false;
616}
617
618/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
619/// when dealing with C "tentative" external object definitions (C99 6.9.2).
620void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
621 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000622 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000623
Douglas Gregor3a423132009-01-07 16:34:42 +0000624 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000625 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000626 for (IdentifierResolver::iterator
627 I = IdResolver.begin(VD->getIdentifier(),
628 VD->getDeclContext(), false/*LookInParentCtx*/),
629 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000630 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000631 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
632
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000633 // Handle the following case:
634 // int a[10];
635 // int a[]; - the code below makes sure we set the correct type.
636 // int a[11]; - this is an error, size isn't 10.
637 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
638 OldDecl->getType()->isConstantArrayType())
639 VD->setType(OldDecl->getType());
640
Steve Naroffb5e78152008-08-08 17:50:35 +0000641 // Check for "tentative" definitions. We can't accomplish this in
642 // MergeVarDecl since the initializer hasn't been attached.
643 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
644 continue;
645
646 // Handle __private_extern__ just like extern.
647 if (OldDecl->getStorageClass() != VarDecl::Extern &&
648 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
649 VD->getStorageClass() != VarDecl::Extern &&
650 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000651 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000652 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000653 }
654 }
655 }
656}
657
Chris Lattner4b009652007-07-25 00:24:17 +0000658/// MergeVarDecl - We just parsed a variable 'New' which has the same name
659/// and scope as a previous declaration 'Old'. Figure out how to resolve this
660/// situation, merging decls or emitting diagnostics as appropriate.
661///
Steve Naroffb5e78152008-08-08 17:50:35 +0000662/// Tentative definition rules (C99 6.9.2p2) are checked by
663/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
664/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000665///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000666VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000667 // Verify the old decl was also a variable.
668 VarDecl *Old = dyn_cast<VarDecl>(OldD);
669 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000670 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000671 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000672 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000673 return New;
674 }
Chris Lattner402b3372008-03-03 03:28:21 +0000675
676 MergeAttributes(New, Old);
677
Eli Friedman4a480d62009-01-24 23:49:55 +0000678 // Merge the types
679 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
680 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000681 Diag(New->getLocation(), diag::err_redefinition_different_type)
682 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000683 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000684 return New;
685 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000686 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000687 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
688 if (New->getStorageClass() == VarDecl::Static &&
689 (Old->getStorageClass() == VarDecl::None ||
690 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000691 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000692 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000693 return New;
694 }
695 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
696 if (New->getStorageClass() != VarDecl::Static &&
697 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000698 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000699 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000700 return New;
701 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000702 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
703 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000704 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000705 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000706 }
707 return New;
708}
709
Chris Lattner3e254fb2008-04-08 04:40:51 +0000710/// CheckParmsForFunctionDef - Check that the parameters of the given
711/// function are appropriate for the definition of a function. This
712/// takes care of any checks that cannot be performed on the
713/// declaration itself, e.g., that the types of each of the function
714/// parameters are complete.
715bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
716 bool HasInvalidParm = false;
717 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
718 ParmVarDecl *Param = FD->getParamDecl(p);
719
720 // C99 6.7.5.3p4: the parameters in a parameter type list in a
721 // function declarator that is part of a function definition of
722 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000723 if (!Param->isInvalidDecl() &&
724 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
725 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000726 Param->setInvalidDecl();
727 HasInvalidParm = true;
728 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000729
730 // C99 6.9.1p5: If the declarator includes a parameter type list, the
731 // declaration of each parameter shall include an identifier.
732 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
733 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000734 }
735
736 return HasInvalidParm;
737}
738
Chris Lattner4b009652007-07-25 00:24:17 +0000739/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
740/// no declarator (e.g. "struct foo;") is parsed.
741Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000742 TagDecl *Tag
743 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
744 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
745 if (!Record->getDeclName() && Record->isDefinition() &&
746 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
747 return BuildAnonymousStructOrUnion(S, DS, Record);
748
749 // Microsoft allows unnamed struct/union fields. Don't complain
750 // about them.
751 // FIXME: Should we support Microsoft's extensions in this area?
752 if (Record->getDeclName() && getLangOptions().Microsoft)
753 return Tag;
754 }
755
Sebastian Redlb7605e82008-12-28 15:28:59 +0000756 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000757 // Warn about typedefs of enums without names, since this is an
758 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000759 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
760 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000761 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000762 << DS.getSourceRange();
763 return Tag;
764 }
765
Sebastian Redlb7605e82008-12-28 15:28:59 +0000766 // FIXME: This diagnostic is emitted even when various previous
767 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
768 // DeclSpec has no means of communicating this information, and the
769 // responsible parser functions are quite far apart.
770 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
771 << DS.getSourceRange();
772 return 0;
773 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000774
Douglas Gregor723d3332009-01-07 00:43:41 +0000775 return Tag;
776}
777
778/// InjectAnonymousStructOrUnionMembers - Inject the members of the
779/// anonymous struct or union AnonRecord into the owning context Owner
780/// and scope S. This routine will be invoked just after we realize
781/// that an unnamed union or struct is actually an anonymous union or
782/// struct, e.g.,
783///
784/// @code
785/// union {
786/// int i;
787/// float f;
788/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
789/// // f into the surrounding scope.x
790/// @endcode
791///
792/// This routine is recursive, injecting the names of nested anonymous
793/// structs/unions into the owning context and scope as well.
794bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
795 RecordDecl *AnonRecord) {
796 bool Invalid = false;
797 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
798 FEnd = AnonRecord->field_end();
799 F != FEnd; ++F) {
800 if ((*F)->getDeclName()) {
Steve Naroffc349ee22009-01-29 00:07:50 +0000801 Decl *PrevDecl = LookupDeclInContext((*F)->getDeclName(),
802 Decl::IDNS_Ordinary, Owner, false);
Douglas Gregor723d3332009-01-07 00:43:41 +0000803 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
804 // C++ [class.union]p2:
805 // The names of the members of an anonymous union shall be
806 // distinct from the names of any other entity in the
807 // scope in which the anonymous union is declared.
808 unsigned diagKind
809 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
810 : diag::err_anonymous_struct_member_redecl;
811 Diag((*F)->getLocation(), diagKind)
812 << (*F)->getDeclName();
813 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
814 Invalid = true;
815 } else {
816 // C++ [class.union]p2:
817 // For the purpose of name lookup, after the anonymous union
818 // definition, the members of the anonymous union are
819 // considered to have been defined in the scope in which the
820 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000821 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000822 S->AddDecl(*F);
823 IdResolver.AddDecl(*F);
824 }
825 } else if (const RecordType *InnerRecordType
826 = (*F)->getType()->getAsRecordType()) {
827 RecordDecl *InnerRecord = InnerRecordType->getDecl();
828 if (InnerRecord->isAnonymousStructOrUnion())
829 Invalid = Invalid ||
830 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
831 }
832 }
833
834 return Invalid;
835}
836
837/// ActOnAnonymousStructOrUnion - Handle the declaration of an
838/// anonymous structure or union. Anonymous unions are a C++ feature
839/// (C++ [class.union]) and a GNU C extension; anonymous structures
840/// are a GNU C and GNU C++ extension.
841Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
842 RecordDecl *Record) {
843 DeclContext *Owner = Record->getDeclContext();
844
845 // Diagnose whether this anonymous struct/union is an extension.
846 if (Record->isUnion() && !getLangOptions().CPlusPlus)
847 Diag(Record->getLocation(), diag::ext_anonymous_union);
848 else if (!Record->isUnion())
849 Diag(Record->getLocation(), diag::ext_anonymous_struct);
850
851 // C and C++ require different kinds of checks for anonymous
852 // structs/unions.
853 bool Invalid = false;
854 if (getLangOptions().CPlusPlus) {
855 const char* PrevSpec = 0;
856 // C++ [class.union]p3:
857 // Anonymous unions declared in a named namespace or in the
858 // global namespace shall be declared static.
859 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
860 (isa<TranslationUnitDecl>(Owner) ||
861 (isa<NamespaceDecl>(Owner) &&
862 cast<NamespaceDecl>(Owner)->getDeclName()))) {
863 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
864 Invalid = true;
865
866 // Recover by adding 'static'.
867 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
868 }
869 // C++ [class.union]p3:
870 // A storage class is not allowed in a declaration of an
871 // anonymous union in a class scope.
872 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
873 isa<RecordDecl>(Owner)) {
874 Diag(DS.getStorageClassSpecLoc(),
875 diag::err_anonymous_union_with_storage_spec);
876 Invalid = true;
877
878 // Recover by removing the storage specifier.
879 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
880 PrevSpec);
881 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000882
883 // C++ [class.union]p2:
884 // The member-specification of an anonymous union shall only
885 // define non-static data members. [Note: nested types and
886 // functions cannot be declared within an anonymous union. ]
887 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
888 MemEnd = Record->decls_end();
889 Mem != MemEnd; ++Mem) {
890 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
891 // C++ [class.union]p3:
892 // An anonymous union shall not have private or protected
893 // members (clause 11).
894 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
895 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
896 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
897 Invalid = true;
898 }
899 } else if ((*Mem)->isImplicit()) {
900 // Any implicit members are fine.
901 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
902 if (!MemRecord->isAnonymousStructOrUnion() &&
903 MemRecord->getDeclName()) {
904 // This is a nested type declaration.
905 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
906 << (int)Record->isUnion();
907 Invalid = true;
908 }
909 } else {
910 // We have something that isn't a non-static data
911 // member. Complain about it.
912 unsigned DK = diag::err_anonymous_record_bad_member;
913 if (isa<TypeDecl>(*Mem))
914 DK = diag::err_anonymous_record_with_type;
915 else if (isa<FunctionDecl>(*Mem))
916 DK = diag::err_anonymous_record_with_function;
917 else if (isa<VarDecl>(*Mem))
918 DK = diag::err_anonymous_record_with_static;
919 Diag((*Mem)->getLocation(), DK)
920 << (int)Record->isUnion();
921 Invalid = true;
922 }
923 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000924 } else {
925 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000926 if (Record->isUnion() && !Owner->isRecord()) {
927 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
928 << (int)getLangOptions().CPlusPlus;
929 Invalid = true;
930 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000931 }
932
933 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000934 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
935 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000936 Invalid = true;
937 }
938
939 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000940 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +0000941 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
942 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
943 /*IdentifierInfo=*/0,
944 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000945 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000946 Anon->setAccess(AS_public);
947 if (getLangOptions().CPlusPlus)
948 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000949 } else {
950 VarDecl::StorageClass SC;
951 switch (DS.getStorageClassSpec()) {
952 default: assert(0 && "Unknown storage class!");
953 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
954 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
955 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
956 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
957 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
958 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
959 case DeclSpec::SCS_mutable:
960 // mutable can only appear on non-static class members, so it's always
961 // an error here
962 Diag(Record->getLocation(), diag::err_mutable_nonmember);
963 Invalid = true;
964 SC = VarDecl::None;
965 break;
966 }
967
968 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
969 /*IdentifierInfo=*/0,
970 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000971 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +0000972 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000973 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000974
975 // Add the anonymous struct/union object to the current
976 // context. We'll be referencing this object when we refer to one of
977 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000978 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000979
980 // Inject the members of the anonymous struct/union into the owning
981 // context and into the identifier resolver chain for name lookup
982 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000983 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
984 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000985
986 // Mark this as an anonymous struct/union type. Note that we do not
987 // do this until after we have already checked and injected the
988 // members of this anonymous struct/union type, because otherwise
989 // the members could be injected twice: once by DeclContext when it
990 // builds its lookup table, and once by
991 // InjectAnonymousStructOrUnionMembers.
992 Record->setAnonymousStructOrUnion(true);
993
994 if (Invalid)
995 Anon->setInvalidDecl();
996
997 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000998}
999
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001000bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1001 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001002 // Get the type before calling CheckSingleAssignmentConstraints(), since
1003 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +00001004 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +00001005
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001006 if (getLangOptions().CPlusPlus) {
1007 // FIXME: I dislike this error message. A lot.
1008 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1009 return Diag(Init->getSourceRange().getBegin(),
1010 diag::err_typecheck_convert_incompatible)
1011 << DeclType << Init->getType() << "initializing"
1012 << Init->getSourceRange();
1013
1014 return false;
1015 }
Douglas Gregor6fd35572008-12-19 17:40:08 +00001016
Chris Lattner005ed752008-01-04 18:04:52 +00001017 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1018 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1019 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001020}
1021
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001022bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001023 const ArrayType *AT = Context.getAsArrayType(DeclT);
1024
1025 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001026 // C99 6.7.8p14. We have an array of character type with unknown size
1027 // being initialized to a string literal.
1028 llvm::APSInt ConstVal(32);
1029 ConstVal = strLiteral->getByteLength() + 1;
1030 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001031 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001032 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001033 } else {
1034 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001035 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001036 // FIXME: Avoid truncation for 64-bit length strings.
1037 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001038 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001039 diag::warn_initializer_string_for_char_array_too_long)
1040 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001041 }
1042 // Set type from "char *" to "constant array of char".
1043 strLiteral->setType(DeclT);
1044 // For now, we always return false (meaning success).
1045 return false;
1046}
1047
1048StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001049 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001050 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +00001051 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +00001052 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001053 return 0;
1054}
1055
Douglas Gregor6428e762008-11-05 15:29:30 +00001056bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1057 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001058 DeclarationName InitEntity,
1059 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001060 if (DeclType->isDependentType() || Init->isTypeDependent())
1061 return false;
1062
Douglas Gregor81c29152008-10-29 00:13:59 +00001063 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001064 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001065 // (8.3.2), shall be initialized by an object, or function, of
1066 // type T or by an object that can be converted into a T.
1067 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001068 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001069
Steve Naroff8e9337f2008-01-21 23:53:58 +00001070 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1071 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001072 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001073 return Diag(InitLoc, diag::err_variable_object_no_init)
1074 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001075
Steve Naroffcb69fb72007-12-10 22:44:33 +00001076 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1077 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001078 // FIXME: Handle wide strings
1079 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1080 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001081
Douglas Gregor6428e762008-11-05 15:29:30 +00001082 // C++ [dcl.init]p14:
1083 // -- If the destination type is a (possibly cv-qualified) class
1084 // type:
1085 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1086 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1087 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1088
1089 // -- If the initialization is direct-initialization, or if it is
1090 // copy-initialization where the cv-unqualified version of the
1091 // source type is the same class as, or a derived class of, the
1092 // class of the destination, constructors are considered.
1093 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1094 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1095 CXXConstructorDecl *Constructor
1096 = PerformInitializationByConstructor(DeclType, &Init, 1,
1097 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001098 InitEntity,
1099 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001100 return Constructor == 0;
1101 }
1102
1103 // -- Otherwise (i.e., for the remaining copy-initialization
1104 // cases), user-defined conversion sequences that can
1105 // convert from the source type to the destination type or
1106 // (when a conversion function is used) to a derived class
1107 // thereof are enumerated as described in 13.3.1.4, and the
1108 // best one is chosen through overload resolution
1109 // (13.3). If the conversion cannot be done or is
1110 // ambiguous, the initialization is ill-formed. The
1111 // function selected is called with the initializer
1112 // expression as its argument; if the function is a
1113 // constructor, the call initializes a temporary of the
1114 // destination type.
1115 // FIXME: We're pretending to do copy elision here; return to
1116 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001117 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001118 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001119
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001120 if (InitEntity)
1121 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1122 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1123 << Init->getType() << Init->getSourceRange();
1124 else
1125 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1126 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1127 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001128 }
1129
Steve Naroffb2f72412008-09-29 20:07:05 +00001130 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001131 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001132 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1133 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001134
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001135 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor15e04622008-11-05 16:20:31 +00001136 } else if (getLangOptions().CPlusPlus) {
1137 // C++ [dcl.init]p14:
1138 // [...] If the class is an aggregate (8.5.1), and the initializer
1139 // is a brace-enclosed list, see 8.5.1.
1140 //
1141 // Note: 8.5.1 is handled below; here, we diagnose the case where
1142 // we have an initializer list and a destination type that is not
1143 // an aggregate.
1144 // FIXME: In C++0x, this is yet another form of initialization.
1145 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1146 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1147 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001148 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001149 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001150 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001151 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001152
Steve Naroffc4d4a482008-05-01 22:18:59 +00001153 InitListChecker CheckInitList(this, InitList, DeclType);
Douglas Gregorf603b472009-01-28 21:54:33 +00001154 if (!CheckInitList.HadError())
1155 Init = CheckInitList.getFullyStructuredList();
1156
Steve Naroffc4d4a482008-05-01 22:18:59 +00001157 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +00001158}
1159
Douglas Gregor6704b312008-11-17 22:58:34 +00001160/// GetNameForDeclarator - Determine the full declaration name for the
1161/// given Declarator.
1162DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1163 switch (D.getKind()) {
1164 case Declarator::DK_Abstract:
1165 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1166 return DeclarationName();
1167
1168 case Declarator::DK_Normal:
1169 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1170 return DeclarationName(D.getIdentifier());
1171
1172 case Declarator::DK_Constructor: {
1173 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1174 Ty = Context.getCanonicalType(Ty);
1175 return Context.DeclarationNames.getCXXConstructorName(Ty);
1176 }
1177
1178 case Declarator::DK_Destructor: {
1179 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1180 Ty = Context.getCanonicalType(Ty);
1181 return Context.DeclarationNames.getCXXDestructorName(Ty);
1182 }
1183
1184 case Declarator::DK_Conversion: {
1185 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1186 Ty = Context.getCanonicalType(Ty);
1187 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1188 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001189
1190 case Declarator::DK_Operator:
1191 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1192 return Context.DeclarationNames.getCXXOperatorName(
1193 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001194 }
1195
1196 assert(false && "Unknown name kind");
1197 return DeclarationName();
1198}
1199
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001200/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1201/// functions Declaration and Definition are "nearly" matching. This
1202/// heuristic is used to improve diagnostics in the case where an
1203/// out-of-line member function definition doesn't match any
1204/// declaration within the class.
1205static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1206 FunctionDecl *Declaration,
1207 FunctionDecl *Definition) {
1208 if (Declaration->param_size() != Definition->param_size())
1209 return false;
1210 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1211 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1212 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1213
1214 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1215 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1216 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1217 return false;
1218 }
1219
1220 return true;
1221}
1222
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001223Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001224Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1225 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001226 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001227 DeclarationName Name = GetNameForDeclarator(D);
1228
Chris Lattner4b009652007-07-25 00:24:17 +00001229 // All of these full declarators require an identifier. If it doesn't have
1230 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001231 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001232 if (!D.getInvalidType()) // Reject this if we think it is valid.
1233 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001234 diag::err_declarator_need_ident)
1235 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001236 return 0;
1237 }
1238
Chris Lattnera7549902007-08-26 06:24:45 +00001239 // The scope passed in may not be a decl scope. Zip up the scope tree until
1240 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001241 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1242 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001243 S = S->getParent();
1244
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001245 DeclContext *DC;
1246 Decl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001247 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001248 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001249
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001250 // See if this is a redefinition of a variable in the same scope.
1251 if (!D.getCXXScopeSpec().isSet()) {
1252 DC = CurContext;
Steve Naroffc349ee22009-01-29 00:07:50 +00001253 PrevDecl = LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001254 } else { // Something like "int foo::x;"
1255 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Steve Naroffc349ee22009-01-29 00:07:50 +00001256 PrevDecl = DC ? LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC)
1257 : LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001258
1259 // C++ 7.3.1.2p2:
1260 // Members (including explicit specializations of templates) of a named
1261 // namespace can also be defined outside that namespace by explicit
1262 // qualification of the name being defined, provided that the entity being
1263 // defined was already declared in the namespace and the definition appears
1264 // after the point of declaration in a namespace that encloses the
1265 // declarations namespace.
1266 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001267 // Note that we only check the context at this point. We don't yet
1268 // have enough information to make sure that PrevDecl is actually
1269 // the declaration we want to match. For example, given:
1270 //
Douglas Gregor98341042008-12-12 08:25:50 +00001271 // class X {
1272 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001273 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001274 // };
1275 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001276 // void X::f(int) { } // ill-formed
1277 //
1278 // In this case, PrevDecl will point to the overload set
1279 // containing the two f's declared in X, but neither of them
1280 // matches.
1281 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001282 // The qualifying scope doesn't enclose the original declaration.
1283 // Emit diagnostic based on current scope.
1284 SourceLocation L = D.getIdentifierLoc();
1285 SourceRange R = D.getCXXScopeSpec().getRange();
1286 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001287 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001288 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001289 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001290 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001291 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001292 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001293 }
1294 }
1295
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001296 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001297 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001298 InvalidDecl = InvalidDecl
1299 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001300 // Just pretend that we didn't see the previous declaration.
1301 PrevDecl = 0;
1302 }
1303
Douglas Gregor1d661552008-04-13 21:07:44 +00001304 // In C++, the previous declaration we find might be a tag type
1305 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001306 // tag type. Note that this does does not apply if we're declaring a
1307 // typedef (C++ [dcl.typedef]p4).
1308 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1309 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001310 PrevDecl = 0;
1311
Chris Lattner82bb4792007-11-14 06:34:38 +00001312 QualType R = GetTypeForDeclarator(D, S);
1313 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1314
Chris Lattner4b009652007-07-25 00:24:17 +00001315 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001316 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1317 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001318 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001319 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1320 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001321 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001322 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1323 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001324 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001325
1326 if (New == 0)
1327 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001328
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001329 // Set the lexical context. If the declarator has a C++ scope specifier, the
1330 // lexical context will be different from the semantic context.
1331 New->setLexicalDeclContext(CurContext);
1332
Chris Lattner4b009652007-07-25 00:24:17 +00001333 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001334 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001335 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001336 // If any semantic error occurred, mark the decl as invalid.
1337 if (D.getInvalidType() || InvalidDecl)
1338 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001339
1340 return New;
1341}
1342
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001343NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001344Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001345 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001346 Decl* PrevDecl, bool& InvalidDecl) {
1347 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1348 if (D.getCXXScopeSpec().isSet()) {
1349 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1350 << D.getCXXScopeSpec().getRange();
1351 InvalidDecl = true;
1352 // Pretend we didn't see the scope specifier.
1353 DC = 0;
1354 }
1355
1356 // Check that there are no default arguments (C++ only).
1357 if (getLangOptions().CPlusPlus)
1358 CheckExtraCXXDefaultArguments(D);
1359
1360 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1361 if (!NewTD) return 0;
1362
1363 // Handle attributes prior to checking for duplicates in MergeVarDecl
1364 ProcessDeclAttributes(NewTD, D);
1365 // Merge the decl with the existing one if appropriate. If the decl is
1366 // in an outer scope, it isn't the same thing.
1367 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1368 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1369 if (NewTD == 0) return 0;
1370 }
1371
1372 if (S->getFnParent() == 0) {
1373 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1374 // then it shall have block scope.
1375 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1376 if (NewTD->getUnderlyingType()->isVariableArrayType())
1377 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1378 else
1379 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1380
1381 InvalidDecl = true;
1382 }
1383 }
1384 return NewTD;
1385}
1386
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001387NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001388Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001389 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001390 Decl* PrevDecl, bool& InvalidDecl) {
1391 DeclarationName Name = GetNameForDeclarator(D);
1392
1393 // Check that there are no default arguments (C++ only).
1394 if (getLangOptions().CPlusPlus)
1395 CheckExtraCXXDefaultArguments(D);
1396
1397 if (R.getTypePtr()->isObjCInterfaceType()) {
1398 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1399 << D.getIdentifier();
1400 InvalidDecl = true;
1401 }
1402
1403 VarDecl *NewVD;
1404 VarDecl::StorageClass SC;
1405 switch (D.getDeclSpec().getStorageClassSpec()) {
1406 default: assert(0 && "Unknown storage class!");
1407 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1408 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1409 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1410 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1411 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1412 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1413 case DeclSpec::SCS_mutable:
1414 // mutable can only appear on non-static class members, so it's always
1415 // an error here
1416 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1417 InvalidDecl = true;
1418 SC = VarDecl::None;
1419 break;
1420 }
1421
1422 IdentifierInfo *II = Name.getAsIdentifierInfo();
1423 if (!II) {
1424 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1425 << Name.getAsString();
1426 return 0;
1427 }
1428
1429 if (DC->isRecord()) {
1430 // This is a static data member for a C++ class.
1431 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1432 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001433 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001434 } else {
1435 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1436 if (S->getFnParent() == 0) {
1437 // C99 6.9p2: The storage-class specifiers auto and register shall not
1438 // appear in the declaration specifiers in an external declaration.
1439 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1440 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1441 InvalidDecl = true;
1442 }
1443 }
1444 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001445 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001446 // FIXME: Move to DeclGroup...
1447 D.getDeclSpec().getSourceRange().getBegin());
1448 NewVD->setThreadSpecified(ThreadSpecified);
1449 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001450 NewVD->setNextDeclarator(LastDeclarator);
1451
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001452 // Handle attributes prior to checking for duplicates in MergeVarDecl
1453 ProcessDeclAttributes(NewVD, D);
1454
1455 // Handle GNU asm-label extension (encoded as an attribute).
1456 if (Expr *E = (Expr*) D.getAsmLabel()) {
1457 // The parser guarantees this is a string.
1458 StringLiteral *SE = cast<StringLiteral>(E);
1459 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1460 SE->getByteLength())));
1461 }
1462
1463 // Emit an error if an address space was applied to decl with local storage.
1464 // This includes arrays of objects with address space qualifiers, but not
1465 // automatic variables that point to other address spaces.
1466 // ISO/IEC TR 18037 S5.1.2
1467 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1468 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1469 InvalidDecl = true;
1470 }
1471 // Merge the decl with the existing one if appropriate. If the decl is
1472 // in an outer scope, it isn't the same thing.
1473 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1474 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1475 // The user tried to define a non-static data member
1476 // out-of-line (C++ [dcl.meaning]p1).
1477 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1478 << D.getCXXScopeSpec().getRange();
1479 NewVD->Destroy(Context);
1480 return 0;
1481 }
1482
1483 NewVD = MergeVarDecl(NewVD, PrevDecl);
1484 if (NewVD == 0) return 0;
1485
1486 if (D.getCXXScopeSpec().isSet()) {
1487 // No previous declaration in the qualifying scope.
1488 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1489 << Name << D.getCXXScopeSpec().getRange();
1490 InvalidDecl = true;
1491 }
1492 }
1493 return NewVD;
1494}
1495
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001496NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001497Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001498 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001499 Decl* PrevDecl, bool IsFunctionDefinition,
1500 bool& InvalidDecl) {
1501 assert(R.getTypePtr()->isFunctionType());
1502
1503 DeclarationName Name = GetNameForDeclarator(D);
1504 FunctionDecl::StorageClass SC = FunctionDecl::None;
1505 switch (D.getDeclSpec().getStorageClassSpec()) {
1506 default: assert(0 && "Unknown storage class!");
1507 case DeclSpec::SCS_auto:
1508 case DeclSpec::SCS_register:
1509 case DeclSpec::SCS_mutable:
1510 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1511 InvalidDecl = true;
1512 break;
1513 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1514 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1515 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1516 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1517 }
1518
1519 bool isInline = D.getDeclSpec().isInlineSpecified();
1520 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1521 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1522
1523 FunctionDecl *NewFD;
1524 if (D.getKind() == Declarator::DK_Constructor) {
1525 // This is a C++ constructor declaration.
1526 assert(DC->isRecord() &&
1527 "Constructors can only be declared in a member context");
1528
1529 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1530
1531 // Create the new declaration
1532 NewFD = CXXConstructorDecl::Create(Context,
1533 cast<CXXRecordDecl>(DC),
1534 D.getIdentifierLoc(), Name, R,
1535 isExplicit, isInline,
1536 /*isImplicitlyDeclared=*/false);
1537
1538 if (InvalidDecl)
1539 NewFD->setInvalidDecl();
1540 } else if (D.getKind() == Declarator::DK_Destructor) {
1541 // This is a C++ destructor declaration.
1542 if (DC->isRecord()) {
1543 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1544
1545 NewFD = CXXDestructorDecl::Create(Context,
1546 cast<CXXRecordDecl>(DC),
1547 D.getIdentifierLoc(), Name, R,
1548 isInline,
1549 /*isImplicitlyDeclared=*/false);
1550
1551 if (InvalidDecl)
1552 NewFD->setInvalidDecl();
1553 } else {
1554 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1555
1556 // Create a FunctionDecl to satisfy the function definition parsing
1557 // code path.
1558 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001559 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001560 // FIXME: Move to DeclGroup...
1561 D.getDeclSpec().getSourceRange().getBegin());
1562 InvalidDecl = true;
1563 NewFD->setInvalidDecl();
1564 }
1565 } else if (D.getKind() == Declarator::DK_Conversion) {
1566 if (!DC->isRecord()) {
1567 Diag(D.getIdentifierLoc(),
1568 diag::err_conv_function_not_member);
1569 return 0;
1570 } else {
1571 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1572
1573 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1574 D.getIdentifierLoc(), Name, R,
1575 isInline, isExplicit);
1576
1577 if (InvalidDecl)
1578 NewFD->setInvalidDecl();
1579 }
1580 } else if (DC->isRecord()) {
1581 // This is a C++ method declaration.
1582 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1583 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001584 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001585 } else {
1586 NewFD = FunctionDecl::Create(Context, DC,
1587 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001588 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001589 // FIXME: Move to DeclGroup...
1590 D.getDeclSpec().getSourceRange().getBegin());
1591 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001592 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001593
1594 // Set the lexical context. If the declarator has a C++
1595 // scope specifier, the lexical context will be different
1596 // from the semantic context.
1597 NewFD->setLexicalDeclContext(CurContext);
1598
1599 // Handle GNU asm-label extension (encoded as an attribute).
1600 if (Expr *E = (Expr*) D.getAsmLabel()) {
1601 // The parser guarantees this is a string.
1602 StringLiteral *SE = cast<StringLiteral>(E);
1603 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1604 SE->getByteLength())));
1605 }
1606
1607 // Copy the parameter declarations from the declarator D to
1608 // the function declaration NewFD, if they are available.
1609 if (D.getNumTypeObjects() > 0) {
1610 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1611
1612 // Create Decl objects for each parameter, adding them to the
1613 // FunctionDecl.
1614 llvm::SmallVector<ParmVarDecl*, 16> Params;
1615
1616 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1617 // function that takes no arguments, not a function that takes a
1618 // single void argument.
1619 // We let through "const void" here because Sema::GetTypeForDeclarator
1620 // already checks for that case.
1621 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1622 FTI.ArgInfo[0].Param &&
1623 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1624 // empty arg list, don't push any params.
1625 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1626
1627 // In C++, the empty parameter-type-list must be spelled "void"; a
1628 // typedef of void is not permitted.
1629 if (getLangOptions().CPlusPlus &&
1630 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1631 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1632 }
1633 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1634 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1635 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1636 }
1637
1638 NewFD->setParams(Context, &Params[0], Params.size());
1639 } else if (R->getAsTypedefType()) {
1640 // When we're declaring a function with a typedef, as in the
1641 // following example, we'll need to synthesize (unnamed)
1642 // parameters for use in the declaration.
1643 //
1644 // @code
1645 // typedef void fn(int);
1646 // fn f;
1647 // @endcode
1648 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1649 if (!FT) {
1650 // This is a typedef of a function with no prototype, so we
1651 // don't need to do anything.
1652 } else if ((FT->getNumArgs() == 0) ||
1653 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1654 FT->getArgType(0)->isVoidType())) {
1655 // This is a zero-argument function. We don't need to do anything.
1656 } else {
1657 // Synthesize a parameter for each argument type.
1658 llvm::SmallVector<ParmVarDecl*, 16> Params;
1659 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1660 ArgType != FT->arg_type_end(); ++ArgType) {
1661 Params.push_back(ParmVarDecl::Create(Context, DC,
1662 SourceLocation(), 0,
1663 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001664 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001665 }
1666
1667 NewFD->setParams(Context, &Params[0], Params.size());
1668 }
1669 }
1670
1671 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1672 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1673 else if (isa<CXXDestructorDecl>(NewFD)) {
1674 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1675 Record->setUserDeclaredDestructor(true);
1676 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1677 // user-defined destructor.
1678 Record->setPOD(false);
1679 } else if (CXXConversionDecl *Conversion =
1680 dyn_cast<CXXConversionDecl>(NewFD))
1681 ActOnConversionDeclarator(Conversion);
1682
1683 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1684 if (NewFD->isOverloadedOperator() &&
1685 CheckOverloadedOperatorDeclaration(NewFD))
1686 NewFD->setInvalidDecl();
1687
1688 // Merge the decl with the existing one if appropriate. Since C functions
1689 // are in a flat namespace, make sure we consider decls in outer scopes.
1690 if (PrevDecl &&
1691 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1692 bool Redeclaration = false;
1693
1694 // If C++, determine whether NewFD is an overload of PrevDecl or
1695 // a declaration that requires merging. If it's an overload,
1696 // there's no more work to do here; we'll just add the new
1697 // function to the scope.
1698 OverloadedFunctionDecl::function_iterator MatchedDecl;
1699 if (!getLangOptions().CPlusPlus ||
1700 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1701 Decl *OldDecl = PrevDecl;
1702
1703 // If PrevDecl was an overloaded function, extract the
1704 // FunctionDecl that matched.
1705 if (isa<OverloadedFunctionDecl>(PrevDecl))
1706 OldDecl = *MatchedDecl;
1707
1708 // NewFD and PrevDecl represent declarations that need to be
1709 // merged.
1710 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1711
1712 if (NewFD == 0) return 0;
1713 if (Redeclaration) {
1714 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1715
1716 // An out-of-line member function declaration must also be a
1717 // definition (C++ [dcl.meaning]p1).
1718 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1719 !InvalidDecl) {
1720 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1721 << D.getCXXScopeSpec().getRange();
1722 NewFD->setInvalidDecl();
1723 }
1724 }
1725 }
1726
1727 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1728 // The user tried to provide an out-of-line definition for a
1729 // member function, but there was no such member function
1730 // declared (C++ [class.mfct]p2). For example:
1731 //
1732 // class X {
1733 // void f() const;
1734 // };
1735 //
1736 // void X::f() { } // ill-formed
1737 //
1738 // Complain about this problem, and attempt to suggest close
1739 // matches (e.g., those that differ only in cv-qualifiers and
1740 // whether the parameter types are references).
1741 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1742 << cast<CXXRecordDecl>(DC)->getDeclName()
1743 << D.getCXXScopeSpec().getRange();
1744 InvalidDecl = true;
1745
Steve Naroffc349ee22009-01-29 00:07:50 +00001746 PrevDecl = LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001747 if (!PrevDecl) {
1748 // Nothing to suggest.
1749 } else if (OverloadedFunctionDecl *Ovl
1750 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1751 for (OverloadedFunctionDecl::function_iterator
1752 Func = Ovl->function_begin(),
1753 FuncEnd = Ovl->function_end();
1754 Func != FuncEnd; ++Func) {
1755 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1756 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1757
1758 }
1759 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1760 // Suggest this no matter how mismatched it is; it's the only
1761 // thing we have.
1762 unsigned diag;
1763 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1764 diag = diag::note_member_def_close_match;
1765 else if (Method->getBody())
1766 diag = diag::note_previous_definition;
1767 else
1768 diag = diag::note_previous_declaration;
1769 Diag(Method->getLocation(), diag);
1770 }
1771
1772 PrevDecl = 0;
1773 }
1774 }
1775 // Handle attributes. We need to have merged decls when handling attributes
1776 // (for example to check for conflicts, etc).
1777 ProcessDeclAttributes(NewFD, D);
1778
1779 if (getLangOptions().CPlusPlus) {
1780 // In C++, check default arguments now that we have merged decls.
1781 CheckCXXDefaultArguments(NewFD);
1782
1783 // An out-of-line member function declaration must also be a
1784 // definition (C++ [dcl.meaning]p1).
1785 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1786 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1787 << D.getCXXScopeSpec().getRange();
1788 InvalidDecl = true;
1789 }
1790 }
1791 return NewFD;
1792}
1793
Steve Narofffc08f5e2008-10-27 11:34:16 +00001794void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001795 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1796 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001797}
1798
Eli Friedman02c22ce2008-05-20 13:48:25 +00001799bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1800 switch (Init->getStmtClass()) {
1801 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001802 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001803 return true;
1804 case Expr::ParenExprClass: {
1805 const ParenExpr* PE = cast<ParenExpr>(Init);
1806 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1807 }
1808 case Expr::CompoundLiteralExprClass:
1809 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001810 case Expr::DeclRefExprClass:
1811 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001812 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001813 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1814 if (VD->hasGlobalStorage())
1815 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001816 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001817 return true;
1818 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001819 if (isa<FunctionDecl>(D))
1820 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001821 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001822 return true;
1823 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001824 case Expr::MemberExprClass: {
1825 const MemberExpr *M = cast<MemberExpr>(Init);
1826 if (M->isArrow())
1827 return CheckAddressConstantExpression(M->getBase());
1828 return CheckAddressConstantExpressionLValue(M->getBase());
1829 }
1830 case Expr::ArraySubscriptExprClass: {
1831 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1832 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1833 return CheckAddressConstantExpression(ASE->getBase()) ||
1834 CheckArithmeticConstantExpression(ASE->getIdx());
1835 }
1836 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001837 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001838 return false;
1839 case Expr::UnaryOperatorClass: {
1840 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1841
1842 // C99 6.6p9
1843 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001844 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001845
Steve Narofffc08f5e2008-10-27 11:34:16 +00001846 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001847 return true;
1848 }
1849 }
1850}
1851
1852bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1853 switch (Init->getStmtClass()) {
1854 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001855 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001856 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001857 case Expr::ParenExprClass:
1858 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001859 case Expr::StringLiteralClass:
1860 case Expr::ObjCStringLiteralClass:
1861 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001862 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001863 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001864 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1865 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1866 Builtin::BI__builtin___CFStringMakeConstantString)
1867 return false;
1868
Steve Narofffc08f5e2008-10-27 11:34:16 +00001869 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001870 return true;
1871
Eli Friedman02c22ce2008-05-20 13:48:25 +00001872 case Expr::UnaryOperatorClass: {
1873 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1874
1875 // C99 6.6p9
1876 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1877 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1878
1879 if (Exp->getOpcode() == UnaryOperator::Extension)
1880 return CheckAddressConstantExpression(Exp->getSubExpr());
1881
Steve Narofffc08f5e2008-10-27 11:34:16 +00001882 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001883 return true;
1884 }
1885 case Expr::BinaryOperatorClass: {
1886 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1887 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1888
1889 Expr *PExp = Exp->getLHS();
1890 Expr *IExp = Exp->getRHS();
1891 if (IExp->getType()->isPointerType())
1892 std::swap(PExp, IExp);
1893
1894 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1895 return CheckAddressConstantExpression(PExp) ||
1896 CheckArithmeticConstantExpression(IExp);
1897 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001898 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001899 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001900 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001901 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1902 // Check for implicit promotion
1903 if (SubExpr->getType()->isFunctionType() ||
1904 SubExpr->getType()->isArrayType())
1905 return CheckAddressConstantExpressionLValue(SubExpr);
1906 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001907
1908 // Check for pointer->pointer cast
1909 if (SubExpr->getType()->isPointerType())
1910 return CheckAddressConstantExpression(SubExpr);
1911
Eli Friedman1fad3c62008-08-25 20:46:57 +00001912 if (SubExpr->getType()->isIntegralType()) {
1913 // Check for the special-case of a pointer->int->pointer cast;
1914 // this isn't standard, but some code requires it. See
1915 // PR2720 for an example.
1916 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1917 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1918 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1919 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1920 if (IntWidth >= PointerWidth) {
1921 return CheckAddressConstantExpression(SubCast->getSubExpr());
1922 }
1923 }
1924 }
1925 }
1926 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001927 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001928 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001929
Steve Narofffc08f5e2008-10-27 11:34:16 +00001930 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001931 return true;
1932 }
1933 case Expr::ConditionalOperatorClass: {
1934 // FIXME: Should we pedwarn here?
1935 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1936 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001937 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001938 return true;
1939 }
1940 if (CheckArithmeticConstantExpression(Exp->getCond()))
1941 return true;
1942 if (Exp->getLHS() &&
1943 CheckAddressConstantExpression(Exp->getLHS()))
1944 return true;
1945 return CheckAddressConstantExpression(Exp->getRHS());
1946 }
1947 case Expr::AddrLabelExprClass:
1948 return false;
1949 }
1950}
1951
Eli Friedman998dffb2008-06-09 05:05:07 +00001952static const Expr* FindExpressionBaseAddress(const Expr* E);
1953
1954static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1955 switch (E->getStmtClass()) {
1956 default:
1957 return E;
1958 case Expr::ParenExprClass: {
1959 const ParenExpr* PE = cast<ParenExpr>(E);
1960 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1961 }
1962 case Expr::MemberExprClass: {
1963 const MemberExpr *M = cast<MemberExpr>(E);
1964 if (M->isArrow())
1965 return FindExpressionBaseAddress(M->getBase());
1966 return FindExpressionBaseAddressLValue(M->getBase());
1967 }
1968 case Expr::ArraySubscriptExprClass: {
1969 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1970 return FindExpressionBaseAddress(ASE->getBase());
1971 }
1972 case Expr::UnaryOperatorClass: {
1973 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1974
1975 if (Exp->getOpcode() == UnaryOperator::Deref)
1976 return FindExpressionBaseAddress(Exp->getSubExpr());
1977
1978 return E;
1979 }
1980 }
1981}
1982
1983static const Expr* FindExpressionBaseAddress(const Expr* E) {
1984 switch (E->getStmtClass()) {
1985 default:
1986 return E;
1987 case Expr::ParenExprClass: {
1988 const ParenExpr* PE = cast<ParenExpr>(E);
1989 return FindExpressionBaseAddress(PE->getSubExpr());
1990 }
1991 case Expr::UnaryOperatorClass: {
1992 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1993
1994 // C99 6.6p9
1995 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1996 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1997
1998 if (Exp->getOpcode() == UnaryOperator::Extension)
1999 return FindExpressionBaseAddress(Exp->getSubExpr());
2000
2001 return E;
2002 }
2003 case Expr::BinaryOperatorClass: {
2004 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2005
2006 Expr *PExp = Exp->getLHS();
2007 Expr *IExp = Exp->getRHS();
2008 if (IExp->getType()->isPointerType())
2009 std::swap(PExp, IExp);
2010
2011 return FindExpressionBaseAddress(PExp);
2012 }
2013 case Expr::ImplicitCastExprClass: {
2014 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2015
2016 // Check for implicit promotion
2017 if (SubExpr->getType()->isFunctionType() ||
2018 SubExpr->getType()->isArrayType())
2019 return FindExpressionBaseAddressLValue(SubExpr);
2020
2021 // Check for pointer->pointer cast
2022 if (SubExpr->getType()->isPointerType())
2023 return FindExpressionBaseAddress(SubExpr);
2024
2025 // We assume that we have an arithmetic expression here;
2026 // if we don't, we'll figure it out later
2027 return 0;
2028 }
Douglas Gregor035d0882008-10-28 15:36:24 +00002029 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00002030 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2031
2032 // Check for pointer->pointer cast
2033 if (SubExpr->getType()->isPointerType())
2034 return FindExpressionBaseAddress(SubExpr);
2035
2036 // We assume that we have an arithmetic expression here;
2037 // if we don't, we'll figure it out later
2038 return 0;
2039 }
2040 }
2041}
2042
Anders Carlssone8bd9f22008-11-22 21:04:56 +00002043bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002044 switch (Init->getStmtClass()) {
2045 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002046 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002047 return true;
2048 case Expr::ParenExprClass: {
2049 const ParenExpr* PE = cast<ParenExpr>(Init);
2050 return CheckArithmeticConstantExpression(PE->getSubExpr());
2051 }
2052 case Expr::FloatingLiteralClass:
2053 case Expr::IntegerLiteralClass:
2054 case Expr::CharacterLiteralClass:
2055 case Expr::ImaginaryLiteralClass:
2056 case Expr::TypesCompatibleExprClass:
2057 case Expr::CXXBoolLiteralExprClass:
2058 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002059 case Expr::CallExprClass:
2060 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002061 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002062
2063 // Allow any constant foldable calls to builtins.
2064 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002065 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002066
Steve Narofffc08f5e2008-10-27 11:34:16 +00002067 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002068 return true;
2069 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002070 case Expr::DeclRefExprClass:
2071 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002072 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2073 if (isa<EnumConstantDecl>(D))
2074 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002075 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002076 return true;
2077 }
2078 case Expr::CompoundLiteralExprClass:
2079 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2080 // but vectors are allowed to be magic.
2081 if (Init->getType()->isVectorType())
2082 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002083 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002084 return true;
2085 case Expr::UnaryOperatorClass: {
2086 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2087
2088 switch (Exp->getOpcode()) {
2089 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2090 // See C99 6.6p3.
2091 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002092 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002093 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002094 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002095 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2096 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002097 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002098 return true;
2099 case UnaryOperator::Extension:
2100 case UnaryOperator::LNot:
2101 case UnaryOperator::Plus:
2102 case UnaryOperator::Minus:
2103 case UnaryOperator::Not:
2104 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2105 }
2106 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002107 case Expr::SizeOfAlignOfExprClass: {
2108 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002109 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002110 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002111 return false;
2112 // alignof always evaluates to a constant.
2113 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002114 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002115 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002116 return true;
2117 }
2118 return false;
2119 }
2120 case Expr::BinaryOperatorClass: {
2121 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2122
2123 if (Exp->getLHS()->getType()->isArithmeticType() &&
2124 Exp->getRHS()->getType()->isArithmeticType()) {
2125 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2126 CheckArithmeticConstantExpression(Exp->getRHS());
2127 }
2128
Eli Friedman998dffb2008-06-09 05:05:07 +00002129 if (Exp->getLHS()->getType()->isPointerType() &&
2130 Exp->getRHS()->getType()->isPointerType()) {
2131 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2132 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2133
2134 // Only allow a null (constant integer) base; we could
2135 // allow some additional cases if necessary, but this
2136 // is sufficient to cover offsetof-like constructs.
2137 if (!LHSBase && !RHSBase) {
2138 return CheckAddressConstantExpression(Exp->getLHS()) ||
2139 CheckAddressConstantExpression(Exp->getRHS());
2140 }
2141 }
2142
Steve Narofffc08f5e2008-10-27 11:34:16 +00002143 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002144 return true;
2145 }
2146 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002147 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002148 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002149 if (SubExpr->getType()->isArithmeticType())
2150 return CheckArithmeticConstantExpression(SubExpr);
2151
Eli Friedman266df142008-09-02 09:37:00 +00002152 if (SubExpr->getType()->isPointerType()) {
2153 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2154 // If the pointer has a null base, this is an offsetof-like construct
2155 if (!Base)
2156 return CheckAddressConstantExpression(SubExpr);
2157 }
2158
Steve Narofffc08f5e2008-10-27 11:34:16 +00002159 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002160 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002161 }
2162 case Expr::ConditionalOperatorClass: {
2163 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002164
2165 // If GNU extensions are disabled, we require all operands to be arithmetic
2166 // constant expressions.
2167 if (getLangOptions().NoExtensions) {
2168 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2169 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2170 CheckArithmeticConstantExpression(Exp->getRHS());
2171 }
2172
2173 // Otherwise, we have to emulate some of the behavior of fold here.
2174 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2175 // because it can constant fold things away. To retain compatibility with
2176 // GCC code, we see if we can fold the condition to a constant (which we
2177 // should always be able to do in theory). If so, we only require the
2178 // specified arm of the conditional to be a constant. This is a horrible
2179 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002180 Expr::EvalResult EvalResult;
2181 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2182 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002183 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002184 // won't be able to either. Use it to emit the diagnostic though.
2185 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002186 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002187 return Res;
2188 }
2189
2190 // Verify that the side following the condition is also a constant.
2191 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002192 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002193 std::swap(TrueSide, FalseSide);
2194
2195 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002196 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002197
2198 // Okay, the evaluated side evaluates to a constant, so we accept this.
2199 // Check to see if the other side is obviously not a constant. If so,
2200 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002201 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002202 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002203 diag::ext_typecheck_expression_not_constant_but_accepted)
2204 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002205 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002206 }
2207 }
2208}
2209
2210bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002211 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2212 Init = DIE->getInit();
2213
Nuno Lopese7280452008-07-07 16:46:50 +00002214 Init = Init->IgnoreParens();
2215
Nate Begemand6d2f772009-01-18 03:20:47 +00002216 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002217 return false;
2218
Eli Friedman02c22ce2008-05-20 13:48:25 +00002219 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2220 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2221 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2222
Nuno Lopese7280452008-07-07 16:46:50 +00002223 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2224 return CheckForConstantInitializer(e->getInitializer(), DclT);
2225
Eli Friedman02c22ce2008-05-20 13:48:25 +00002226 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2227 unsigned numInits = Exp->getNumInits();
2228 for (unsigned i = 0; i < numInits; i++) {
2229 // FIXME: Need to get the type of the declaration for C++,
2230 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002231
2232 // Implicitly-generated value initializations are okay.
2233 if (isa<CXXZeroInitValueExpr>(Exp->getInit(i)) &&
2234 cast<CXXZeroInitValueExpr>(Exp->getInit(i))->isImplicit())
2235 continue;
2236
Eli Friedman02c22ce2008-05-20 13:48:25 +00002237 if (CheckForConstantInitializer(Exp->getInit(i),
2238 Exp->getInit(i)->getType()))
2239 return true;
2240 }
2241 return false;
2242 }
2243
Anders Carlssonf6791c62008-12-05 05:09:56 +00002244 // FIXME: We can probably remove some of this code below, now that
2245 // Expr::Evaluate is doing the heavy lifting for scalars.
2246
Eli Friedman02c22ce2008-05-20 13:48:25 +00002247 if (Init->isNullPointerConstant(Context))
2248 return false;
2249 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002250 QualType InitTy = Context.getCanonicalType(Init->getType())
2251 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002252 if (InitTy == Context.BoolTy) {
2253 // Special handling for pointers implicitly cast to bool;
2254 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2255 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2256 Expr* SubE = ICE->getSubExpr();
2257 if (SubE->getType()->isPointerType() ||
2258 SubE->getType()->isArrayType() ||
2259 SubE->getType()->isFunctionType()) {
2260 return CheckAddressConstantExpression(Init);
2261 }
2262 }
2263 } else if (InitTy->isIntegralType()) {
2264 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002265 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002266 SubE = CE->getSubExpr();
2267 // Special check for pointer cast to int; we allow as an extension
2268 // an address constant cast to an integer if the integer
2269 // is of an appropriate width (this sort of code is apparently used
2270 // in some places).
2271 // FIXME: Add pedwarn?
2272 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2273 if (SubE && (SubE->getType()->isPointerType() ||
2274 SubE->getType()->isArrayType() ||
2275 SubE->getType()->isFunctionType())) {
2276 unsigned IntWidth = Context.getTypeSize(Init->getType());
2277 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2278 if (IntWidth >= PointerWidth)
2279 return CheckAddressConstantExpression(Init);
2280 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002281 }
2282
2283 return CheckArithmeticConstantExpression(Init);
2284 }
2285
2286 if (Init->getType()->isPointerType())
2287 return CheckAddressConstantExpression(Init);
2288
Eli Friedman25086f02008-05-30 18:14:48 +00002289 // An array type at the top level that isn't an init-list must
2290 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002291 if (Init->getType()->isArrayType())
2292 return false;
2293
Nuno Lopes1dc26762008-09-01 18:42:41 +00002294 if (Init->getType()->isFunctionType())
2295 return false;
2296
Steve Naroffdff3fb22008-10-02 17:12:56 +00002297 // Allow block exprs at top level.
2298 if (Init->getType()->isBlockPointerType())
2299 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002300
2301 // GCC cast to union extension
2302 // note: the validity of the cast expr is checked by CheckCastTypes()
2303 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2304 QualType T = C->getType();
2305 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2306 }
2307
Steve Narofffc08f5e2008-10-27 11:34:16 +00002308 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002309 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002310}
2311
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002312void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002313 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2314}
2315
2316/// AddInitializerToDecl - Adds the initializer Init to the
2317/// declaration dcl. If DirectInit is true, this is C++ direct
2318/// initialization rather than copy initialization.
2319void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002320 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002321 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002322 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002323
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002324 // If there is no declaration, there was an error parsing it. Just ignore
2325 // the initializer.
2326 if (RealDecl == 0) {
2327 delete Init;
2328 return;
2329 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002330
Steve Naroff420d0f52007-09-12 20:13:48 +00002331 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2332 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002333 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002334 RealDecl->setInvalidDecl();
2335 return;
2336 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002337 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002338 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002339 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002340 if (VDecl->isBlockVarDecl()) {
2341 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002342 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002343 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002344 VDecl->setInvalidDecl();
2345 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002346 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002347 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002348 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002349
2350 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2351 if (!getLangOptions().CPlusPlus) {
2352 if (SC == VarDecl::Static) // C99 6.7.8p4.
2353 CheckForConstantInitializer(Init, DclT);
2354 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002355 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002356 } else if (VDecl->isFileVarDecl()) {
2357 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002358 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002359 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002360 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002361 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002362 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002363
Anders Carlssonea7140a2008-08-22 05:00:02 +00002364 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2365 if (!getLangOptions().CPlusPlus) {
2366 // C99 6.7.8p4. All file scoped initializers need to be constant.
2367 CheckForConstantInitializer(Init, DclT);
2368 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002369 }
2370 // If the type changed, it means we had an incomplete type that was
2371 // completed by the initializer. For example:
2372 // int ary[] = { 1, 3, 5 };
2373 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002374 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002375 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002376 Init->setType(DclT);
2377 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002378
2379 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002380 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002381 return;
2382}
2383
Douglas Gregor81c29152008-10-29 00:13:59 +00002384void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2385 Decl *RealDecl = static_cast<Decl *>(dcl);
2386
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002387 // If there is no declaration, there was an error parsing it. Just ignore it.
2388 if (RealDecl == 0)
2389 return;
2390
Douglas Gregor81c29152008-10-29 00:13:59 +00002391 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2392 QualType Type = Var->getType();
2393 // C++ [dcl.init.ref]p3:
2394 // The initializer can be omitted for a reference only in a
2395 // parameter declaration (8.3.5), in the declaration of a
2396 // function return type, in the declaration of a class member
2397 // within its class declaration (9.2), and where the extern
2398 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002399 if (Type->isReferenceType() &&
2400 Var->getStorageClass() != VarDecl::Extern &&
2401 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002402 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002403 << Var->getDeclName()
2404 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002405 Var->setInvalidDecl();
2406 return;
2407 }
2408
2409 // C++ [dcl.init]p9:
2410 //
2411 // If no initializer is specified for an object, and the object
2412 // is of (possibly cv-qualified) non-POD class type (or array
2413 // thereof), the object shall be default-initialized; if the
2414 // object is of const-qualified type, the underlying class type
2415 // shall have a user-declared default constructor.
2416 if (getLangOptions().CPlusPlus) {
2417 QualType InitType = Type;
2418 if (const ArrayType *Array = Context.getAsArrayType(Type))
2419 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002420 if (Var->getStorageClass() != VarDecl::Extern &&
2421 Var->getStorageClass() != VarDecl::PrivateExtern &&
2422 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002423 const CXXConstructorDecl *Constructor
2424 = PerformInitializationByConstructor(InitType, 0, 0,
2425 Var->getLocation(),
2426 SourceRange(Var->getLocation(),
2427 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002428 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002429 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002430 if (!Constructor)
2431 Var->setInvalidDecl();
2432 }
2433 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002434
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002435#if 0
2436 // FIXME: Temporarily disabled because we are not properly parsing
2437 // linkage specifications on declarations, e.g.,
2438 //
2439 // extern "C" const CGPoint CGPointerZero;
2440 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002441 // C++ [dcl.init]p9:
2442 //
2443 // If no initializer is specified for an object, and the
2444 // object is of (possibly cv-qualified) non-POD class type (or
2445 // array thereof), the object shall be default-initialized; if
2446 // the object is of const-qualified type, the underlying class
2447 // type shall have a user-declared default
2448 // constructor. Otherwise, if no initializer is specified for
2449 // an object, the object and its subobjects, if any, have an
2450 // indeterminate initial value; if the object or any of its
2451 // subobjects are of const-qualified type, the program is
2452 // ill-formed.
2453 //
2454 // This isn't technically an error in C, so we don't diagnose it.
2455 //
2456 // FIXME: Actually perform the POD/user-defined default
2457 // constructor check.
2458 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002459 Context.getCanonicalType(Type).isConstQualified() &&
2460 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002461 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2462 << Var->getName()
2463 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002464#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002465 }
2466}
2467
Chris Lattner4b009652007-07-25 00:24:17 +00002468/// The declarators are chained together backwards, reverse the list.
2469Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2470 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002471 Decl *GroupDecl = static_cast<Decl*>(group);
2472 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002473 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002474
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002475 Decl *Group = dyn_cast<Decl>(GroupDecl);
2476 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002477 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002478 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002479 else { // reverse the list.
2480 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002481 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002482 Group->setNextDeclarator(NewGroup);
2483 NewGroup = Group;
2484 Group = Next;
2485 }
2486 }
2487 // Perform semantic analysis that depends on having fully processed both
2488 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002489 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002490 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2491 if (!IDecl)
2492 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002493 QualType T = IDecl->getType();
2494
Anders Carlsson68adbd12008-12-07 00:20:55 +00002495 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002496 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002497
2498 // FIXME: This won't give the correct result for
2499 // int a[10][n];
2500 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002501 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002502 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2503 SizeRange;
2504
Eli Friedman8ff07782008-02-15 18:16:39 +00002505 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002506 } else {
2507 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2508 // static storage duration, it shall not have a variable length array.
2509 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002510 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2511 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002512 IDecl->setInvalidDecl();
2513 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002514 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2515 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002516 IDecl->setInvalidDecl();
2517 }
2518 }
2519 } else if (T->isVariablyModifiedType()) {
2520 if (IDecl->isFileVarDecl()) {
2521 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2522 IDecl->setInvalidDecl();
2523 } else {
2524 if (IDecl->getStorageClass() == VarDecl::Extern) {
2525 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2526 IDecl->setInvalidDecl();
2527 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002528 }
2529 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002530
Steve Naroff6a0e2092007-09-12 14:07:44 +00002531 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2532 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002533 if (IDecl->isBlockVarDecl() &&
2534 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002535 if (!IDecl->isInvalidDecl() &&
2536 DiagnoseIncompleteType(IDecl->getLocation(), T,
2537 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002538 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002539 }
2540 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2541 // object that has file scope without an initializer, and without a
2542 // storage-class specifier or with the storage-class specifier "static",
2543 // constitutes a tentative definition. Note: A tentative definition with
2544 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002545 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002546 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002547 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2548 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002549 } else if (!IDecl->isInvalidDecl() &&
2550 DiagnoseIncompleteType(IDecl->getLocation(), T,
2551 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002552 // C99 6.9.2p3: If the declaration of an identifier for an object is
2553 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2554 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002555 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002556 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002557 if (IDecl->isFileVarDecl())
2558 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002559 }
2560 return NewGroup;
2561}
Steve Naroff91b03f72007-08-28 03:03:08 +00002562
Chris Lattner3e254fb2008-04-08 04:40:51 +00002563/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2564/// to introduce parameters into function prototype scope.
2565Sema::DeclTy *
2566Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002567 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002568
Chris Lattner3e254fb2008-04-08 04:40:51 +00002569 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002570 VarDecl::StorageClass StorageClass = VarDecl::None;
2571 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2572 StorageClass = VarDecl::Register;
2573 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002574 Diag(DS.getStorageClassSpecLoc(),
2575 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002576 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002577 }
2578 if (DS.isThreadSpecified()) {
2579 Diag(DS.getThreadSpecLoc(),
2580 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002581 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002582 }
2583
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002584 // Check that there are no default arguments inside the type of this
2585 // parameter (C++ only).
2586 if (getLangOptions().CPlusPlus)
2587 CheckExtraCXXDefaultArguments(D);
2588
Chris Lattner3e254fb2008-04-08 04:40:51 +00002589 // In this context, we *do not* check D.getInvalidType(). If the declarator
2590 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2591 // though it will not reflect the user specified type.
2592 QualType parmDeclType = GetTypeForDeclarator(D, S);
2593
2594 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2595
Chris Lattner4b009652007-07-25 00:24:17 +00002596 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2597 // Can this happen for params? We already checked that they don't conflict
2598 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002599 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002600 if (II) {
Steve Naroffc349ee22009-01-29 00:07:50 +00002601 if (Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Ordinary, S)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002602 if (PrevDecl->isTemplateParameter()) {
2603 // Maybe we will complain about the shadowed template parameter.
2604 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2605 // Just pretend that we didn't see the previous declaration.
2606 PrevDecl = 0;
2607 } else if (S->isDeclScope(PrevDecl)) {
2608 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002609
Chris Lattner310dea32009-01-21 02:38:50 +00002610 // Recover by removing the name
2611 II = 0;
2612 D.SetIdentifier(0, D.getIdentifierLoc());
2613 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002614 }
Chris Lattner4b009652007-07-25 00:24:17 +00002615 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002616
2617 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2618 // Doing the promotion here has a win and a loss. The win is the type for
2619 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2620 // code generator). The loss is the orginal type isn't preserved. For example:
2621 //
2622 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2623 // int blockvardecl[5];
2624 // sizeof(parmvardecl); // size == 4
2625 // sizeof(blockvardecl); // size == 20
2626 // }
2627 //
2628 // For expressions, all implicit conversions are captured using the
2629 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2630 //
2631 // FIXME: If a source translation tool needs to see the original type, then
2632 // we need to consider storing both types (in ParmVarDecl)...
2633 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002634 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002635 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002636 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002637 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002638 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002639
Chris Lattner3e254fb2008-04-08 04:40:51 +00002640 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2641 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002642 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002643 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002644
Chris Lattner3e254fb2008-04-08 04:40:51 +00002645 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002646 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002647
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002648 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2649 if (D.getCXXScopeSpec().isSet()) {
2650 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2651 << D.getCXXScopeSpec().getRange();
2652 New->setInvalidDecl();
2653 }
2654
Douglas Gregor8acb7272008-12-11 16:49:14 +00002655 // Add the parameter declaration into this scope.
2656 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002657 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002658 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002659
Chris Lattner9b384ca2008-06-29 00:02:00 +00002660 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002661 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002662
Chris Lattner4b009652007-07-25 00:24:17 +00002663}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002664
Douglas Gregor65075ec2009-01-23 16:23:13 +00002665void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002666 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2667 "Not a function declarator!");
2668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002669
Chris Lattner4b009652007-07-25 00:24:17 +00002670 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2671 // for a K&R function.
2672 if (!FTI.hasPrototype) {
2673 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002674 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002675 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2676 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002677 // Implicitly declare the argument as type 'int' for lack of a better
2678 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002679 DeclSpec DS;
2680 const char* PrevSpec; // unused
2681 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2682 PrevSpec);
2683 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2684 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002685 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002686 }
2687 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002688 }
2689}
2690
2691Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2692 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2693 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2694 "Not a function declarator!");
2695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2696
2697 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002698 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002699 }
2700
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002701 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002702
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002703 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002704 ActOnDeclarator(ParentScope, D, 0,
2705 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002706}
2707
2708Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2709 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002710 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002711
2712 // See if this is a redefinition.
2713 const FunctionDecl *Definition;
2714 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002715 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002716 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002717 }
2718
Douglas Gregor8acb7272008-12-11 16:49:14 +00002719 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002720
Chris Lattner3e254fb2008-04-08 04:40:51 +00002721 // Check the validity of our function parameters
2722 CheckParmsForFunctionDef(FD);
2723
2724 // Introduce our parameters into the function scope
2725 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2726 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002727 Param->setOwningFunction(FD);
2728
Chris Lattner3e254fb2008-04-08 04:40:51 +00002729 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002730 if (Param->getIdentifier())
2731 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002732 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002733
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002734 // Checking attributes of current function definition
2735 // dllimport attribute.
2736 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2737 // dllimport attribute cannot be applied to definition.
2738 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2739 Diag(FD->getLocation(),
2740 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2741 << "dllimport";
2742 FD->setInvalidDecl();
2743 return FD;
2744 } else {
2745 // If a symbol previously declared dllimport is later defined, the
2746 // attribute is ignored in subsequent references, and a warning is
2747 // emitted.
2748 Diag(FD->getLocation(),
2749 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2750 << FD->getNameAsCString() << "dllimport";
2751 }
2752 }
Chris Lattner4b009652007-07-25 00:24:17 +00002753 return FD;
2754}
2755
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002756Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002757 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002758 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002759 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002760 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002761 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002762 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002763 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002764 } else
2765 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002766 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002767 // Verify and clean out per-function state.
2768
2769 // Check goto/label use.
2770 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2771 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2772 // Verify that we have no forward references left. If so, there was a goto
2773 // or address of a label taken, but no definition of it. Label fwd
2774 // definitions are indicated with a null substmt.
2775 if (I->second->getSubStmt() == 0) {
2776 LabelStmt *L = I->second;
2777 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002778 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002779
2780 // At this point, we have gotos that use the bogus label. Stitch it into
2781 // the function body so that they aren't leaked and that the AST is well
2782 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002783 if (Body) {
2784 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002785 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002786 } else {
2787 // The whole function wasn't parsed correctly, just delete this.
2788 delete L;
2789 }
Chris Lattner4b009652007-07-25 00:24:17 +00002790 }
2791 }
2792 LabelMap.clear();
2793
Steve Naroff99ee4302007-11-11 23:20:51 +00002794 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002795}
2796
Chris Lattner4b009652007-07-25 00:24:17 +00002797/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2798/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002799NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2800 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002801 // Extension in C99. Legal in C90, but warn about it.
2802 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002803 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002804 else
Chris Lattner65cae292008-11-19 08:23:25 +00002805 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002806
2807 // FIXME: handle stuff like:
2808 // void foo() { extern float X(); }
2809 // void bar() { X(); } <-- implicit decl for X in another scope.
2810
2811 // Set a Declarator for the implicit definition: int foo();
2812 const char *Dummy;
2813 DeclSpec DS;
2814 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2815 Error = Error; // Silence warning.
2816 assert(!Error && "Error setting up implicit decl!");
2817 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002818 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002819 D.SetIdentifier(&II, Loc);
2820
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002821 // Insert this function into translation-unit scope.
2822
2823 DeclContext *PrevDC = CurContext;
2824 CurContext = Context.getTranslationUnitDecl();
2825
Steve Naroff9104f3c2008-04-04 14:32:09 +00002826 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002827 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002828 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002829
2830 CurContext = PrevDC;
2831
Steve Naroff9104f3c2008-04-04 14:32:09 +00002832 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002833}
2834
2835
Chris Lattner82bb4792007-11-14 06:34:38 +00002836TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002837 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002838 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002839 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002840
2841 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002842 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2843 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002844 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002845 T);
2846 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002847 if (D.getInvalidType())
2848 NewTD->setInvalidDecl();
2849 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002850}
2851
Steve Naroff0acc9c92007-09-15 18:49:24 +00002852/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002853/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002854/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002855/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002856Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002857 SourceLocation KWLoc, const CXXScopeSpec &SS,
2858 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002859 AttributeList *Attr,
2860 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002861 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002862 assert((Name != 0 || TK == TK_Definition) &&
2863 "Nameless record must be a definition!");
2864
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002865 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002866 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002867 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002868 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2869 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2870 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2871 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002872 }
2873
Douglas Gregorb748fc52009-01-12 22:49:06 +00002874 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002875 DeclContext *DC = CurContext;
Douglas Gregorcab994d2009-01-09 22:42:13 +00002876 DeclContext *LexicalContext = CurContext;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002877 Decl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002878
Douglas Gregor98b27542009-01-17 00:42:38 +00002879 bool Invalid = false;
2880
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002881 if (Name && SS.isNotEmpty()) {
2882 // We have a nested-name tag ('struct foo::bar').
2883
2884 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002885 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002886 Name = 0;
2887 goto CreateNewDecl;
2888 }
2889
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002890 DC = static_cast<DeclContext*>(SS.getScopeRep());
2891 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002892 PrevDecl = dyn_cast_or_null<TagDecl>(
2893 LookupDeclInContext(Name, Decl::IDNS_Tag, DC).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002894
2895 // A tag 'foo::bar' must already exist.
2896 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002897 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002898 Name = 0;
2899 goto CreateNewDecl;
2900 }
Chris Lattner310dea32009-01-21 02:38:50 +00002901 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002902 // If this is a named struct, check to see if there was a previous forward
2903 // declaration or definition.
Steve Naroffc349ee22009-01-29 00:07:50 +00002904 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDeclInScope(Name,
2905 Decl::IDNS_Tag,S)
Chris Lattner310dea32009-01-21 02:38:50 +00002906 .getAsDecl());
Douglas Gregordb568cf2009-01-08 20:45:30 +00002907
2908 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2909 // FIXME: This makes sure that we ignore the contexts associated
2910 // with C structs, unions, and enums when looking for a matching
2911 // tag declaration or definition. See the similar lookup tweak
2912 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002913 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2914 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002915 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002916 }
2917
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002918 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002919 // Maybe we will complain about the shadowed template parameter.
2920 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2921 // Just pretend that we didn't see the previous declaration.
2922 PrevDecl = 0;
2923 }
2924
Ted Kremenekd4434152008-09-02 21:26:19 +00002925 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002926 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002927 // If this is a use of a previous tag, or if the tag is already declared
2928 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002929 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002930 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002931 // Make sure that this wasn't declared as an enum and now used as a
2932 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002933 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002934 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002935 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002936 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002937 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002938 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002939 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002940 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002941 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002942
Douglas Gregorae644892008-12-15 16:32:14 +00002943 // FIXME: In the future, return a variant or some other clue
2944 // for the consumer of this Decl to know it doesn't own it.
2945 // For our current ASTs this shouldn't be a problem, but will
2946 // need to be changed with DeclGroups.
2947 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002948 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002949
2950 // Diagnose attempts to redefine a tag.
2951 if (TK == TK_Definition) {
2952 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2953 Diag(NameLoc, diag::err_redefinition) << Name;
2954 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002955 // If this is a redefinition, recover by making this
2956 // struct be anonymous, which will make any later
2957 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002958 Name = 0;
2959 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002960 Invalid = true;
2961 } else {
2962 // If the type is currently being defined, complain
2963 // about a nested redefinition.
2964 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2965 if (Tag->isBeingDefined()) {
2966 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2967 Diag(PrevTagDecl->getLocation(),
2968 diag::note_previous_definition);
2969 Name = 0;
2970 PrevDecl = 0;
2971 Invalid = true;
2972 }
Douglas Gregorae644892008-12-15 16:32:14 +00002973 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002974
Douglas Gregorae644892008-12-15 16:32:14 +00002975 // Okay, this is definition of a previously declared or referenced
2976 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002977 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002978 }
Douglas Gregorae644892008-12-15 16:32:14 +00002979 // If we get here we have (another) forward declaration or we
2980 // have a definition. Just create a new decl.
2981 } else {
2982 // If we get here, this is a definition of a new tag type in a nested
2983 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2984 // new decl/type. We set PrevDecl to NULL so that the entities
2985 // have distinct types.
2986 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002987 }
Douglas Gregorae644892008-12-15 16:32:14 +00002988 // If we get here, we're going to create a new Decl. If PrevDecl
2989 // is non-NULL, it's a definition of the tag declared by
2990 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002991 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00002992 // PrevDecl is a namespace, template, or anything else
2993 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002994 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002995 // The tag name clashes with a namespace name, issue an error and
2996 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002997 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002998 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002999 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00003000 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00003001 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00003002 } else {
3003 // The existing declaration isn't relevant to us; we're in a
3004 // new scope, so clear out the previous declaration.
3005 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00003006 }
Chris Lattner4b009652007-07-25 00:24:17 +00003007 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00003008 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3009 (Kind != TagDecl::TK_enum)) {
3010 // C++ [basic.scope.pdecl]p5:
3011 // -- for an elaborated-type-specifier of the form
3012 //
3013 // class-key identifier
3014 //
3015 // if the elaborated-type-specifier is used in the
3016 // decl-specifier-seq or parameter-declaration-clause of a
3017 // function defined in namespace scope, the identifier is
3018 // declared as a class-name in the namespace that contains
3019 // the declaration; otherwise, except as a friend
3020 // declaration, the identifier is declared in the smallest
3021 // non-class, non-function-prototype scope that contains the
3022 // declaration.
3023 //
3024 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3025 // C structs and unions.
3026
3027 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00003028 // FIXME: We would like to maintain the current DeclContext as the
3029 // lexical context,
Douglas Gregorcab994d2009-01-09 22:42:13 +00003030 while (DC->isRecord())
3031 DC = DC->getParent();
3032 LexicalContext = DC;
3033
3034 // Find the scope where we'll be declaring the tag.
3035 while (S->isClassScope() ||
3036 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003037 ((S->getFlags() & Scope::DeclScope) == 0) ||
3038 (S->getEntity() &&
3039 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00003040 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00003041 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00003042
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003043CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00003044
3045 // If there is an identifier, use the location of the identifier as the
3046 // location of the decl, otherwise use the location of the struct/union
3047 // keyword.
3048 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3049
Douglas Gregorae644892008-12-15 16:32:14 +00003050 // Otherwise, create a new declaration. If there is a previous
3051 // declaration of the same entity, the two will be linked via
3052 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003053 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00003054
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003055 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003056 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3057 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00003058 New = EnumDecl::Create(Context, DC, Loc, Name,
3059 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003060 // If this is an undefined enum, warn.
3061 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003062 } else {
3063 // struct/union/class
3064
Chris Lattner4b009652007-07-25 00:24:17 +00003065 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3066 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003067 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003068 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00003069 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3070 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003071 else
Douglas Gregorae644892008-12-15 16:32:14 +00003072 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3073 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003074 }
Douglas Gregorae644892008-12-15 16:32:14 +00003075
3076 if (Kind != TagDecl::TK_enum) {
3077 // Handle #pragma pack: if the #pragma pack stack has non-default
3078 // alignment, make up a packed attribute for this decl. These
3079 // attributes are checked when the ASTContext lays out the
3080 // structure.
3081 //
3082 // It is important for implementing the correct semantics that this
3083 // happen here (in act on tag decl). The #pragma pack stack is
3084 // maintained as a result of parser callbacks which can occur at
3085 // many points during the parsing of a struct declaration (because
3086 // the #pragma tokens are effectively skipped over during the
3087 // parsing of the struct).
3088 if (unsigned Alignment = PackContext.getAlignment())
3089 New->addAttr(new PackedAttr(Alignment * 8));
3090 }
3091
Douglas Gregorb31f2942009-01-28 17:15:10 +00003092 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3093 // C++ [dcl.typedef]p3:
3094 // [...] Similarly, in a given scope, a class or enumeration
3095 // shall not be declared with the same name as a typedef-name
3096 // that is declared in that scope and refers to a type other
3097 // than the class or enumeration itself.
3098 LookupResult Lookup = LookupName(S, Name,
3099 LookupCriteria(LookupCriteria::Ordinary,
3100 true, true));
3101 TypedefDecl *PrevTypedef = 0;
3102 if (Lookup.getKind() == LookupResult::Found)
3103 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3104
3105 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3106 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3107 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3108 Diag(Loc, diag::err_tag_definition_of_typedef)
3109 << Context.getTypeDeclType(New)
3110 << PrevTypedef->getUnderlyingType();
3111 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3112 Invalid = true;
3113 }
3114 }
3115
Douglas Gregor98b27542009-01-17 00:42:38 +00003116 if (Invalid)
3117 New->setInvalidDecl();
3118
Douglas Gregorae644892008-12-15 16:32:14 +00003119 if (Attr)
3120 ProcessDeclAttributeList(New, Attr);
3121
Douglas Gregor98b27542009-01-17 00:42:38 +00003122 // If we're declaring or defining a tag in function prototype scope
3123 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003124 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3125 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3126
Douglas Gregorae644892008-12-15 16:32:14 +00003127 // Set the lexical context. If the tag has a C++ scope specifier, the
3128 // lexical context will be different from the semantic context.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003129 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003130
3131 if (TK == TK_Definition)
3132 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003133
3134 // If this has an identifier, add it to the scope stack.
3135 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003136 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003137
3138 // Add it to the decl chain.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003139 if (LexicalContext != CurContext) {
3140 // FIXME: PushOnScopeChains should not rely on CurContext!
3141 DeclContext *OldContext = CurContext;
3142 CurContext = LexicalContext;
3143 PushOnScopeChains(New, S);
3144 CurContext = OldContext;
3145 } else
3146 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003147 } else {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003148 LexicalContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003149 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003150
Chris Lattner4b009652007-07-25 00:24:17 +00003151 return New;
3152}
3153
Douglas Gregordb568cf2009-01-08 20:45:30 +00003154void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3155 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3156
3157 // Enter the tag context.
3158 PushDeclContext(S, Tag);
3159
3160 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3161 FieldCollector->StartClass();
3162
3163 if (Record->getIdentifier()) {
3164 // C++ [class]p2:
3165 // [...] The class-name is also inserted into the scope of the
3166 // class itself; this is known as the injected-class-name. For
3167 // purposes of access checking, the injected-class-name is treated
3168 // as if it were a public member name.
3169 RecordDecl *InjectedClassName
3170 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3171 CurContext, Record->getLocation(),
3172 Record->getIdentifier(), Record);
3173 InjectedClassName->setImplicit();
3174 PushOnScopeChains(InjectedClassName, S);
3175 }
3176 }
3177}
3178
3179void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3180 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3181
3182 if (isa<CXXRecordDecl>(Tag))
3183 FieldCollector->FinishClass();
3184
3185 // Exit this scope of this tag's definition.
3186 PopDeclContext();
3187
3188 // Notify the consumer that we've defined a tag.
3189 Consumer.HandleTagDeclDefinition(Tag);
3190}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003191
Chris Lattnera73e2202008-11-12 21:17:48 +00003192/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3193/// types into constant array types in certain situations which would otherwise
3194/// be errors (for GCC compatibility).
3195static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3196 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003197 // This method tries to turn a variable array into a constant
3198 // array even when the size isn't an ICE. This is necessary
3199 // for compatibility with code that depends on gcc's buggy
3200 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003201 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3202 if (!VLATy) return QualType();
3203
Anders Carlsson8c3de802008-12-19 20:58:05 +00003204 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003205 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003206 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003207 return QualType();
3208
Anders Carlsson8c3de802008-12-19 20:58:05 +00003209 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3210 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003211 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3212 return Context.getConstantArrayType(VLATy->getElementType(),
3213 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003214 return QualType();
3215}
3216
Anders Carlsson108229a2008-12-06 20:33:04 +00003217bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003218 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003219 // FIXME: 6.7.2.1p4 - verify the field type.
3220
3221 llvm::APSInt Value;
3222 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3223 return true;
3224
Chris Lattner8464c372008-12-12 04:56:04 +00003225 // Zero-width bitfield is ok for anonymous field.
3226 if (Value == 0 && FieldName)
3227 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3228
3229 if (Value.isNegative())
3230 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003231
3232 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3233 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003234 if (TypeSize && Value.getZExtValue() > TypeSize)
3235 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3236 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003237
3238 return false;
3239}
3240
Steve Naroff0acc9c92007-09-15 18:49:24 +00003241/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003242/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003243Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003244 SourceLocation DeclStart,
3245 Declarator &D, ExprTy *BitfieldWidth) {
3246 IdentifierInfo *II = D.getIdentifier();
3247 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003248 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003249 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003250 if (II) Loc = D.getIdentifierLoc();
3251
3252 // FIXME: Unnamed fields can be handled in various different ways, for
3253 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003254
Chris Lattner4b009652007-07-25 00:24:17 +00003255 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003256 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3257 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003258
Chris Lattner4b009652007-07-25 00:24:17 +00003259 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3260 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003261 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003262 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003263 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003264 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003265 T = FixedTy;
3266 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003267 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003268 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003269 InvalidDecl = true;
3270 }
Chris Lattner4b009652007-07-25 00:24:17 +00003271 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003272
3273 if (BitWidth) {
3274 if (VerifyBitField(Loc, II, T, BitWidth))
3275 InvalidDecl = true;
3276 } else {
3277 // Not a bitfield.
3278
3279 // validate II.
3280
3281 }
3282
Chris Lattner4b009652007-07-25 00:24:17 +00003283 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003284 FieldDecl *NewFD;
3285
Douglas Gregor8acb7272008-12-11 16:49:14 +00003286 NewFD = FieldDecl::Create(Context, Record,
3287 Loc, II, T, BitWidth,
3288 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003289 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003290
Douglas Gregordb568cf2009-01-08 20:45:30 +00003291 if (II) {
3292 Decl *PrevDecl
Steve Naroffc349ee22009-01-29 00:07:50 +00003293 = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003294 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3295 && !isa<TagDecl>(PrevDecl)) {
3296 Diag(Loc, diag::err_duplicate_member) << II;
3297 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3298 NewFD->setInvalidDecl();
3299 Record->setInvalidDecl();
3300 }
3301 }
3302
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003303 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003304 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003305 if (!T->isPODType())
3306 cast<CXXRecordDecl>(Record)->setPOD(false);
3307 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003308
Chris Lattner9b384ca2008-06-29 00:02:00 +00003309 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003310
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003311 if (D.getInvalidType() || InvalidDecl)
3312 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003313
Douglas Gregordb568cf2009-01-08 20:45:30 +00003314 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003315 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003316 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003317 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003318
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003319 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003320}
3321
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003322/// TranslateIvarVisibility - Translate visibility from a token ID to an
3323/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003324static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003325TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003326 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003327 default: assert(0 && "Unknown visitibility kind");
3328 case tok::objc_private: return ObjCIvarDecl::Private;
3329 case tok::objc_public: return ObjCIvarDecl::Public;
3330 case tok::objc_protected: return ObjCIvarDecl::Protected;
3331 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003332 }
3333}
3334
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003335/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3336/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003337Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003338 SourceLocation DeclStart,
3339 Declarator &D, ExprTy *BitfieldWidth,
3340 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003341
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003342 IdentifierInfo *II = D.getIdentifier();
3343 Expr *BitWidth = (Expr*)BitfieldWidth;
3344 SourceLocation Loc = DeclStart;
3345 if (II) Loc = D.getIdentifierLoc();
3346
3347 // FIXME: Unnamed fields can be handled in various different ways, for
3348 // example, unnamed unions inject all members into the struct namespace!
3349
Anders Carlsson108229a2008-12-06 20:33:04 +00003350 QualType T = GetTypeForDeclarator(D, S);
3351 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3352 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003353
3354 if (BitWidth) {
3355 // TODO: Validate.
3356 //printf("WARNING: BITFIELDS IGNORED!\n");
3357
3358 // 6.7.2.1p3
3359 // 6.7.2.1p4
3360
3361 } else {
3362 // Not a bitfield.
3363
3364 // validate II.
3365
3366 }
3367
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003368 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3369 // than a variably modified type.
3370 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003371 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003372 InvalidDecl = true;
3373 }
3374
Ted Kremenek173dd312008-07-23 18:04:17 +00003375 // Get the visibility (access control) for this ivar.
3376 ObjCIvarDecl::AccessControl ac =
3377 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3378 : ObjCIvarDecl::None;
3379
3380 // Construct the decl.
3381 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003382 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003383
Douglas Gregordb568cf2009-01-08 20:45:30 +00003384 if (II) {
Steve Naroffc349ee22009-01-29 00:07:50 +00003385 Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003386 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3387 && !isa<TagDecl>(PrevDecl)) {
3388 Diag(Loc, diag::err_duplicate_member) << II;
3389 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3390 NewID->setInvalidDecl();
3391 }
3392 }
3393
Ted Kremenek173dd312008-07-23 18:04:17 +00003394 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003395 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003396
3397 if (D.getInvalidType() || InvalidDecl)
3398 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003399
Douglas Gregordb568cf2009-01-08 20:45:30 +00003400 if (II) {
3401 // FIXME: When interfaces are DeclContexts, we'll need to add
3402 // these to the interface.
3403 S->AddDecl(NewID);
3404 IdResolver.AddDecl(NewID);
3405 }
3406
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003407 return NewID;
3408}
3409
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003410void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003411 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003412 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003413 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003414 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003415 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3416 assert(EnclosingDecl && "missing record or interface decl");
3417 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3418
Chris Lattner4b009652007-07-25 00:24:17 +00003419 // Verify that all the fields are okay.
3420 unsigned NumNamedMembers = 0;
3421 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003422
Chris Lattner4b009652007-07-25 00:24:17 +00003423 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003424 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3425 assert(FD && "missing field decl");
3426
Chris Lattner4b009652007-07-25 00:24:17 +00003427 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003428 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003429
Douglas Gregordb568cf2009-01-08 20:45:30 +00003430 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003431 // Remember all fields written by the user.
3432 RecFields.push_back(FD);
3433 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003434
Chris Lattner4b009652007-07-25 00:24:17 +00003435 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003436 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003437 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003438 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003439 FD->setInvalidDecl();
3440 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003441 continue;
3442 }
Chris Lattner4b009652007-07-25 00:24:17 +00003443 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3444 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003445 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003446 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3447 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003448 FD->setInvalidDecl();
3449 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003450 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003451 }
Chris Lattner4b009652007-07-25 00:24:17 +00003452 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003453 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003454 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003455 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3456 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003457 FD->setInvalidDecl();
3458 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003459 continue;
3460 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003461 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003462 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003463 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003464 FD->setInvalidDecl();
3465 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003466 continue;
3467 }
Chris Lattner4b009652007-07-25 00:24:17 +00003468 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003469 if (Record)
3470 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003471 }
Chris Lattner4b009652007-07-25 00:24:17 +00003472 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3473 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003474 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003475 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3476 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003477 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003478 Record->setHasFlexibleArrayMember(true);
3479 } else {
3480 // If this is a struct/class and this is not the last element, reject
3481 // it. Note that GCC supports variable sized arrays in the middle of
3482 // structures.
3483 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003484 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003485 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003486 FD->setInvalidDecl();
3487 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003488 continue;
3489 }
Chris Lattner4b009652007-07-25 00:24:17 +00003490 // We support flexible arrays at the end of structs in other structs
3491 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003492 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003493 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003494 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003495 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003496 }
3497 }
3498 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003499 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003500 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003501 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003502 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003503 FD->setInvalidDecl();
3504 EnclosingDecl->setInvalidDecl();
3505 continue;
3506 }
Chris Lattner4b009652007-07-25 00:24:17 +00003507 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003508 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003509 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003510 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003511
Chris Lattner4b009652007-07-25 00:24:17 +00003512 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003513 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003514 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003515 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003516 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003517 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003518 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003519 // Must enforce the rule that ivars in the base classes may not be
3520 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003521 if (ID->getSuperClass()) {
3522 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3523 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3524 ObjCIvarDecl* Ivar = (*IVI);
3525 IdentifierInfo *II = Ivar->getIdentifier();
3526 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3527 if (prevIvar) {
3528 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003529 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003530 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003531 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003532 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003533 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003534 else if (ObjCImplementationDecl *IMPDecl =
3535 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003536 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3537 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003538 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003539 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003540 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003541
3542 if (Attr)
3543 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003544}
3545
Steve Naroff0acc9c92007-09-15 18:49:24 +00003546Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003547 DeclTy *lastEnumConst,
3548 SourceLocation IdLoc, IdentifierInfo *Id,
3549 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003550 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003551 EnumConstantDecl *LastEnumConst =
3552 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3553 Expr *Val = static_cast<Expr*>(val);
3554
Chris Lattnera7549902007-08-26 06:24:45 +00003555 // The scope passed in may not be a decl scope. Zip up the scope tree until
3556 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003557 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003558
Chris Lattner4b009652007-07-25 00:24:17 +00003559 // Verify that there isn't already something declared with this name in this
3560 // scope.
Steve Naroffc349ee22009-01-29 00:07:50 +00003561 Decl *PrevDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003562 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003563 // Maybe we will complain about the shadowed template parameter.
3564 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3565 // Just pretend that we didn't see the previous declaration.
3566 PrevDecl = 0;
3567 }
3568
3569 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003570 // When in C++, we may get a TagDecl with the same name; in this case the
3571 // enum constant will 'hide' the tag.
3572 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3573 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003574 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003575 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003576 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003577 else
Chris Lattner65cae292008-11-19 08:23:25 +00003578 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003579 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003580 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003581 return 0;
3582 }
3583 }
3584
3585 llvm::APSInt EnumVal(32);
3586 QualType EltTy;
3587 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003588 // Make sure to promote the operand type to int.
3589 UsualUnaryConversions(Val);
3590
Chris Lattner4b009652007-07-25 00:24:17 +00003591 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3592 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003593 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003594 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003595 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003596 } else {
3597 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003598 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003599 }
3600
3601 if (!Val) {
3602 if (LastEnumConst) {
3603 // Assign the last value + 1.
3604 EnumVal = LastEnumConst->getInitVal();
3605 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003606
3607 // Check for overflow on increment.
3608 if (EnumVal < LastEnumConst->getInitVal())
3609 Diag(IdLoc, diag::warn_enum_value_overflow);
3610
Chris Lattnere7f53a42007-08-27 17:37:24 +00003611 EltTy = LastEnumConst->getType();
3612 } else {
3613 // First value, set to zero.
3614 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003615 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003616 }
Chris Lattner4b009652007-07-25 00:24:17 +00003617 }
3618
Chris Lattnere4650482008-03-15 06:12:44 +00003619 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003620 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003621 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003622
3623 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003624 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003625
Chris Lattner4b009652007-07-25 00:24:17 +00003626 return New;
3627}
3628
Steve Naroffb0726b82008-08-07 14:08:16 +00003629// FIXME: For consistency with ActOnFields(), we should have the parser
3630// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003631void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003632 DeclTy **Elements, unsigned NumElements) {
3633 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003634 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003635
Chris Lattner435c3fd2007-08-28 05:10:31 +00003636 // TODO: If the result value doesn't fit in an int, it must be a long or long
3637 // long value. ISO C does not support this, but GCC does as an extension,
3638 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003639 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003640
Chris Lattner206754a2007-08-28 06:15:15 +00003641 // Verify that all the values are okay, compute the size of the values, and
3642 // reverse the list.
3643 unsigned NumNegativeBits = 0;
3644 unsigned NumPositiveBits = 0;
3645
3646 // Keep track of whether all elements have type int.
3647 bool AllElementsInt = true;
3648
Chris Lattner4b009652007-07-25 00:24:17 +00003649 for (unsigned i = 0; i != NumElements; ++i) {
3650 EnumConstantDecl *ECD =
3651 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3652 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003653
3654 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003655 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003656 assert(InitVal.getBitWidth() >= IntWidth &&
3657 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003658 if (InitVal.getBitWidth() > IntWidth) {
3659 llvm::APSInt V(InitVal);
3660 V.trunc(IntWidth);
3661 V.extend(InitVal.getBitWidth());
3662 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003663 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3664 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003665 }
Chris Lattner206754a2007-08-28 06:15:15 +00003666
3667 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003668 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003669 NumPositiveBits = std::max(NumPositiveBits,
3670 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003671 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003672 NumNegativeBits = std::max(NumNegativeBits,
3673 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003674
Chris Lattner206754a2007-08-28 06:15:15 +00003675 // Keep track of whether every enum element has type int (very commmon).
3676 if (AllElementsInt)
3677 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003678 }
3679
Chris Lattner206754a2007-08-28 06:15:15 +00003680 // Figure out the type that should be used for this enum.
3681 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3682 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003683 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003684
3685 if (NumNegativeBits) {
3686 // If there is a negative value, figure out the smallest integer type (of
3687 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003688 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003689 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003690 BestWidth = IntWidth;
3691 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003692 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003693
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003694 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003695 BestType = Context.LongTy;
3696 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003697 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003698
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003699 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003700 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3701 BestType = Context.LongLongTy;
3702 }
3703 }
3704 } else {
3705 // If there is no negative value, figure out which of uint, ulong, ulonglong
3706 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003707 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003708 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003709 BestWidth = IntWidth;
3710 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003711 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003712 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003713 } else {
3714 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003715 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003716 "How could an initializer get larger than ULL?");
3717 BestType = Context.UnsignedLongLongTy;
3718 }
3719 }
3720
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003721 // Loop over all of the enumerator constants, changing their types to match
3722 // the type of the enum if needed.
3723 for (unsigned i = 0; i != NumElements; ++i) {
3724 EnumConstantDecl *ECD =
3725 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3726 if (!ECD) continue; // Already issued a diagnostic.
3727
3728 // Standard C says the enumerators have int type, but we allow, as an
3729 // extension, the enumerators to be larger than int size. If each
3730 // enumerator value fits in an int, type it as an int, otherwise type it the
3731 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3732 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003733 if (ECD->getType() == Context.IntTy) {
3734 // Make sure the init value is signed.
3735 llvm::APSInt IV = ECD->getInitVal();
3736 IV.setIsSigned(true);
3737 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003738
3739 if (getLangOptions().CPlusPlus)
3740 // C++ [dcl.enum]p4: Following the closing brace of an
3741 // enum-specifier, each enumerator has the type of its
3742 // enumeration.
3743 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003744 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003745 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003746
3747 // Determine whether the value fits into an int.
3748 llvm::APSInt InitVal = ECD->getInitVal();
3749 bool FitsInInt;
3750 if (InitVal.isUnsigned() || !InitVal.isNegative())
3751 FitsInInt = InitVal.getActiveBits() < IntWidth;
3752 else
3753 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3754
3755 // If it fits into an integer type, force it. Otherwise force it to match
3756 // the enum decl type.
3757 QualType NewTy;
3758 unsigned NewWidth;
3759 bool NewSign;
3760 if (FitsInInt) {
3761 NewTy = Context.IntTy;
3762 NewWidth = IntWidth;
3763 NewSign = true;
3764 } else if (ECD->getType() == BestType) {
3765 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003766 if (getLangOptions().CPlusPlus)
3767 // C++ [dcl.enum]p4: Following the closing brace of an
3768 // enum-specifier, each enumerator has the type of its
3769 // enumeration.
3770 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003771 continue;
3772 } else {
3773 NewTy = BestType;
3774 NewWidth = BestWidth;
3775 NewSign = BestType->isSignedIntegerType();
3776 }
3777
3778 // Adjust the APSInt value.
3779 InitVal.extOrTrunc(NewWidth);
3780 InitVal.setIsSigned(NewSign);
3781 ECD->setInitVal(InitVal);
3782
3783 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003784 if (ECD->getInitExpr())
3785 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3786 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003787 if (getLangOptions().CPlusPlus)
3788 // C++ [dcl.enum]p4: Following the closing brace of an
3789 // enum-specifier, each enumerator has the type of its
3790 // enumeration.
3791 ECD->setType(EnumType);
3792 else
3793 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003794 }
Chris Lattner206754a2007-08-28 06:15:15 +00003795
Douglas Gregor8acb7272008-12-11 16:49:14 +00003796 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003797}
3798
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003799Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003800 ExprArg expr) {
3801 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3802
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003803 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003804}
3805
Douglas Gregorad17e372008-12-16 22:23:02 +00003806
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003807void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3808 ExprTy *alignment, SourceLocation PragmaLoc,
3809 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3810 Expr *Alignment = static_cast<Expr *>(alignment);
3811
3812 // If specified then alignment must be a "small" power of two.
3813 unsigned AlignmentVal = 0;
3814 if (Alignment) {
3815 llvm::APSInt Val;
3816 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3817 !Val.isPowerOf2() ||
3818 Val.getZExtValue() > 16) {
3819 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3820 delete Alignment;
3821 return; // Ignore
3822 }
3823
3824 AlignmentVal = (unsigned) Val.getZExtValue();
3825 }
3826
3827 switch (Kind) {
3828 case Action::PPK_Default: // pack([n])
3829 PackContext.setAlignment(AlignmentVal);
3830 break;
3831
3832 case Action::PPK_Show: // pack(show)
3833 // Show the current alignment, making sure to show the right value
3834 // for the default.
3835 AlignmentVal = PackContext.getAlignment();
3836 // FIXME: This should come from the target.
3837 if (AlignmentVal == 0)
3838 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003839 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003840 break;
3841
3842 case Action::PPK_Push: // pack(push [, id] [, [n])
3843 PackContext.push(Name);
3844 // Set the new alignment if specified.
3845 if (Alignment)
3846 PackContext.setAlignment(AlignmentVal);
3847 break;
3848
3849 case Action::PPK_Pop: // pack(pop [, id] [, n])
3850 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3851 // "#pragma pack(pop, identifier, n) is undefined"
3852 if (Alignment && Name)
3853 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3854
3855 // Do the pop.
3856 if (!PackContext.pop(Name)) {
3857 // If a name was specified then failure indicates the name
3858 // wasn't found. Otherwise failure indicates the stack was
3859 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003860 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3861 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003862
3863 // FIXME: Warn about popping named records as MSVC does.
3864 } else {
3865 // Pop succeeded, set the new alignment if specified.
3866 if (Alignment)
3867 PackContext.setAlignment(AlignmentVal);
3868 }
3869 break;
3870
3871 default:
3872 assert(0 && "Invalid #pragma pack kind.");
3873 }
3874}
3875
3876bool PragmaPackStack::pop(IdentifierInfo *Name) {
3877 if (Stack.empty())
3878 return false;
3879
3880 // If name is empty just pop top.
3881 if (!Name) {
3882 Alignment = Stack.back().first;
3883 Stack.pop_back();
3884 return true;
3885 }
3886
3887 // Otherwise, find the named record.
3888 for (unsigned i = Stack.size(); i != 0; ) {
3889 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003890 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003891 // Found it, pop up to and including this record.
3892 Alignment = Stack[i].first;
3893 Stack.erase(Stack.begin() + i, Stack.end());
3894 return true;
3895 }
3896 }
3897
3898 return false;
3899}