blob: 22650f525dbb8a615d07e15a2f02a01f3c0bf9f0 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
Steve Naroff939837f2009-01-28 15:51:12 +000042 LookupResult Result = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor7176fff2009-01-15 00:26:24 +000044 Decl *IIDecl = 0;
45 switch (Result.getKind()) {
46 case LookupResult::NotFound:
47 case LookupResult::FoundOverloaded:
48 case LookupResult::AmbiguousBaseSubobjectTypes:
49 case LookupResult::AmbiguousBaseSubobjects:
50 // FIXME: In the event of an ambiguous lookup, we could visit all of
51 // the entities found to determine whether they are all types. This
52 // might provide better diagnostics.
53 return 0;
54
55 case LookupResult::Found:
56 IIDecl = Result.getAsDecl();
57 break;
58 }
59
60 if (isa<TypedefDecl>(IIDecl) ||
61 isa<ObjCInterfaceDecl>(IIDecl) ||
62 isa<TagDecl>(IIDecl) ||
63 isa<TemplateTypeParmDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000064 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000065 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000066}
67
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000068DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000070 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000071 if (MD->isOutOfLineDefinition())
72 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073
74 // A C++ inline method is parsed *after* the topmost class it was declared in
75 // is fully parsed (it's "complete").
76 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000077 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000078 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
79 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000080 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000081 DC = RD;
82
83 // Return the declaration context of the topmost class the inline method is
84 // declared in.
85 return DC;
86 }
87
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000088 if (isa<ObjCMethodDecl>(DC))
89 return Context.getTranslationUnitDecl();
90
Douglas Gregor4afa39d2009-01-20 01:17:11 +000091 if (Decl *D = dyn_cast<Decl>(DC))
92 return D->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000093
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000094 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000095}
96
Douglas Gregor44b43212008-12-11 16:49:14 +000097void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000098 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000099 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000100 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000101 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000102}
103
Chris Lattnerb048c982008-04-06 04:47:34 +0000104void Sema::PopDeclContext() {
105 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000106
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000107 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000108}
109
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000110/// Add this decl to the scope shadowed decl chains.
111void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000112 // Move up the scope chain until we find the nearest enclosing
113 // non-transparent context. The declaration will be introduced into this
114 // scope.
115 while (S->getEntity() &&
116 ((DeclContext *)S->getEntity())->isTransparentContext())
117 S = S->getParent();
118
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000119 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000120
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000121 // Add scoped declarations into their context, so that they can be
122 // found later. Declarations without a context won't be inserted
123 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000124 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000125
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000126 // C++ [basic.scope]p4:
127 // -- exactly one declaration shall declare a class name or
128 // enumeration name that is not a typedef name and the other
129 // declarations shall all refer to the same object or
130 // enumerator, or all refer to functions and function templates;
131 // in this case the class name or enumeration name is hidden.
132 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
133 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000134 if (CurContext->getLookupContext()
135 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000136 // We're pushing the tag into the current context, which might
137 // require some reshuffling in the identifier resolver.
138 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000139 I = IdResolver.begin(TD->getDeclName(), CurContext,
140 false/*LookInParentCtx*/),
141 IEnd = IdResolver.end();
142 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
143 NamedDecl *PrevDecl = *I;
144 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
145 PrevDecl = *I, ++I) {
146 if (TD->declarationReplaces(*I)) {
147 // This is a redeclaration. Remove it from the chain and
148 // break out, so that we'll add in the shadowed
149 // declaration.
150 S->RemoveDecl(*I);
151 if (PrevDecl == *I) {
152 IdResolver.RemoveDecl(*I);
153 IdResolver.AddDecl(TD);
154 return;
155 } else {
156 IdResolver.RemoveDecl(*I);
157 break;
158 }
159 }
160 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000161
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000162 // There is already a declaration with the same name in the same
163 // scope, which is not a tag declaration. It must be found
164 // before we find the new declaration, so insert the new
165 // declaration at the end of the chain.
166 IdResolver.AddShadowedDecl(TD, PrevDecl);
167
168 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000169 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000170 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000171 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 // We are pushing the name of a function, which might be an
173 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000174 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000175 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000176 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000177 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000178 false/*LookInParentCtx*/),
179 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000180 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000181 FD));
182 if (Redecl != IdResolver.end()) {
183 // There is already a declaration of a function on our
184 // IdResolver chain. Replace it with this declaration.
185 S->RemoveDecl(*Redecl);
186 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000187 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000188 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000190 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000191}
192
Steve Naroffb216c882007-10-09 22:01:59 +0000193void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000194 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000195 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
196 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000197
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
199 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000200 Decl *TmpD = static_cast<Decl*>(*I);
201 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000202
Douglas Gregor44b43212008-12-11 16:49:14 +0000203 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
204 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000205
Douglas Gregor44b43212008-12-11 16:49:14 +0000206 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000207
Douglas Gregor44b43212008-12-11 16:49:14 +0000208 // Remove this name from our lexical scope.
209 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000210 }
211}
212
Steve Naroffe8043c32008-04-01 23:04:06 +0000213/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
214/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000215ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000216 // The third "scope" argument is 0 since we aren't enabling lazy built-in
217 // creation from this context.
Steve Naroff133147d2009-01-28 16:09:22 +0000218 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000219
Steve Naroffb327ce02008-04-02 14:35:35 +0000220 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000221}
222
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000223/// getNonFieldDeclScope - Retrieves the innermost scope, starting
224/// from S, where a non-field would be declared. This routine copes
225/// with the difference between C and C++ scoping rules in structs and
226/// unions. For example, the following code is well-formed in C but
227/// ill-formed in C++:
228/// @code
229/// struct S6 {
230/// enum { BAR } e;
231/// };
232///
233/// void test_S6() {
234/// struct S6 a;
235/// a.e = BAR;
236/// }
237/// @endcode
238/// For the declaration of BAR, this routine will return a different
239/// scope. The scope S will be the scope of the unnamed enumeration
240/// within S6. In C++, this routine will return the scope associated
241/// with S6, because the enumeration's scope is a transparent
242/// context but structures can contain non-field names. In C, this
243/// routine will return the translation unit scope, since the
244/// enumeration's scope is a transparent context and structures cannot
245/// contain non-field names.
246Scope *Sema::getNonFieldDeclScope(Scope *S) {
247 while (((S->getFlags() & Scope::DeclScope) == 0) ||
248 (S->getEntity() &&
249 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
250 (S->isClassScope() && !getLangOptions().CPlusPlus))
251 S = S->getParent();
252 return S;
253}
254
Steve Naroffe8043c32008-04-01 23:04:06 +0000255/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000256/// namespace. NamespaceNameOnly - during lookup only namespace names
257/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
258/// 'When looking up a namespace-name in a using-directive or
259/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000260///
261/// Note: The use of this routine is deprecated. Please use
262/// LookupName, LookupQualifiedName, or LookupParsedName instead.
263Sema::LookupResult
264Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
265 const DeclContext *LookupCtx,
Steve Naroff133147d2009-01-28 16:09:22 +0000266 bool LookInParent) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000267 LookupCriteria::NameKind Kind;
268 if (NSI == Decl::IDNS_Ordinary) {
Steve Naroff133147d2009-01-28 16:09:22 +0000269 Kind = LookupCriteria::Ordinary;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000270 } else if (NSI == Decl::IDNS_Tag)
271 Kind = LookupCriteria::Tag;
Chris Lattner95d58f32009-01-16 19:44:00 +0000272 else {
273 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000274 Kind = LookupCriteria::Member;
Chris Lattner95d58f32009-01-16 19:44:00 +0000275 }
276
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000277 if (LookupCtx)
278 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
279 LookupCriteria(Kind, !LookInParent,
280 getLangOptions().CPlusPlus));
Douglas Gregor72de6672009-01-08 20:45:30 +0000281
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000282 // Unqualified lookup
283 return LookupName(S, Name,
284 LookupCriteria(Kind, !LookInParent,
285 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000286}
287
Chris Lattner95e2c712008-05-05 22:18:14 +0000288void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000289 if (!Context.getBuiltinVaListType().isNull())
290 return;
291
292 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000293 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000294 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000295 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
296}
297
Reid Spencer5f016e22007-07-11 17:01:13 +0000298/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
299/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000300NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
301 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 Builtin::ID BID = (Builtin::ID)bid;
303
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000304 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000305 InitBuiltinVaListType();
306
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000307 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000308 FunctionDecl *New = FunctionDecl::Create(Context,
309 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000310 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000311 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
Chris Lattner95e2c712008-05-05 22:18:14 +0000313 // Create Decl objects for each parameter, adding them to the
314 // FunctionDecl.
315 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
316 llvm::SmallVector<ParmVarDecl*, 16> Params;
317 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
318 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000319 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000320 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000321 }
322
323
324
Chris Lattner7f925cc2008-04-11 07:00:53 +0000325 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000326 // FIXME: This is hideous. We need to teach PushOnScopeChains to
327 // relate Scopes to DeclContexts, and probably eliminate CurContext
328 // entirely, but we're not there yet.
329 DeclContext *SavedContext = CurContext;
330 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000331 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000332 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 return New;
334}
335
Sebastian Redlc42e1182008-11-11 11:37:55 +0000336/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
337/// everything from the standard library is defined.
338NamespaceDecl *Sema::GetStdNamespace() {
339 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000340 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000341 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroff939837f2009-01-28 15:51:12 +0000342 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary, 0, Global);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000343 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
344 }
345 return StdNamespace;
346}
347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
349/// and scope as a previous declaration 'Old'. Figure out how to resolve this
350/// situation, merging decls or emitting diagnostics as appropriate.
351///
Steve Naroffe8043c32008-04-01 23:04:06 +0000352TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000353 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000354 // Allow multiple definitions for ObjC built-in typedefs.
355 // FIXME: Verify the underlying types are equivalent!
356 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000357 const IdentifierInfo *TypeID = New->getIdentifier();
358 switch (TypeID->getLength()) {
359 default: break;
360 case 2:
361 if (!TypeID->isStr("id"))
362 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000363 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000364 objc_types = true;
365 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000366 case 5:
367 if (!TypeID->isStr("Class"))
368 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000369 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000370 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000371 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000372 case 3:
373 if (!TypeID->isStr("SEL"))
374 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000375 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000376 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000377 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000378 case 8:
379 if (!TypeID->isStr("Protocol"))
380 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000381 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000382 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000383 return New;
384 }
385 // Fall through - the typedef name was not a builtin type.
386 }
Douglas Gregor66973122009-01-28 17:15:10 +0000387 // Verify the old decl was also a type.
388 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000390 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000391 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000392 if (!objc_types)
393 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 return New;
395 }
Douglas Gregor66973122009-01-28 17:15:10 +0000396
397 // Determine the "old" type we'll use for checking and diagnostics.
398 QualType OldType;
399 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
400 OldType = OldTypedef->getUnderlyingType();
401 else
402 OldType = Context.getTypeDeclType(Old);
403
Chris Lattner99cb9972008-07-25 18:44:27 +0000404 // If the typedef types are not identical, reject them in all languages and
405 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000406
407 if (OldType != New->getUnderlyingType() &&
408 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000409 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000410 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000411 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000412 if (!objc_types)
413 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000414 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000415 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000416 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000417 if (getLangOptions().Microsoft) return New;
418
Douglas Gregorbbe27432008-11-21 16:29:06 +0000419 // C++ [dcl.typedef]p2:
420 // In a given non-class scope, a typedef specifier can be used to
421 // redefine the name of any type declared in that scope to refer
422 // to the type to which it already refers.
423 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
424 return New;
425
426 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000427 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
428 // *either* declaration is in a system header. The code below implements
429 // this adhoc compatibility rule. FIXME: The following code will not
430 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000431 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
432 SourceManager &SrcMgr = Context.getSourceManager();
433 if (SrcMgr.isInSystemHeader(Old->getLocation()))
434 return New;
435 if (SrcMgr.isInSystemHeader(New->getLocation()))
436 return New;
437 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000438
Chris Lattner08631c52008-11-23 21:45:46 +0000439 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000440 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000441 return New;
442}
443
Chris Lattner6b6b5372008-06-26 18:38:35 +0000444/// DeclhasAttr - returns true if decl Declaration already has the target
445/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000446static bool DeclHasAttr(const Decl *decl, const Attr *target) {
447 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
448 if (attr->getKind() == target->getKind())
449 return true;
450
451 return false;
452}
453
454/// MergeAttributes - append attributes from the Old decl to the New one.
455static void MergeAttributes(Decl *New, Decl *Old) {
456 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
457
Chris Lattnerddee4232008-03-03 03:28:21 +0000458 while (attr) {
459 tmp = attr;
460 attr = attr->getNext();
461
462 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000463 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000464 New->addAttr(tmp);
465 } else {
466 tmp->setNext(0);
467 delete(tmp);
468 }
469 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000470
471 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000472}
473
Chris Lattner04421082008-04-08 04:40:51 +0000474/// MergeFunctionDecl - We just parsed a function 'New' from
475/// declarator D which has the same name and scope as a previous
476/// declaration 'Old'. Figure out how to resolve this situation,
477/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478/// Redeclaration will be set true if this New is a redeclaration OldD.
479///
480/// In C++, New and Old must be declarations that are not
481/// overloaded. Use IsOverload to determine whether New and Old are
482/// overloaded, and to select the Old declaration that New should be
483/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000484FunctionDecl *
485Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000486 assert(!isa<OverloadedFunctionDecl>(OldD) &&
487 "Cannot merge with an overloaded function declaration");
488
Douglas Gregorf0097952008-04-21 02:02:58 +0000489 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // Verify the old decl was also a function.
491 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
492 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000493 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000494 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000495 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 return New;
497 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498
499 // Determine whether the previous declaration was a definition,
500 // implicit declaration, or a declaration.
501 diag::kind PrevDiag;
502 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000503 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000505 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000507 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000508
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000509 QualType OldQType = Context.getCanonicalType(Old->getType());
510 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000511
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 if (getLangOptions().CPlusPlus) {
513 // (C++98 13.1p2):
514 // Certain function declarations cannot be overloaded:
515 // -- Function declarations that differ only in the return type
516 // cannot be overloaded.
517 QualType OldReturnType
518 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
519 QualType NewReturnType
520 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
521 if (OldReturnType != NewReturnType) {
522 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
523 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000524 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525 return New;
526 }
527
528 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
529 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
530 if (OldMethod && NewMethod) {
531 // -- Member function declarations with the same name and the
532 // same parameter types cannot be overloaded if any of them
533 // is a static member function declaration.
534 if (OldMethod->isStatic() || NewMethod->isStatic()) {
535 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
536 Diag(Old->getLocation(), PrevDiag);
537 return New;
538 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000539
540 // C++ [class.mem]p1:
541 // [...] A member shall not be declared twice in the
542 // member-specification, except that a nested class or member
543 // class template can be declared and then later defined.
544 if (OldMethod->getLexicalDeclContext() ==
545 NewMethod->getLexicalDeclContext()) {
546 unsigned NewDiag;
547 if (isa<CXXConstructorDecl>(OldMethod))
548 NewDiag = diag::err_constructor_redeclared;
549 else if (isa<CXXDestructorDecl>(NewMethod))
550 NewDiag = diag::err_destructor_redeclared;
551 else if (isa<CXXConversionDecl>(NewMethod))
552 NewDiag = diag::err_conv_function_redeclared;
553 else
554 NewDiag = diag::err_member_redeclared;
555
556 Diag(New->getLocation(), NewDiag);
557 Diag(Old->getLocation(), PrevDiag);
558 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559 }
560
561 // (C++98 8.3.5p3):
562 // All declarations for a function shall agree exactly in both the
563 // return type and the parameter-type-list.
564 if (OldQType == NewQType) {
565 // We have a redeclaration.
566 MergeAttributes(New, Old);
567 Redeclaration = true;
568 return MergeCXXFunctionDecl(New, Old);
569 }
570
571 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000572 }
Chris Lattner04421082008-04-08 04:40:51 +0000573
574 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000575 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000576 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000577 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000578 MergeAttributes(New, Old);
579 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000580 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000581 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000582
Steve Naroff837618c2008-01-16 15:01:34 +0000583 // A function that has already been declared has been redeclared or defined
584 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
587 // TODO: This is totally simplistic. It should handle merging functions
588 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000589 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000590 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 return New;
592}
593
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000594/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000595static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000596 if (VD->isFileVarDecl())
597 return (!VD->getInit() &&
598 (VD->getStorageClass() == VarDecl::None ||
599 VD->getStorageClass() == VarDecl::Static));
600 return false;
601}
602
603/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
604/// when dealing with C "tentative" external object definitions (C99 6.9.2).
605void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
606 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000607 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000608
Douglas Gregore21b9942009-01-07 16:34:42 +0000609 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000610 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000611 for (IdentifierResolver::iterator
612 I = IdResolver.begin(VD->getIdentifier(),
613 VD->getDeclContext(), false/*LookInParentCtx*/),
614 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000615 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000616 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
617
Steve Narofff855e6f2008-08-10 15:20:13 +0000618 // Handle the following case:
619 // int a[10];
620 // int a[]; - the code below makes sure we set the correct type.
621 // int a[11]; - this is an error, size isn't 10.
622 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
623 OldDecl->getType()->isConstantArrayType())
624 VD->setType(OldDecl->getType());
625
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000626 // Check for "tentative" definitions. We can't accomplish this in
627 // MergeVarDecl since the initializer hasn't been attached.
628 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
629 continue;
630
631 // Handle __private_extern__ just like extern.
632 if (OldDecl->getStorageClass() != VarDecl::Extern &&
633 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
634 VD->getStorageClass() != VarDecl::Extern &&
635 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000636 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000637 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000638 }
639 }
640 }
641}
642
Reid Spencer5f016e22007-07-11 17:01:13 +0000643/// MergeVarDecl - We just parsed a variable 'New' which has the same name
644/// and scope as a previous declaration 'Old'. Figure out how to resolve this
645/// situation, merging decls or emitting diagnostics as appropriate.
646///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000647/// Tentative definition rules (C99 6.9.2p2) are checked by
648/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
649/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000650///
Steve Naroffe8043c32008-04-01 23:04:06 +0000651VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 // Verify the old decl was also a variable.
653 VarDecl *Old = dyn_cast<VarDecl>(OldD);
654 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000655 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000656 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000657 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 return New;
659 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000660
661 MergeAttributes(New, Old);
662
Eli Friedman13ca96a2009-01-24 23:49:55 +0000663 // Merge the types
664 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
665 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000666 Diag(New->getLocation(), diag::err_redefinition_different_type)
667 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000668 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 return New;
670 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000671 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000672 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
673 if (New->getStorageClass() == VarDecl::Static &&
674 (Old->getStorageClass() == VarDecl::None ||
675 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000676 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000678 return New;
679 }
680 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
681 if (New->getStorageClass() != VarDecl::Static &&
682 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000683 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000684 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000685 return New;
686 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000687 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
688 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000689 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000690 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 }
692 return New;
693}
694
Chris Lattner04421082008-04-08 04:40:51 +0000695/// CheckParmsForFunctionDef - Check that the parameters of the given
696/// function are appropriate for the definition of a function. This
697/// takes care of any checks that cannot be performed on the
698/// declaration itself, e.g., that the types of each of the function
699/// parameters are complete.
700bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
701 bool HasInvalidParm = false;
702 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
703 ParmVarDecl *Param = FD->getParamDecl(p);
704
705 // C99 6.7.5.3p4: the parameters in a parameter type list in a
706 // function declarator that is part of a function definition of
707 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000708 if (!Param->isInvalidDecl() &&
709 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
710 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000711 Param->setInvalidDecl();
712 HasInvalidParm = true;
713 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000714
715 // C99 6.9.1p5: If the declarator includes a parameter type list, the
716 // declaration of each parameter shall include an identifier.
717 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
718 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000719 }
720
721 return HasInvalidParm;
722}
723
Reid Spencer5f016e22007-07-11 17:01:13 +0000724/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
725/// no declarator (e.g. "struct foo;") is parsed.
726Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000727 TagDecl *Tag
728 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
729 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
730 if (!Record->getDeclName() && Record->isDefinition() &&
731 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
732 return BuildAnonymousStructOrUnion(S, DS, Record);
733
734 // Microsoft allows unnamed struct/union fields. Don't complain
735 // about them.
736 // FIXME: Should we support Microsoft's extensions in this area?
737 if (Record->getDeclName() && getLangOptions().Microsoft)
738 return Tag;
739 }
740
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000741 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000742 // Warn about typedefs of enums without names, since this is an
743 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000744 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
745 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000746 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000747 << DS.getSourceRange();
748 return Tag;
749 }
750
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000751 // FIXME: This diagnostic is emitted even when various previous
752 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
753 // DeclSpec has no means of communicating this information, and the
754 // responsible parser functions are quite far apart.
755 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
756 << DS.getSourceRange();
757 return 0;
758 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000759
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000760 return Tag;
761}
762
763/// InjectAnonymousStructOrUnionMembers - Inject the members of the
764/// anonymous struct or union AnonRecord into the owning context Owner
765/// and scope S. This routine will be invoked just after we realize
766/// that an unnamed union or struct is actually an anonymous union or
767/// struct, e.g.,
768///
769/// @code
770/// union {
771/// int i;
772/// float f;
773/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
774/// // f into the surrounding scope.x
775/// @endcode
776///
777/// This routine is recursive, injecting the names of nested anonymous
778/// structs/unions into the owning context and scope as well.
779bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
780 RecordDecl *AnonRecord) {
781 bool Invalid = false;
782 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
783 FEnd = AnonRecord->field_end();
784 F != FEnd; ++F) {
785 if ((*F)->getDeclName()) {
786 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
Steve Naroff133147d2009-01-28 16:09:22 +0000787 S, Owner, false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000788 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
789 // C++ [class.union]p2:
790 // The names of the members of an anonymous union shall be
791 // distinct from the names of any other entity in the
792 // scope in which the anonymous union is declared.
793 unsigned diagKind
794 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
795 : diag::err_anonymous_struct_member_redecl;
796 Diag((*F)->getLocation(), diagKind)
797 << (*F)->getDeclName();
798 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
799 Invalid = true;
800 } else {
801 // C++ [class.union]p2:
802 // For the purpose of name lookup, after the anonymous union
803 // definition, the members of the anonymous union are
804 // considered to have been defined in the scope in which the
805 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000806 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000807 S->AddDecl(*F);
808 IdResolver.AddDecl(*F);
809 }
810 } else if (const RecordType *InnerRecordType
811 = (*F)->getType()->getAsRecordType()) {
812 RecordDecl *InnerRecord = InnerRecordType->getDecl();
813 if (InnerRecord->isAnonymousStructOrUnion())
814 Invalid = Invalid ||
815 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
816 }
817 }
818
819 return Invalid;
820}
821
822/// ActOnAnonymousStructOrUnion - Handle the declaration of an
823/// anonymous structure or union. Anonymous unions are a C++ feature
824/// (C++ [class.union]) and a GNU C extension; anonymous structures
825/// are a GNU C and GNU C++ extension.
826Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
827 RecordDecl *Record) {
828 DeclContext *Owner = Record->getDeclContext();
829
830 // Diagnose whether this anonymous struct/union is an extension.
831 if (Record->isUnion() && !getLangOptions().CPlusPlus)
832 Diag(Record->getLocation(), diag::ext_anonymous_union);
833 else if (!Record->isUnion())
834 Diag(Record->getLocation(), diag::ext_anonymous_struct);
835
836 // C and C++ require different kinds of checks for anonymous
837 // structs/unions.
838 bool Invalid = false;
839 if (getLangOptions().CPlusPlus) {
840 const char* PrevSpec = 0;
841 // C++ [class.union]p3:
842 // Anonymous unions declared in a named namespace or in the
843 // global namespace shall be declared static.
844 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
845 (isa<TranslationUnitDecl>(Owner) ||
846 (isa<NamespaceDecl>(Owner) &&
847 cast<NamespaceDecl>(Owner)->getDeclName()))) {
848 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
849 Invalid = true;
850
851 // Recover by adding 'static'.
852 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
853 }
854 // C++ [class.union]p3:
855 // A storage class is not allowed in a declaration of an
856 // anonymous union in a class scope.
857 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
858 isa<RecordDecl>(Owner)) {
859 Diag(DS.getStorageClassSpecLoc(),
860 diag::err_anonymous_union_with_storage_spec);
861 Invalid = true;
862
863 // Recover by removing the storage specifier.
864 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
865 PrevSpec);
866 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000867
868 // C++ [class.union]p2:
869 // The member-specification of an anonymous union shall only
870 // define non-static data members. [Note: nested types and
871 // functions cannot be declared within an anonymous union. ]
872 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
873 MemEnd = Record->decls_end();
874 Mem != MemEnd; ++Mem) {
875 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
876 // C++ [class.union]p3:
877 // An anonymous union shall not have private or protected
878 // members (clause 11).
879 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
880 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
881 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
882 Invalid = true;
883 }
884 } else if ((*Mem)->isImplicit()) {
885 // Any implicit members are fine.
886 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
887 if (!MemRecord->isAnonymousStructOrUnion() &&
888 MemRecord->getDeclName()) {
889 // This is a nested type declaration.
890 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
891 << (int)Record->isUnion();
892 Invalid = true;
893 }
894 } else {
895 // We have something that isn't a non-static data
896 // member. Complain about it.
897 unsigned DK = diag::err_anonymous_record_bad_member;
898 if (isa<TypeDecl>(*Mem))
899 DK = diag::err_anonymous_record_with_type;
900 else if (isa<FunctionDecl>(*Mem))
901 DK = diag::err_anonymous_record_with_function;
902 else if (isa<VarDecl>(*Mem))
903 DK = diag::err_anonymous_record_with_static;
904 Diag((*Mem)->getLocation(), DK)
905 << (int)Record->isUnion();
906 Invalid = true;
907 }
908 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000909 } else {
910 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000911 if (Record->isUnion() && !Owner->isRecord()) {
912 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
913 << (int)getLangOptions().CPlusPlus;
914 Invalid = true;
915 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000916 }
917
918 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000919 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
920 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000921 Invalid = true;
922 }
923
924 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000925 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000926 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
927 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
928 /*IdentifierInfo=*/0,
929 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000930 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000931 Anon->setAccess(AS_public);
932 if (getLangOptions().CPlusPlus)
933 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000934 } else {
935 VarDecl::StorageClass SC;
936 switch (DS.getStorageClassSpec()) {
937 default: assert(0 && "Unknown storage class!");
938 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
939 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
940 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
941 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
942 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
943 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
944 case DeclSpec::SCS_mutable:
945 // mutable can only appear on non-static class members, so it's always
946 // an error here
947 Diag(Record->getLocation(), diag::err_mutable_nonmember);
948 Invalid = true;
949 SC = VarDecl::None;
950 break;
951 }
952
953 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
954 /*IdentifierInfo=*/0,
955 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000956 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000957 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000958 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000959
960 // Add the anonymous struct/union object to the current
961 // context. We'll be referencing this object when we refer to one of
962 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000963 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000964
965 // Inject the members of the anonymous struct/union into the owning
966 // context and into the identifier resolver chain for name lookup
967 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000968 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
969 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000970
971 // Mark this as an anonymous struct/union type. Note that we do not
972 // do this until after we have already checked and injected the
973 // members of this anonymous struct/union type, because otherwise
974 // the members could be injected twice: once by DeclContext when it
975 // builds its lookup table, and once by
976 // InjectAnonymousStructOrUnionMembers.
977 Record->setAnonymousStructOrUnion(true);
978
979 if (Invalid)
980 Anon->setInvalidDecl();
981
982 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000983}
984
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000985bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
986 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000987 // Get the type before calling CheckSingleAssignmentConstraints(), since
988 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000989 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000990
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000991 if (getLangOptions().CPlusPlus) {
992 // FIXME: I dislike this error message. A lot.
993 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
994 return Diag(Init->getSourceRange().getBegin(),
995 diag::err_typecheck_convert_incompatible)
996 << DeclType << Init->getType() << "initializing"
997 << Init->getSourceRange();
998
999 return false;
1000 }
Douglas Gregor45920e82008-12-19 17:40:08 +00001001
Chris Lattner5cf216b2008-01-04 18:04:52 +00001002 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1003 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1004 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001005}
1006
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001007bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001008 const ArrayType *AT = Context.getAsArrayType(DeclT);
1009
1010 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001011 // C99 6.7.8p14. We have an array of character type with unknown size
1012 // being initialized to a string literal.
1013 llvm::APSInt ConstVal(32);
1014 ConstVal = strLiteral->getByteLength() + 1;
1015 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001016 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001017 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001018 } else {
1019 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001020 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001021 // FIXME: Avoid truncation for 64-bit length strings.
1022 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001023 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001024 diag::warn_initializer_string_for_char_array_too_long)
1025 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001026 }
1027 // Set type from "char *" to "constant array of char".
1028 strLiteral->setType(DeclT);
1029 // For now, we always return false (meaning success).
1030 return false;
1031}
1032
1033StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001034 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001035 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +00001036 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +00001037 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001038 return 0;
1039}
1040
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001041bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1042 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001043 DeclarationName InitEntity,
1044 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001045 if (DeclType->isDependentType() || Init->isTypeDependent())
1046 return false;
1047
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001048 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001049 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001050 // (8.3.2), shall be initialized by an object, or function, of
1051 // type T or by an object that can be converted into a T.
1052 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001053 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001054
Steve Naroffca107302008-01-21 23:53:58 +00001055 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1056 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001057 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001058 return Diag(InitLoc, diag::err_variable_object_no_init)
1059 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001060
Steve Naroff2fdc3742007-12-10 22:44:33 +00001061 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1062 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001063 // FIXME: Handle wide strings
1064 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1065 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001066
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001067 // C++ [dcl.init]p14:
1068 // -- If the destination type is a (possibly cv-qualified) class
1069 // type:
1070 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1071 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1072 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1073
1074 // -- If the initialization is direct-initialization, or if it is
1075 // copy-initialization where the cv-unqualified version of the
1076 // source type is the same class as, or a derived class of, the
1077 // class of the destination, constructors are considered.
1078 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1079 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1080 CXXConstructorDecl *Constructor
1081 = PerformInitializationByConstructor(DeclType, &Init, 1,
1082 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001083 InitEntity,
1084 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001085 return Constructor == 0;
1086 }
1087
1088 // -- Otherwise (i.e., for the remaining copy-initialization
1089 // cases), user-defined conversion sequences that can
1090 // convert from the source type to the destination type or
1091 // (when a conversion function is used) to a derived class
1092 // thereof are enumerated as described in 13.3.1.4, and the
1093 // best one is chosen through overload resolution
1094 // (13.3). If the conversion cannot be done or is
1095 // ambiguous, the initialization is ill-formed. The
1096 // function selected is called with the initializer
1097 // expression as its argument; if the function is a
1098 // constructor, the call initializes a temporary of the
1099 // destination type.
1100 // FIXME: We're pretending to do copy elision here; return to
1101 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001102 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001103 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001104
Douglas Gregor61366e92008-12-24 00:01:03 +00001105 if (InitEntity)
1106 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1107 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1108 << Init->getType() << Init->getSourceRange();
1109 else
1110 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1111 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1112 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001113 }
1114
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001115 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001116 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001117 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1118 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001119
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001120 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001121 } else if (getLangOptions().CPlusPlus) {
1122 // C++ [dcl.init]p14:
1123 // [...] If the class is an aggregate (8.5.1), and the initializer
1124 // is a brace-enclosed list, see 8.5.1.
1125 //
1126 // Note: 8.5.1 is handled below; here, we diagnose the case where
1127 // we have an initializer list and a destination type that is not
1128 // an aggregate.
1129 // FIXME: In C++0x, this is yet another form of initialization.
1130 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1131 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1132 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001133 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001134 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001135 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001136 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001137
Steve Naroff0cca7492008-05-01 22:18:59 +00001138 InitListChecker CheckInitList(this, InitList, DeclType);
1139 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001140}
1141
Douglas Gregor10bd3682008-11-17 22:58:34 +00001142/// GetNameForDeclarator - Determine the full declaration name for the
1143/// given Declarator.
1144DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1145 switch (D.getKind()) {
1146 case Declarator::DK_Abstract:
1147 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1148 return DeclarationName();
1149
1150 case Declarator::DK_Normal:
1151 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1152 return DeclarationName(D.getIdentifier());
1153
1154 case Declarator::DK_Constructor: {
1155 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1156 Ty = Context.getCanonicalType(Ty);
1157 return Context.DeclarationNames.getCXXConstructorName(Ty);
1158 }
1159
1160 case Declarator::DK_Destructor: {
1161 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1162 Ty = Context.getCanonicalType(Ty);
1163 return Context.DeclarationNames.getCXXDestructorName(Ty);
1164 }
1165
1166 case Declarator::DK_Conversion: {
1167 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1168 Ty = Context.getCanonicalType(Ty);
1169 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1170 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001171
1172 case Declarator::DK_Operator:
1173 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1174 return Context.DeclarationNames.getCXXOperatorName(
1175 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001176 }
1177
1178 assert(false && "Unknown name kind");
1179 return DeclarationName();
1180}
1181
Douglas Gregor584049d2008-12-15 23:53:10 +00001182/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1183/// functions Declaration and Definition are "nearly" matching. This
1184/// heuristic is used to improve diagnostics in the case where an
1185/// out-of-line member function definition doesn't match any
1186/// declaration within the class.
1187static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1188 FunctionDecl *Declaration,
1189 FunctionDecl *Definition) {
1190 if (Declaration->param_size() != Definition->param_size())
1191 return false;
1192 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1193 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1194 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1195
1196 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1197 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1198 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1199 return false;
1200 }
1201
1202 return true;
1203}
1204
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001205Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001206Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1207 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001208 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001209 DeclarationName Name = GetNameForDeclarator(D);
1210
Chris Lattnere80a59c2007-07-25 00:24:17 +00001211 // All of these full declarators require an identifier. If it doesn't have
1212 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001213 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001214 if (!D.getInvalidType()) // Reject this if we think it is valid.
1215 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001216 diag::err_declarator_need_ident)
1217 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001218 return 0;
1219 }
1220
Chris Lattner31e05722007-08-26 06:24:45 +00001221 // The scope passed in may not be a decl scope. Zip up the scope tree until
1222 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001223 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1224 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001225 S = S->getParent();
1226
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001227 DeclContext *DC;
1228 Decl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001229 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001230 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001231
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001232 // See if this is a redefinition of a variable in the same scope.
1233 if (!D.getCXXScopeSpec().isSet()) {
1234 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001235 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001236 } else { // Something like "int foo::x;"
1237 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001238 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001239
1240 // C++ 7.3.1.2p2:
1241 // Members (including explicit specializations of templates) of a named
1242 // namespace can also be defined outside that namespace by explicit
1243 // qualification of the name being defined, provided that the entity being
1244 // defined was already declared in the namespace and the definition appears
1245 // after the point of declaration in a namespace that encloses the
1246 // declarations namespace.
1247 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001248 // Note that we only check the context at this point. We don't yet
1249 // have enough information to make sure that PrevDecl is actually
1250 // the declaration we want to match. For example, given:
1251 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001252 // class X {
1253 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001254 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001255 // };
1256 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001257 // void X::f(int) { } // ill-formed
1258 //
1259 // In this case, PrevDecl will point to the overload set
1260 // containing the two f's declared in X, but neither of them
1261 // matches.
1262 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001263 // The qualifying scope doesn't enclose the original declaration.
1264 // Emit diagnostic based on current scope.
1265 SourceLocation L = D.getIdentifierLoc();
1266 SourceRange R = D.getCXXScopeSpec().getRange();
1267 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001268 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001269 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001270 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001271 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001272 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001273 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001274 }
1275 }
1276
Douglas Gregorf57172b2008-12-08 18:40:42 +00001277 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001278 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001279 InvalidDecl = InvalidDecl
1280 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001281 // Just pretend that we didn't see the previous declaration.
1282 PrevDecl = 0;
1283 }
1284
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001285 // In C++, the previous declaration we find might be a tag type
1286 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001287 // tag type. Note that this does does not apply if we're declaring a
1288 // typedef (C++ [dcl.typedef]p4).
1289 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1290 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001291 PrevDecl = 0;
1292
Chris Lattner41af0932007-11-14 06:34:38 +00001293 QualType R = GetTypeForDeclarator(D, S);
1294 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1295
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001297 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1298 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001299 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001300 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1301 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001303 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1304 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001306
1307 if (New == 0)
1308 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001309
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001310 // Set the lexical context. If the declarator has a C++ scope specifier, the
1311 // lexical context will be different from the semantic context.
1312 New->setLexicalDeclContext(CurContext);
1313
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001315 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001316 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001317 // If any semantic error occurred, mark the decl as invalid.
1318 if (D.getInvalidType() || InvalidDecl)
1319 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001320
1321 return New;
1322}
1323
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001324NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001325Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001326 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001327 Decl* PrevDecl, bool& InvalidDecl) {
1328 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1329 if (D.getCXXScopeSpec().isSet()) {
1330 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1331 << D.getCXXScopeSpec().getRange();
1332 InvalidDecl = true;
1333 // Pretend we didn't see the scope specifier.
1334 DC = 0;
1335 }
1336
1337 // Check that there are no default arguments (C++ only).
1338 if (getLangOptions().CPlusPlus)
1339 CheckExtraCXXDefaultArguments(D);
1340
1341 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1342 if (!NewTD) return 0;
1343
1344 // Handle attributes prior to checking for duplicates in MergeVarDecl
1345 ProcessDeclAttributes(NewTD, D);
1346 // Merge the decl with the existing one if appropriate. If the decl is
1347 // in an outer scope, it isn't the same thing.
1348 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1349 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1350 if (NewTD == 0) return 0;
1351 }
1352
1353 if (S->getFnParent() == 0) {
1354 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1355 // then it shall have block scope.
1356 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1357 if (NewTD->getUnderlyingType()->isVariableArrayType())
1358 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1359 else
1360 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1361
1362 InvalidDecl = true;
1363 }
1364 }
1365 return NewTD;
1366}
1367
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001368NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001369Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001370 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001371 Decl* PrevDecl, bool& InvalidDecl) {
1372 DeclarationName Name = GetNameForDeclarator(D);
1373
1374 // Check that there are no default arguments (C++ only).
1375 if (getLangOptions().CPlusPlus)
1376 CheckExtraCXXDefaultArguments(D);
1377
1378 if (R.getTypePtr()->isObjCInterfaceType()) {
1379 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1380 << D.getIdentifier();
1381 InvalidDecl = true;
1382 }
1383
1384 VarDecl *NewVD;
1385 VarDecl::StorageClass SC;
1386 switch (D.getDeclSpec().getStorageClassSpec()) {
1387 default: assert(0 && "Unknown storage class!");
1388 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1389 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1390 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1391 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1392 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1393 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1394 case DeclSpec::SCS_mutable:
1395 // mutable can only appear on non-static class members, so it's always
1396 // an error here
1397 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1398 InvalidDecl = true;
1399 SC = VarDecl::None;
1400 break;
1401 }
1402
1403 IdentifierInfo *II = Name.getAsIdentifierInfo();
1404 if (!II) {
1405 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1406 << Name.getAsString();
1407 return 0;
1408 }
1409
1410 if (DC->isRecord()) {
1411 // This is a static data member for a C++ class.
1412 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1413 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001414 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001415 } else {
1416 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1417 if (S->getFnParent() == 0) {
1418 // C99 6.9p2: The storage-class specifiers auto and register shall not
1419 // appear in the declaration specifiers in an external declaration.
1420 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1421 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1422 InvalidDecl = true;
1423 }
1424 }
1425 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001426 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001427 // FIXME: Move to DeclGroup...
1428 D.getDeclSpec().getSourceRange().getBegin());
1429 NewVD->setThreadSpecified(ThreadSpecified);
1430 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001431 NewVD->setNextDeclarator(LastDeclarator);
1432
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001433 // Handle attributes prior to checking for duplicates in MergeVarDecl
1434 ProcessDeclAttributes(NewVD, D);
1435
1436 // Handle GNU asm-label extension (encoded as an attribute).
1437 if (Expr *E = (Expr*) D.getAsmLabel()) {
1438 // The parser guarantees this is a string.
1439 StringLiteral *SE = cast<StringLiteral>(E);
1440 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1441 SE->getByteLength())));
1442 }
1443
1444 // Emit an error if an address space was applied to decl with local storage.
1445 // This includes arrays of objects with address space qualifiers, but not
1446 // automatic variables that point to other address spaces.
1447 // ISO/IEC TR 18037 S5.1.2
1448 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1449 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1450 InvalidDecl = true;
1451 }
1452 // Merge the decl with the existing one if appropriate. If the decl is
1453 // in an outer scope, it isn't the same thing.
1454 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1455 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1456 // The user tried to define a non-static data member
1457 // out-of-line (C++ [dcl.meaning]p1).
1458 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1459 << D.getCXXScopeSpec().getRange();
1460 NewVD->Destroy(Context);
1461 return 0;
1462 }
1463
1464 NewVD = MergeVarDecl(NewVD, PrevDecl);
1465 if (NewVD == 0) return 0;
1466
1467 if (D.getCXXScopeSpec().isSet()) {
1468 // No previous declaration in the qualifying scope.
1469 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1470 << Name << D.getCXXScopeSpec().getRange();
1471 InvalidDecl = true;
1472 }
1473 }
1474 return NewVD;
1475}
1476
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001477NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001478Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001479 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001480 Decl* PrevDecl, bool IsFunctionDefinition,
1481 bool& InvalidDecl) {
1482 assert(R.getTypePtr()->isFunctionType());
1483
1484 DeclarationName Name = GetNameForDeclarator(D);
1485 FunctionDecl::StorageClass SC = FunctionDecl::None;
1486 switch (D.getDeclSpec().getStorageClassSpec()) {
1487 default: assert(0 && "Unknown storage class!");
1488 case DeclSpec::SCS_auto:
1489 case DeclSpec::SCS_register:
1490 case DeclSpec::SCS_mutable:
1491 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1492 InvalidDecl = true;
1493 break;
1494 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1495 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1496 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1497 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1498 }
1499
1500 bool isInline = D.getDeclSpec().isInlineSpecified();
1501 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1502 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1503
1504 FunctionDecl *NewFD;
1505 if (D.getKind() == Declarator::DK_Constructor) {
1506 // This is a C++ constructor declaration.
1507 assert(DC->isRecord() &&
1508 "Constructors can only be declared in a member context");
1509
1510 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1511
1512 // Create the new declaration
1513 NewFD = CXXConstructorDecl::Create(Context,
1514 cast<CXXRecordDecl>(DC),
1515 D.getIdentifierLoc(), Name, R,
1516 isExplicit, isInline,
1517 /*isImplicitlyDeclared=*/false);
1518
1519 if (InvalidDecl)
1520 NewFD->setInvalidDecl();
1521 } else if (D.getKind() == Declarator::DK_Destructor) {
1522 // This is a C++ destructor declaration.
1523 if (DC->isRecord()) {
1524 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1525
1526 NewFD = CXXDestructorDecl::Create(Context,
1527 cast<CXXRecordDecl>(DC),
1528 D.getIdentifierLoc(), Name, R,
1529 isInline,
1530 /*isImplicitlyDeclared=*/false);
1531
1532 if (InvalidDecl)
1533 NewFD->setInvalidDecl();
1534 } else {
1535 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1536
1537 // Create a FunctionDecl to satisfy the function definition parsing
1538 // code path.
1539 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001540 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001541 // FIXME: Move to DeclGroup...
1542 D.getDeclSpec().getSourceRange().getBegin());
1543 InvalidDecl = true;
1544 NewFD->setInvalidDecl();
1545 }
1546 } else if (D.getKind() == Declarator::DK_Conversion) {
1547 if (!DC->isRecord()) {
1548 Diag(D.getIdentifierLoc(),
1549 diag::err_conv_function_not_member);
1550 return 0;
1551 } else {
1552 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1553
1554 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1555 D.getIdentifierLoc(), Name, R,
1556 isInline, isExplicit);
1557
1558 if (InvalidDecl)
1559 NewFD->setInvalidDecl();
1560 }
1561 } else if (DC->isRecord()) {
1562 // This is a C++ method declaration.
1563 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1564 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001565 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001566 } else {
1567 NewFD = FunctionDecl::Create(Context, DC,
1568 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001569 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001570 // FIXME: Move to DeclGroup...
1571 D.getDeclSpec().getSourceRange().getBegin());
1572 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001573 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001574
1575 // Set the lexical context. If the declarator has a C++
1576 // scope specifier, the lexical context will be different
1577 // from the semantic context.
1578 NewFD->setLexicalDeclContext(CurContext);
1579
1580 // Handle GNU asm-label extension (encoded as an attribute).
1581 if (Expr *E = (Expr*) D.getAsmLabel()) {
1582 // The parser guarantees this is a string.
1583 StringLiteral *SE = cast<StringLiteral>(E);
1584 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1585 SE->getByteLength())));
1586 }
1587
1588 // Copy the parameter declarations from the declarator D to
1589 // the function declaration NewFD, if they are available.
1590 if (D.getNumTypeObjects() > 0) {
1591 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1592
1593 // Create Decl objects for each parameter, adding them to the
1594 // FunctionDecl.
1595 llvm::SmallVector<ParmVarDecl*, 16> Params;
1596
1597 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1598 // function that takes no arguments, not a function that takes a
1599 // single void argument.
1600 // We let through "const void" here because Sema::GetTypeForDeclarator
1601 // already checks for that case.
1602 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1603 FTI.ArgInfo[0].Param &&
1604 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1605 // empty arg list, don't push any params.
1606 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1607
1608 // In C++, the empty parameter-type-list must be spelled "void"; a
1609 // typedef of void is not permitted.
1610 if (getLangOptions().CPlusPlus &&
1611 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1612 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1613 }
1614 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1615 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1616 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1617 }
1618
1619 NewFD->setParams(Context, &Params[0], Params.size());
1620 } else if (R->getAsTypedefType()) {
1621 // When we're declaring a function with a typedef, as in the
1622 // following example, we'll need to synthesize (unnamed)
1623 // parameters for use in the declaration.
1624 //
1625 // @code
1626 // typedef void fn(int);
1627 // fn f;
1628 // @endcode
1629 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1630 if (!FT) {
1631 // This is a typedef of a function with no prototype, so we
1632 // don't need to do anything.
1633 } else if ((FT->getNumArgs() == 0) ||
1634 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1635 FT->getArgType(0)->isVoidType())) {
1636 // This is a zero-argument function. We don't need to do anything.
1637 } else {
1638 // Synthesize a parameter for each argument type.
1639 llvm::SmallVector<ParmVarDecl*, 16> Params;
1640 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1641 ArgType != FT->arg_type_end(); ++ArgType) {
1642 Params.push_back(ParmVarDecl::Create(Context, DC,
1643 SourceLocation(), 0,
1644 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001645 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001646 }
1647
1648 NewFD->setParams(Context, &Params[0], Params.size());
1649 }
1650 }
1651
1652 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1653 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1654 else if (isa<CXXDestructorDecl>(NewFD)) {
1655 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1656 Record->setUserDeclaredDestructor(true);
1657 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1658 // user-defined destructor.
1659 Record->setPOD(false);
1660 } else if (CXXConversionDecl *Conversion =
1661 dyn_cast<CXXConversionDecl>(NewFD))
1662 ActOnConversionDeclarator(Conversion);
1663
1664 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1665 if (NewFD->isOverloadedOperator() &&
1666 CheckOverloadedOperatorDeclaration(NewFD))
1667 NewFD->setInvalidDecl();
1668
1669 // Merge the decl with the existing one if appropriate. Since C functions
1670 // are in a flat namespace, make sure we consider decls in outer scopes.
1671 if (PrevDecl &&
1672 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1673 bool Redeclaration = false;
1674
1675 // If C++, determine whether NewFD is an overload of PrevDecl or
1676 // a declaration that requires merging. If it's an overload,
1677 // there's no more work to do here; we'll just add the new
1678 // function to the scope.
1679 OverloadedFunctionDecl::function_iterator MatchedDecl;
1680 if (!getLangOptions().CPlusPlus ||
1681 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1682 Decl *OldDecl = PrevDecl;
1683
1684 // If PrevDecl was an overloaded function, extract the
1685 // FunctionDecl that matched.
1686 if (isa<OverloadedFunctionDecl>(PrevDecl))
1687 OldDecl = *MatchedDecl;
1688
1689 // NewFD and PrevDecl represent declarations that need to be
1690 // merged.
1691 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1692
1693 if (NewFD == 0) return 0;
1694 if (Redeclaration) {
1695 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1696
1697 // An out-of-line member function declaration must also be a
1698 // definition (C++ [dcl.meaning]p1).
1699 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1700 !InvalidDecl) {
1701 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1702 << D.getCXXScopeSpec().getRange();
1703 NewFD->setInvalidDecl();
1704 }
1705 }
1706 }
1707
1708 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1709 // The user tried to provide an out-of-line definition for a
1710 // member function, but there was no such member function
1711 // declared (C++ [class.mfct]p2). For example:
1712 //
1713 // class X {
1714 // void f() const;
1715 // };
1716 //
1717 // void X::f() { } // ill-formed
1718 //
1719 // Complain about this problem, and attempt to suggest close
1720 // matches (e.g., those that differ only in cv-qualifiers and
1721 // whether the parameter types are references).
1722 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1723 << cast<CXXRecordDecl>(DC)->getDeclName()
1724 << D.getCXXScopeSpec().getRange();
1725 InvalidDecl = true;
1726
1727 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1728 if (!PrevDecl) {
1729 // Nothing to suggest.
1730 } else if (OverloadedFunctionDecl *Ovl
1731 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1732 for (OverloadedFunctionDecl::function_iterator
1733 Func = Ovl->function_begin(),
1734 FuncEnd = Ovl->function_end();
1735 Func != FuncEnd; ++Func) {
1736 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1737 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1738
1739 }
1740 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1741 // Suggest this no matter how mismatched it is; it's the only
1742 // thing we have.
1743 unsigned diag;
1744 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1745 diag = diag::note_member_def_close_match;
1746 else if (Method->getBody())
1747 diag = diag::note_previous_definition;
1748 else
1749 diag = diag::note_previous_declaration;
1750 Diag(Method->getLocation(), diag);
1751 }
1752
1753 PrevDecl = 0;
1754 }
1755 }
1756 // Handle attributes. We need to have merged decls when handling attributes
1757 // (for example to check for conflicts, etc).
1758 ProcessDeclAttributes(NewFD, D);
1759
1760 if (getLangOptions().CPlusPlus) {
1761 // In C++, check default arguments now that we have merged decls.
1762 CheckCXXDefaultArguments(NewFD);
1763
1764 // An out-of-line member function declaration must also be a
1765 // definition (C++ [dcl.meaning]p1).
1766 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1767 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1768 << D.getCXXScopeSpec().getRange();
1769 InvalidDecl = true;
1770 }
1771 }
1772 return NewFD;
1773}
1774
Steve Naroff6594a702008-10-27 11:34:16 +00001775void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001776 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1777 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001778}
1779
Eli Friedmanc594b322008-05-20 13:48:25 +00001780bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1781 switch (Init->getStmtClass()) {
1782 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001783 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001784 return true;
1785 case Expr::ParenExprClass: {
1786 const ParenExpr* PE = cast<ParenExpr>(Init);
1787 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1788 }
1789 case Expr::CompoundLiteralExprClass:
1790 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001791 case Expr::DeclRefExprClass:
1792 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001793 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001794 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1795 if (VD->hasGlobalStorage())
1796 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001797 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001798 return true;
1799 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001800 if (isa<FunctionDecl>(D))
1801 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001802 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001803 return true;
1804 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001805 case Expr::MemberExprClass: {
1806 const MemberExpr *M = cast<MemberExpr>(Init);
1807 if (M->isArrow())
1808 return CheckAddressConstantExpression(M->getBase());
1809 return CheckAddressConstantExpressionLValue(M->getBase());
1810 }
1811 case Expr::ArraySubscriptExprClass: {
1812 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1813 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1814 return CheckAddressConstantExpression(ASE->getBase()) ||
1815 CheckArithmeticConstantExpression(ASE->getIdx());
1816 }
1817 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001818 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001819 return false;
1820 case Expr::UnaryOperatorClass: {
1821 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1822
1823 // C99 6.6p9
1824 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001825 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001826
Steve Naroff6594a702008-10-27 11:34:16 +00001827 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001828 return true;
1829 }
1830 }
1831}
1832
1833bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1834 switch (Init->getStmtClass()) {
1835 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001836 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001837 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001838 case Expr::ParenExprClass:
1839 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001840 case Expr::StringLiteralClass:
1841 case Expr::ObjCStringLiteralClass:
1842 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001843 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001844 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001845 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1846 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1847 Builtin::BI__builtin___CFStringMakeConstantString)
1848 return false;
1849
Steve Naroff6594a702008-10-27 11:34:16 +00001850 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001851 return true;
1852
Eli Friedmanc594b322008-05-20 13:48:25 +00001853 case Expr::UnaryOperatorClass: {
1854 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1855
1856 // C99 6.6p9
1857 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1858 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1859
1860 if (Exp->getOpcode() == UnaryOperator::Extension)
1861 return CheckAddressConstantExpression(Exp->getSubExpr());
1862
Steve Naroff6594a702008-10-27 11:34:16 +00001863 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001864 return true;
1865 }
1866 case Expr::BinaryOperatorClass: {
1867 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1868 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1869
1870 Expr *PExp = Exp->getLHS();
1871 Expr *IExp = Exp->getRHS();
1872 if (IExp->getType()->isPointerType())
1873 std::swap(PExp, IExp);
1874
1875 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1876 return CheckAddressConstantExpression(PExp) ||
1877 CheckArithmeticConstantExpression(IExp);
1878 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001879 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001880 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001881 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001882 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1883 // Check for implicit promotion
1884 if (SubExpr->getType()->isFunctionType() ||
1885 SubExpr->getType()->isArrayType())
1886 return CheckAddressConstantExpressionLValue(SubExpr);
1887 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001888
1889 // Check for pointer->pointer cast
1890 if (SubExpr->getType()->isPointerType())
1891 return CheckAddressConstantExpression(SubExpr);
1892
Eli Friedmanc3f07642008-08-25 20:46:57 +00001893 if (SubExpr->getType()->isIntegralType()) {
1894 // Check for the special-case of a pointer->int->pointer cast;
1895 // this isn't standard, but some code requires it. See
1896 // PR2720 for an example.
1897 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1898 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1899 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1900 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1901 if (IntWidth >= PointerWidth) {
1902 return CheckAddressConstantExpression(SubCast->getSubExpr());
1903 }
1904 }
1905 }
1906 }
1907 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001908 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001909 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001910
Steve Naroff6594a702008-10-27 11:34:16 +00001911 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001912 return true;
1913 }
1914 case Expr::ConditionalOperatorClass: {
1915 // FIXME: Should we pedwarn here?
1916 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1917 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001918 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001919 return true;
1920 }
1921 if (CheckArithmeticConstantExpression(Exp->getCond()))
1922 return true;
1923 if (Exp->getLHS() &&
1924 CheckAddressConstantExpression(Exp->getLHS()))
1925 return true;
1926 return CheckAddressConstantExpression(Exp->getRHS());
1927 }
1928 case Expr::AddrLabelExprClass:
1929 return false;
1930 }
1931}
1932
Eli Friedman4caf0552008-06-09 05:05:07 +00001933static const Expr* FindExpressionBaseAddress(const Expr* E);
1934
1935static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1936 switch (E->getStmtClass()) {
1937 default:
1938 return E;
1939 case Expr::ParenExprClass: {
1940 const ParenExpr* PE = cast<ParenExpr>(E);
1941 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1942 }
1943 case Expr::MemberExprClass: {
1944 const MemberExpr *M = cast<MemberExpr>(E);
1945 if (M->isArrow())
1946 return FindExpressionBaseAddress(M->getBase());
1947 return FindExpressionBaseAddressLValue(M->getBase());
1948 }
1949 case Expr::ArraySubscriptExprClass: {
1950 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1951 return FindExpressionBaseAddress(ASE->getBase());
1952 }
1953 case Expr::UnaryOperatorClass: {
1954 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1955
1956 if (Exp->getOpcode() == UnaryOperator::Deref)
1957 return FindExpressionBaseAddress(Exp->getSubExpr());
1958
1959 return E;
1960 }
1961 }
1962}
1963
1964static const Expr* FindExpressionBaseAddress(const Expr* E) {
1965 switch (E->getStmtClass()) {
1966 default:
1967 return E;
1968 case Expr::ParenExprClass: {
1969 const ParenExpr* PE = cast<ParenExpr>(E);
1970 return FindExpressionBaseAddress(PE->getSubExpr());
1971 }
1972 case Expr::UnaryOperatorClass: {
1973 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1974
1975 // C99 6.6p9
1976 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1977 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1978
1979 if (Exp->getOpcode() == UnaryOperator::Extension)
1980 return FindExpressionBaseAddress(Exp->getSubExpr());
1981
1982 return E;
1983 }
1984 case Expr::BinaryOperatorClass: {
1985 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1986
1987 Expr *PExp = Exp->getLHS();
1988 Expr *IExp = Exp->getRHS();
1989 if (IExp->getType()->isPointerType())
1990 std::swap(PExp, IExp);
1991
1992 return FindExpressionBaseAddress(PExp);
1993 }
1994 case Expr::ImplicitCastExprClass: {
1995 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1996
1997 // Check for implicit promotion
1998 if (SubExpr->getType()->isFunctionType() ||
1999 SubExpr->getType()->isArrayType())
2000 return FindExpressionBaseAddressLValue(SubExpr);
2001
2002 // Check for pointer->pointer cast
2003 if (SubExpr->getType()->isPointerType())
2004 return FindExpressionBaseAddress(SubExpr);
2005
2006 // We assume that we have an arithmetic expression here;
2007 // if we don't, we'll figure it out later
2008 return 0;
2009 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002010 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002011 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2012
2013 // Check for pointer->pointer cast
2014 if (SubExpr->getType()->isPointerType())
2015 return FindExpressionBaseAddress(SubExpr);
2016
2017 // We assume that we have an arithmetic expression here;
2018 // if we don't, we'll figure it out later
2019 return 0;
2020 }
2021 }
2022}
2023
Anders Carlsson51fe9962008-11-22 21:04:56 +00002024bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002025 switch (Init->getStmtClass()) {
2026 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002027 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002028 return true;
2029 case Expr::ParenExprClass: {
2030 const ParenExpr* PE = cast<ParenExpr>(Init);
2031 return CheckArithmeticConstantExpression(PE->getSubExpr());
2032 }
2033 case Expr::FloatingLiteralClass:
2034 case Expr::IntegerLiteralClass:
2035 case Expr::CharacterLiteralClass:
2036 case Expr::ImaginaryLiteralClass:
2037 case Expr::TypesCompatibleExprClass:
2038 case Expr::CXXBoolLiteralExprClass:
2039 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002040 case Expr::CallExprClass:
2041 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002042 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002043
2044 // Allow any constant foldable calls to builtins.
2045 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002046 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002047
Steve Naroff6594a702008-10-27 11:34:16 +00002048 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002049 return true;
2050 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002051 case Expr::DeclRefExprClass:
2052 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002053 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2054 if (isa<EnumConstantDecl>(D))
2055 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002056 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002057 return true;
2058 }
2059 case Expr::CompoundLiteralExprClass:
2060 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2061 // but vectors are allowed to be magic.
2062 if (Init->getType()->isVectorType())
2063 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002064 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002065 return true;
2066 case Expr::UnaryOperatorClass: {
2067 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2068
2069 switch (Exp->getOpcode()) {
2070 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2071 // See C99 6.6p3.
2072 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002073 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002074 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002075 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002076 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2077 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002078 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002079 return true;
2080 case UnaryOperator::Extension:
2081 case UnaryOperator::LNot:
2082 case UnaryOperator::Plus:
2083 case UnaryOperator::Minus:
2084 case UnaryOperator::Not:
2085 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2086 }
2087 }
Sebastian Redl05189992008-11-11 17:56:53 +00002088 case Expr::SizeOfAlignOfExprClass: {
2089 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002090 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002091 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002092 return false;
2093 // alignof always evaluates to a constant.
2094 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002095 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002096 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002097 return true;
2098 }
2099 return false;
2100 }
2101 case Expr::BinaryOperatorClass: {
2102 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2103
2104 if (Exp->getLHS()->getType()->isArithmeticType() &&
2105 Exp->getRHS()->getType()->isArithmeticType()) {
2106 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2107 CheckArithmeticConstantExpression(Exp->getRHS());
2108 }
2109
Eli Friedman4caf0552008-06-09 05:05:07 +00002110 if (Exp->getLHS()->getType()->isPointerType() &&
2111 Exp->getRHS()->getType()->isPointerType()) {
2112 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2113 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2114
2115 // Only allow a null (constant integer) base; we could
2116 // allow some additional cases if necessary, but this
2117 // is sufficient to cover offsetof-like constructs.
2118 if (!LHSBase && !RHSBase) {
2119 return CheckAddressConstantExpression(Exp->getLHS()) ||
2120 CheckAddressConstantExpression(Exp->getRHS());
2121 }
2122 }
2123
Steve Naroff6594a702008-10-27 11:34:16 +00002124 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002125 return true;
2126 }
2127 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002128 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002129 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002130 if (SubExpr->getType()->isArithmeticType())
2131 return CheckArithmeticConstantExpression(SubExpr);
2132
Eli Friedmanb529d832008-09-02 09:37:00 +00002133 if (SubExpr->getType()->isPointerType()) {
2134 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2135 // If the pointer has a null base, this is an offsetof-like construct
2136 if (!Base)
2137 return CheckAddressConstantExpression(SubExpr);
2138 }
2139
Steve Naroff6594a702008-10-27 11:34:16 +00002140 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002141 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002142 }
2143 case Expr::ConditionalOperatorClass: {
2144 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002145
2146 // If GNU extensions are disabled, we require all operands to be arithmetic
2147 // constant expressions.
2148 if (getLangOptions().NoExtensions) {
2149 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2150 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2151 CheckArithmeticConstantExpression(Exp->getRHS());
2152 }
2153
2154 // Otherwise, we have to emulate some of the behavior of fold here.
2155 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2156 // because it can constant fold things away. To retain compatibility with
2157 // GCC code, we see if we can fold the condition to a constant (which we
2158 // should always be able to do in theory). If so, we only require the
2159 // specified arm of the conditional to be a constant. This is a horrible
2160 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002161 Expr::EvalResult EvalResult;
2162 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2163 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002164 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002165 // won't be able to either. Use it to emit the diagnostic though.
2166 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002167 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002168 return Res;
2169 }
2170
2171 // Verify that the side following the condition is also a constant.
2172 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002173 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002174 std::swap(TrueSide, FalseSide);
2175
2176 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002177 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002178
2179 // Okay, the evaluated side evaluates to a constant, so we accept this.
2180 // Check to see if the other side is obviously not a constant. If so,
2181 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002182 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002183 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002184 diag::ext_typecheck_expression_not_constant_but_accepted)
2185 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002186 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002187 }
2188 }
2189}
2190
2191bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002192 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2193 Init = DIE->getInit();
2194
Nuno Lopes9a979c32008-07-07 16:46:50 +00002195 Init = Init->IgnoreParens();
2196
Nate Begeman59b5da62009-01-18 03:20:47 +00002197 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002198 return false;
2199
Eli Friedmanc594b322008-05-20 13:48:25 +00002200 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2201 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2202 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2203
Nuno Lopes9a979c32008-07-07 16:46:50 +00002204 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2205 return CheckForConstantInitializer(e->getInitializer(), DclT);
2206
Eli Friedmanc594b322008-05-20 13:48:25 +00002207 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2208 unsigned numInits = Exp->getNumInits();
2209 for (unsigned i = 0; i < numInits; i++) {
2210 // FIXME: Need to get the type of the declaration for C++,
2211 // because it could be a reference?
2212 if (CheckForConstantInitializer(Exp->getInit(i),
2213 Exp->getInit(i)->getType()))
2214 return true;
2215 }
2216 return false;
2217 }
2218
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002219 // FIXME: We can probably remove some of this code below, now that
2220 // Expr::Evaluate is doing the heavy lifting for scalars.
2221
Eli Friedmanc594b322008-05-20 13:48:25 +00002222 if (Init->isNullPointerConstant(Context))
2223 return false;
2224 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002225 QualType InitTy = Context.getCanonicalType(Init->getType())
2226 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002227 if (InitTy == Context.BoolTy) {
2228 // Special handling for pointers implicitly cast to bool;
2229 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2230 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2231 Expr* SubE = ICE->getSubExpr();
2232 if (SubE->getType()->isPointerType() ||
2233 SubE->getType()->isArrayType() ||
2234 SubE->getType()->isFunctionType()) {
2235 return CheckAddressConstantExpression(Init);
2236 }
2237 }
2238 } else if (InitTy->isIntegralType()) {
2239 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002240 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002241 SubE = CE->getSubExpr();
2242 // Special check for pointer cast to int; we allow as an extension
2243 // an address constant cast to an integer if the integer
2244 // is of an appropriate width (this sort of code is apparently used
2245 // in some places).
2246 // FIXME: Add pedwarn?
2247 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2248 if (SubE && (SubE->getType()->isPointerType() ||
2249 SubE->getType()->isArrayType() ||
2250 SubE->getType()->isFunctionType())) {
2251 unsigned IntWidth = Context.getTypeSize(Init->getType());
2252 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2253 if (IntWidth >= PointerWidth)
2254 return CheckAddressConstantExpression(Init);
2255 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002256 }
2257
2258 return CheckArithmeticConstantExpression(Init);
2259 }
2260
2261 if (Init->getType()->isPointerType())
2262 return CheckAddressConstantExpression(Init);
2263
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002264 // An array type at the top level that isn't an init-list must
2265 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002266 if (Init->getType()->isArrayType())
2267 return false;
2268
Nuno Lopes73419bf2008-09-01 18:42:41 +00002269 if (Init->getType()->isFunctionType())
2270 return false;
2271
Steve Naroff8af6a452008-10-02 17:12:56 +00002272 // Allow block exprs at top level.
2273 if (Init->getType()->isBlockPointerType())
2274 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002275
2276 // GCC cast to union extension
2277 // note: the validity of the cast expr is checked by CheckCastTypes()
2278 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2279 QualType T = C->getType();
2280 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2281 }
2282
Steve Naroff6594a702008-10-27 11:34:16 +00002283 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002284 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002285}
2286
Sebastian Redl798d1192008-12-13 16:23:55 +00002287void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002288 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2289}
2290
2291/// AddInitializerToDecl - Adds the initializer Init to the
2292/// declaration dcl. If DirectInit is true, this is C++ direct
2293/// initialization rather than copy initialization.
2294void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002295 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002296 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002297 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002298
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002299 // If there is no declaration, there was an error parsing it. Just ignore
2300 // the initializer.
2301 if (RealDecl == 0) {
2302 delete Init;
2303 return;
2304 }
Steve Naroffbb204692007-09-12 14:07:44 +00002305
Steve Naroff410e3e22007-09-12 20:13:48 +00002306 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2307 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002308 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002309 RealDecl->setInvalidDecl();
2310 return;
2311 }
Steve Naroffbb204692007-09-12 14:07:44 +00002312 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002313 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002314 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002315 if (VDecl->isBlockVarDecl()) {
2316 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002317 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002318 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002319 VDecl->setInvalidDecl();
2320 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002321 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002322 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002323 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002324
2325 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2326 if (!getLangOptions().CPlusPlus) {
2327 if (SC == VarDecl::Static) // C99 6.7.8p4.
2328 CheckForConstantInitializer(Init, DclT);
2329 }
Steve Naroffbb204692007-09-12 14:07:44 +00002330 }
Steve Naroff248a7532008-04-15 22:42:06 +00002331 } else if (VDecl->isFileVarDecl()) {
2332 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002333 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002334 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002335 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002336 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002337 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002338
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002339 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2340 if (!getLangOptions().CPlusPlus) {
2341 // C99 6.7.8p4. All file scoped initializers need to be constant.
2342 CheckForConstantInitializer(Init, DclT);
2343 }
Steve Naroffbb204692007-09-12 14:07:44 +00002344 }
2345 // If the type changed, it means we had an incomplete type that was
2346 // completed by the initializer. For example:
2347 // int ary[] = { 1, 3, 5 };
2348 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002349 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002350 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002351 Init->setType(DclT);
2352 }
Steve Naroffbb204692007-09-12 14:07:44 +00002353
2354 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002355 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002356 return;
2357}
2358
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002359void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2360 Decl *RealDecl = static_cast<Decl *>(dcl);
2361
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002362 // If there is no declaration, there was an error parsing it. Just ignore it.
2363 if (RealDecl == 0)
2364 return;
2365
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002366 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2367 QualType Type = Var->getType();
2368 // C++ [dcl.init.ref]p3:
2369 // The initializer can be omitted for a reference only in a
2370 // parameter declaration (8.3.5), in the declaration of a
2371 // function return type, in the declaration of a class member
2372 // within its class declaration (9.2), and where the extern
2373 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002374 if (Type->isReferenceType() &&
2375 Var->getStorageClass() != VarDecl::Extern &&
2376 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002377 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002378 << Var->getDeclName()
2379 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002380 Var->setInvalidDecl();
2381 return;
2382 }
2383
2384 // C++ [dcl.init]p9:
2385 //
2386 // If no initializer is specified for an object, and the object
2387 // is of (possibly cv-qualified) non-POD class type (or array
2388 // thereof), the object shall be default-initialized; if the
2389 // object is of const-qualified type, the underlying class type
2390 // shall have a user-declared default constructor.
2391 if (getLangOptions().CPlusPlus) {
2392 QualType InitType = Type;
2393 if (const ArrayType *Array = Context.getAsArrayType(Type))
2394 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002395 if (Var->getStorageClass() != VarDecl::Extern &&
2396 Var->getStorageClass() != VarDecl::PrivateExtern &&
2397 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002398 const CXXConstructorDecl *Constructor
2399 = PerformInitializationByConstructor(InitType, 0, 0,
2400 Var->getLocation(),
2401 SourceRange(Var->getLocation(),
2402 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002403 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002404 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002405 if (!Constructor)
2406 Var->setInvalidDecl();
2407 }
2408 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002409
Douglas Gregor818ce482008-10-29 13:50:18 +00002410#if 0
2411 // FIXME: Temporarily disabled because we are not properly parsing
2412 // linkage specifications on declarations, e.g.,
2413 //
2414 // extern "C" const CGPoint CGPointerZero;
2415 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002416 // C++ [dcl.init]p9:
2417 //
2418 // If no initializer is specified for an object, and the
2419 // object is of (possibly cv-qualified) non-POD class type (or
2420 // array thereof), the object shall be default-initialized; if
2421 // the object is of const-qualified type, the underlying class
2422 // type shall have a user-declared default
2423 // constructor. Otherwise, if no initializer is specified for
2424 // an object, the object and its subobjects, if any, have an
2425 // indeterminate initial value; if the object or any of its
2426 // subobjects are of const-qualified type, the program is
2427 // ill-formed.
2428 //
2429 // This isn't technically an error in C, so we don't diagnose it.
2430 //
2431 // FIXME: Actually perform the POD/user-defined default
2432 // constructor check.
2433 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002434 Context.getCanonicalType(Type).isConstQualified() &&
2435 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002436 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2437 << Var->getName()
2438 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002439#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002440 }
2441}
2442
Reid Spencer5f016e22007-07-11 17:01:13 +00002443/// The declarators are chained together backwards, reverse the list.
2444Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2445 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002446 Decl *GroupDecl = static_cast<Decl*>(group);
2447 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002448 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002449
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002450 Decl *Group = dyn_cast<Decl>(GroupDecl);
2451 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002452 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002453 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002454 else { // reverse the list.
2455 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002456 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002457 Group->setNextDeclarator(NewGroup);
2458 NewGroup = Group;
2459 Group = Next;
2460 }
2461 }
2462 // Perform semantic analysis that depends on having fully processed both
2463 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002464 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002465 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2466 if (!IDecl)
2467 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002468 QualType T = IDecl->getType();
2469
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002470 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002471 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002472
2473 // FIXME: This won't give the correct result for
2474 // int a[10][n];
2475 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002476 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002477 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2478 SizeRange;
2479
Eli Friedmanc5773c42008-02-15 18:16:39 +00002480 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002481 } else {
2482 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2483 // static storage duration, it shall not have a variable length array.
2484 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002485 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2486 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002487 IDecl->setInvalidDecl();
2488 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002489 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2490 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002491 IDecl->setInvalidDecl();
2492 }
2493 }
2494 } else if (T->isVariablyModifiedType()) {
2495 if (IDecl->isFileVarDecl()) {
2496 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2497 IDecl->setInvalidDecl();
2498 } else {
2499 if (IDecl->getStorageClass() == VarDecl::Extern) {
2500 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2501 IDecl->setInvalidDecl();
2502 }
Steve Naroffbb204692007-09-12 14:07:44 +00002503 }
2504 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002505
Steve Naroffbb204692007-09-12 14:07:44 +00002506 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2507 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002508 if (IDecl->isBlockVarDecl() &&
2509 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002510 if (!IDecl->isInvalidDecl() &&
2511 DiagnoseIncompleteType(IDecl->getLocation(), T,
2512 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002513 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002514 }
2515 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2516 // object that has file scope without an initializer, and without a
2517 // storage-class specifier or with the storage-class specifier "static",
2518 // constitutes a tentative definition. Note: A tentative definition with
2519 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002520 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002521 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002522 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2523 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002524 } else if (!IDecl->isInvalidDecl() &&
2525 DiagnoseIncompleteType(IDecl->getLocation(), T,
2526 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002527 // C99 6.9.2p3: If the declaration of an identifier for an object is
2528 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2529 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002530 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002531 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002532 if (IDecl->isFileVarDecl())
2533 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 }
2535 return NewGroup;
2536}
Steve Naroffe1223f72007-08-28 03:03:08 +00002537
Chris Lattner04421082008-04-08 04:40:51 +00002538/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2539/// to introduce parameters into function prototype scope.
2540Sema::DeclTy *
2541Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002542 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002543
Chris Lattner04421082008-04-08 04:40:51 +00002544 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002545 VarDecl::StorageClass StorageClass = VarDecl::None;
2546 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2547 StorageClass = VarDecl::Register;
2548 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002549 Diag(DS.getStorageClassSpecLoc(),
2550 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002551 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002552 }
2553 if (DS.isThreadSpecified()) {
2554 Diag(DS.getThreadSpecLoc(),
2555 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002556 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002557 }
2558
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002559 // Check that there are no default arguments inside the type of this
2560 // parameter (C++ only).
2561 if (getLangOptions().CPlusPlus)
2562 CheckExtraCXXDefaultArguments(D);
2563
Chris Lattner04421082008-04-08 04:40:51 +00002564 // In this context, we *do not* check D.getInvalidType(). If the declarator
2565 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2566 // though it will not reflect the user specified type.
2567 QualType parmDeclType = GetTypeForDeclarator(D, S);
2568
2569 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2570
Reid Spencer5f016e22007-07-11 17:01:13 +00002571 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2572 // Can this happen for params? We already checked that they don't conflict
2573 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002574 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002575 if (II) {
2576 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2577 if (PrevDecl->isTemplateParameter()) {
2578 // Maybe we will complain about the shadowed template parameter.
2579 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2580 // Just pretend that we didn't see the previous declaration.
2581 PrevDecl = 0;
2582 } else if (S->isDeclScope(PrevDecl)) {
2583 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002584
Chris Lattnercf79b012009-01-21 02:38:50 +00002585 // Recover by removing the name
2586 II = 0;
2587 D.SetIdentifier(0, D.getIdentifierLoc());
2588 }
Chris Lattner04421082008-04-08 04:40:51 +00002589 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002591
2592 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2593 // Doing the promotion here has a win and a loss. The win is the type for
2594 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2595 // code generator). The loss is the orginal type isn't preserved. For example:
2596 //
2597 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2598 // int blockvardecl[5];
2599 // sizeof(parmvardecl); // size == 4
2600 // sizeof(blockvardecl); // size == 20
2601 // }
2602 //
2603 // For expressions, all implicit conversions are captured using the
2604 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2605 //
2606 // FIXME: If a source translation tool needs to see the original type, then
2607 // we need to consider storing both types (in ParmVarDecl)...
2608 //
Chris Lattnere6327742008-04-02 05:18:44 +00002609 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002610 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002611 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002612 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002613 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002614
Chris Lattner04421082008-04-08 04:40:51 +00002615 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2616 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002617 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002618 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002619
Chris Lattner04421082008-04-08 04:40:51 +00002620 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002621 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002622
Douglas Gregor584049d2008-12-15 23:53:10 +00002623 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2624 if (D.getCXXScopeSpec().isSet()) {
2625 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2626 << D.getCXXScopeSpec().getRange();
2627 New->setInvalidDecl();
2628 }
2629
Douglas Gregor44b43212008-12-11 16:49:14 +00002630 // Add the parameter declaration into this scope.
2631 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002632 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002633 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002634
Chris Lattner3ff30c82008-06-29 00:02:00 +00002635 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002639
Douglas Gregorbe109b32009-01-23 16:23:13 +00002640void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002641 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2642 "Not a function declarator!");
2643 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002644
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2646 // for a K&R function.
2647 if (!FTI.hasPrototype) {
2648 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002649 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002650 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2651 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 // Implicitly declare the argument as type 'int' for lack of a better
2653 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002654 DeclSpec DS;
2655 const char* PrevSpec; // unused
2656 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2657 PrevSpec);
2658 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2659 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002660 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002661 }
2662 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002663 }
2664}
2665
2666Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2667 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2668 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2669 "Not a function declarator!");
2670 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2671
2672 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002673 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002674 }
2675
Douglas Gregor584049d2008-12-15 23:53:10 +00002676 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002677
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002678 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002679 ActOnDeclarator(ParentScope, D, 0,
2680 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002681}
2682
2683Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2684 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002685 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002686
2687 // See if this is a redefinition.
2688 const FunctionDecl *Definition;
2689 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002690 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002691 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002692 }
2693
Douglas Gregor44b43212008-12-11 16:49:14 +00002694 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002695
Chris Lattner04421082008-04-08 04:40:51 +00002696 // Check the validity of our function parameters
2697 CheckParmsForFunctionDef(FD);
2698
2699 // Introduce our parameters into the function scope
2700 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2701 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002702 Param->setOwningFunction(FD);
2703
Chris Lattner04421082008-04-08 04:40:51 +00002704 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002705 if (Param->getIdentifier())
2706 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 }
Chris Lattner04421082008-04-08 04:40:51 +00002708
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002709 // Checking attributes of current function definition
2710 // dllimport attribute.
2711 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2712 // dllimport attribute cannot be applied to definition.
2713 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2714 Diag(FD->getLocation(),
2715 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2716 << "dllimport";
2717 FD->setInvalidDecl();
2718 return FD;
2719 } else {
2720 // If a symbol previously declared dllimport is later defined, the
2721 // attribute is ignored in subsequent references, and a warning is
2722 // emitted.
2723 Diag(FD->getLocation(),
2724 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2725 << FD->getNameAsCString() << "dllimport";
2726 }
2727 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002728 return FD;
2729}
2730
Sebastian Redl798d1192008-12-13 16:23:55 +00002731Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002732 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002733 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002734 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002735 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002736 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002737 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002738 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002739 } else
2740 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002741 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 // Verify and clean out per-function state.
2743
2744 // Check goto/label use.
2745 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2746 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2747 // Verify that we have no forward references left. If so, there was a goto
2748 // or address of a label taken, but no definition of it. Label fwd
2749 // definitions are indicated with a null substmt.
2750 if (I->second->getSubStmt() == 0) {
2751 LabelStmt *L = I->second;
2752 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002753 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002754
2755 // At this point, we have gotos that use the bogus label. Stitch it into
2756 // the function body so that they aren't leaked and that the AST is well
2757 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002758 if (Body) {
2759 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002760 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002761 } else {
2762 // The whole function wasn't parsed correctly, just delete this.
2763 delete L;
2764 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 }
2766 }
2767 LabelMap.clear();
2768
Steve Naroffd6d054d2007-11-11 23:20:51 +00002769 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002770}
2771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2773/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002774NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2775 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002776 // Extension in C99. Legal in C90, but warn about it.
2777 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002778 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002779 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002780 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781
2782 // FIXME: handle stuff like:
2783 // void foo() { extern float X(); }
2784 // void bar() { X(); } <-- implicit decl for X in another scope.
2785
2786 // Set a Declarator for the implicit definition: int foo();
2787 const char *Dummy;
2788 DeclSpec DS;
2789 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2790 Error = Error; // Silence warning.
2791 assert(!Error && "Error setting up implicit decl!");
2792 Declarator D(DS, Declarator::BlockContext);
Chris Lattner5af2f352009-01-20 19:11:22 +00002793 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 D.SetIdentifier(&II, Loc);
2795
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002796 // Insert this function into translation-unit scope.
2797
2798 DeclContext *PrevDC = CurContext;
2799 CurContext = Context.getTranslationUnitDecl();
2800
Steve Naroffe2ef8152008-04-04 14:32:09 +00002801 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002802 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002803 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002804
2805 CurContext = PrevDC;
2806
Steve Naroffe2ef8152008-04-04 14:32:09 +00002807 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002808}
2809
2810
Chris Lattner41af0932007-11-14 06:34:38 +00002811TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002812 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002814 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002815
2816 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002817 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2818 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002819 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002820 T);
2821 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002822 if (D.getInvalidType())
2823 NewTD->setInvalidDecl();
2824 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002825}
2826
Steve Naroff08d92e42007-09-15 18:49:24 +00002827/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002828/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002829/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002830/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002831Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002832 SourceLocation KWLoc, const CXXScopeSpec &SS,
2833 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002834 AttributeList *Attr,
2835 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002836 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002837 assert((Name != 0 || TK == TK_Definition) &&
2838 "Nameless record must be a definition!");
2839
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002840 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002841 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002842 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002843 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2844 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2845 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2846 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002847 }
2848
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002849 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002850 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002851 DeclContext *LexicalContext = CurContext;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002852 Decl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002853
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002854 bool Invalid = false;
2855
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002856 if (Name && SS.isNotEmpty()) {
2857 // We have a nested-name tag ('struct foo::bar').
2858
2859 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002860 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002861 Name = 0;
2862 goto CreateNewDecl;
2863 }
2864
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002865 DC = static_cast<DeclContext*>(SS.getScopeRep());
2866 // Look-up name inside 'foo::'.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002867 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2868 .getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002869
2870 // A tag 'foo::bar' must already exist.
2871 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002872 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002873 Name = 0;
2874 goto CreateNewDecl;
2875 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002876 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002877 // If this is a named struct, check to see if there was a previous forward
2878 // declaration or definition.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002879 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
Chris Lattnercf79b012009-01-21 02:38:50 +00002880 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002881
2882 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2883 // FIXME: This makes sure that we ignore the contexts associated
2884 // with C structs, unions, and enums when looking for a matching
2885 // tag declaration or definition. See the similar lookup tweak
2886 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002887 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2888 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002889 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002890 }
2891
Douglas Gregorf57172b2008-12-08 18:40:42 +00002892 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002893 // Maybe we will complain about the shadowed template parameter.
2894 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2895 // Just pretend that we didn't see the previous declaration.
2896 PrevDecl = 0;
2897 }
2898
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002899 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002900 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002901 // If this is a use of a previous tag, or if the tag is already declared
2902 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002903 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002904 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002905 // Make sure that this wasn't declared as an enum and now used as a
2906 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002907 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002908 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002909 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002910 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002911 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002912 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002913 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002914 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002915 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002916
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002917 // FIXME: In the future, return a variant or some other clue
2918 // for the consumer of this Decl to know it doesn't own it.
2919 // For our current ASTs this shouldn't be a problem, but will
2920 // need to be changed with DeclGroups.
2921 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002922 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002923
2924 // Diagnose attempts to redefine a tag.
2925 if (TK == TK_Definition) {
2926 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2927 Diag(NameLoc, diag::err_redefinition) << Name;
2928 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002929 // If this is a redefinition, recover by making this
2930 // struct be anonymous, which will make any later
2931 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002932 Name = 0;
2933 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002934 Invalid = true;
2935 } else {
2936 // If the type is currently being defined, complain
2937 // about a nested redefinition.
2938 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2939 if (Tag->isBeingDefined()) {
2940 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2941 Diag(PrevTagDecl->getLocation(),
2942 diag::note_previous_definition);
2943 Name = 0;
2944 PrevDecl = 0;
2945 Invalid = true;
2946 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002947 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002948
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002949 // Okay, this is definition of a previously declared or referenced
2950 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002951 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002952 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002953 // If we get here we have (another) forward declaration or we
2954 // have a definition. Just create a new decl.
2955 } else {
2956 // If we get here, this is a definition of a new tag type in a nested
2957 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2958 // new decl/type. We set PrevDecl to NULL so that the entities
2959 // have distinct types.
2960 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002961 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002962 // If we get here, we're going to create a new Decl. If PrevDecl
2963 // is non-NULL, it's a definition of the tag declared by
2964 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002965 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00002966 // PrevDecl is a namespace, template, or anything else
2967 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002968 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002969 // The tag name clashes with a namespace name, issue an error and
2970 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002971 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002972 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002973 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002974 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002975 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002976 } else {
2977 // The existing declaration isn't relevant to us; we're in a
2978 // new scope, so clear out the previous declaration.
2979 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002980 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002981 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002982 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2983 (Kind != TagDecl::TK_enum)) {
2984 // C++ [basic.scope.pdecl]p5:
2985 // -- for an elaborated-type-specifier of the form
2986 //
2987 // class-key identifier
2988 //
2989 // if the elaborated-type-specifier is used in the
2990 // decl-specifier-seq or parameter-declaration-clause of a
2991 // function defined in namespace scope, the identifier is
2992 // declared as a class-name in the namespace that contains
2993 // the declaration; otherwise, except as a friend
2994 // declaration, the identifier is declared in the smallest
2995 // non-class, non-function-prototype scope that contains the
2996 // declaration.
2997 //
2998 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2999 // C structs and unions.
3000
3001 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003002 // FIXME: We would like to maintain the current DeclContext as the
3003 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003004 while (DC->isRecord())
3005 DC = DC->getParent();
3006 LexicalContext = DC;
3007
3008 // Find the scope where we'll be declaring the tag.
3009 while (S->isClassScope() ||
3010 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003011 ((S->getFlags() & Scope::DeclScope) == 0) ||
3012 (S->getEntity() &&
3013 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003014 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003016
Chris Lattnercc98eac2008-12-17 07:13:27 +00003017CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003018
3019 // If there is an identifier, use the location of the identifier as the
3020 // location of the decl, otherwise use the location of the struct/union
3021 // keyword.
3022 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3023
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003024 // Otherwise, create a new declaration. If there is a previous
3025 // declaration of the same entity, the two will be linked via
3026 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003028
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003029 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003030 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3031 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003032 New = EnumDecl::Create(Context, DC, Loc, Name,
3033 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 // If this is an undefined enum, warn.
3035 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003036 } else {
3037 // struct/union/class
3038
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3040 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003041 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003042 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003043 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3044 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003045 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003046 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3047 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003048 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003049
3050 if (Kind != TagDecl::TK_enum) {
3051 // Handle #pragma pack: if the #pragma pack stack has non-default
3052 // alignment, make up a packed attribute for this decl. These
3053 // attributes are checked when the ASTContext lays out the
3054 // structure.
3055 //
3056 // It is important for implementing the correct semantics that this
3057 // happen here (in act on tag decl). The #pragma pack stack is
3058 // maintained as a result of parser callbacks which can occur at
3059 // many points during the parsing of a struct declaration (because
3060 // the #pragma tokens are effectively skipped over during the
3061 // parsing of the struct).
3062 if (unsigned Alignment = PackContext.getAlignment())
3063 New->addAttr(new PackedAttr(Alignment * 8));
3064 }
3065
Douglas Gregor66973122009-01-28 17:15:10 +00003066 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3067 // C++ [dcl.typedef]p3:
3068 // [...] Similarly, in a given scope, a class or enumeration
3069 // shall not be declared with the same name as a typedef-name
3070 // that is declared in that scope and refers to a type other
3071 // than the class or enumeration itself.
3072 LookupResult Lookup = LookupName(S, Name,
3073 LookupCriteria(LookupCriteria::Ordinary,
3074 true, true));
3075 TypedefDecl *PrevTypedef = 0;
3076 if (Lookup.getKind() == LookupResult::Found)
3077 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3078
3079 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3080 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3081 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3082 Diag(Loc, diag::err_tag_definition_of_typedef)
3083 << Context.getTypeDeclType(New)
3084 << PrevTypedef->getUnderlyingType();
3085 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3086 Invalid = true;
3087 }
3088 }
3089
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003090 if (Invalid)
3091 New->setInvalidDecl();
3092
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003093 if (Attr)
3094 ProcessDeclAttributeList(New, Attr);
3095
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003096 // If we're declaring or defining a tag in function prototype scope
3097 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003098 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3099 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3100
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003101 // Set the lexical context. If the tag has a C++ scope specifier, the
3102 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003103 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003104
3105 if (TK == TK_Definition)
3106 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003107
3108 // If this has an identifier, add it to the scope stack.
3109 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003110 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003111
3112 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003113 if (LexicalContext != CurContext) {
3114 // FIXME: PushOnScopeChains should not rely on CurContext!
3115 DeclContext *OldContext = CurContext;
3116 CurContext = LexicalContext;
3117 PushOnScopeChains(New, S);
3118 CurContext = OldContext;
3119 } else
3120 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003121 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003122 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003123 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003124
Reid Spencer5f016e22007-07-11 17:01:13 +00003125 return New;
3126}
3127
Douglas Gregor72de6672009-01-08 20:45:30 +00003128void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3129 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3130
3131 // Enter the tag context.
3132 PushDeclContext(S, Tag);
3133
3134 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3135 FieldCollector->StartClass();
3136
3137 if (Record->getIdentifier()) {
3138 // C++ [class]p2:
3139 // [...] The class-name is also inserted into the scope of the
3140 // class itself; this is known as the injected-class-name. For
3141 // purposes of access checking, the injected-class-name is treated
3142 // as if it were a public member name.
3143 RecordDecl *InjectedClassName
3144 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3145 CurContext, Record->getLocation(),
3146 Record->getIdentifier(), Record);
3147 InjectedClassName->setImplicit();
3148 PushOnScopeChains(InjectedClassName, S);
3149 }
3150 }
3151}
3152
3153void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3154 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3155
3156 if (isa<CXXRecordDecl>(Tag))
3157 FieldCollector->FinishClass();
3158
3159 // Exit this scope of this tag's definition.
3160 PopDeclContext();
3161
3162 // Notify the consumer that we've defined a tag.
3163 Consumer.HandleTagDeclDefinition(Tag);
3164}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003165
Chris Lattner1d353ba2008-11-12 21:17:48 +00003166/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3167/// types into constant array types in certain situations which would otherwise
3168/// be errors (for GCC compatibility).
3169static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3170 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003171 // This method tries to turn a variable array into a constant
3172 // array even when the size isn't an ICE. This is necessary
3173 // for compatibility with code that depends on gcc's buggy
3174 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003175 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3176 if (!VLATy) return QualType();
3177
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003178 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003179 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003180 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003181 return QualType();
3182
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003183 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3184 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003185 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3186 return Context.getConstantArrayType(VLATy->getElementType(),
3187 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003188 return QualType();
3189}
3190
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003191bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003192 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003193 // FIXME: 6.7.2.1p4 - verify the field type.
3194
3195 llvm::APSInt Value;
3196 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3197 return true;
3198
Chris Lattnercd087072008-12-12 04:56:04 +00003199 // Zero-width bitfield is ok for anonymous field.
3200 if (Value == 0 && FieldName)
3201 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3202
3203 if (Value.isNegative())
3204 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003205
3206 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3207 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003208 if (TypeSize && Value.getZExtValue() > TypeSize)
3209 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3210 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003211
3212 return false;
3213}
3214
Steve Naroff08d92e42007-09-15 18:49:24 +00003215/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003216/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003217Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003218 SourceLocation DeclStart,
3219 Declarator &D, ExprTy *BitfieldWidth) {
3220 IdentifierInfo *II = D.getIdentifier();
3221 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003222 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003223 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003224 if (II) Loc = D.getIdentifierLoc();
3225
3226 // FIXME: Unnamed fields can be handled in various different ways, for
3227 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003228
Reid Spencer5f016e22007-07-11 17:01:13 +00003229 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003230 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3231 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003232
Reid Spencer5f016e22007-07-11 17:01:13 +00003233 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3234 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003235 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003236 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003237 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003238 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003239 T = FixedTy;
3240 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003241 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003242 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003243 InvalidDecl = true;
3244 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003245 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003246
3247 if (BitWidth) {
3248 if (VerifyBitField(Loc, II, T, BitWidth))
3249 InvalidDecl = true;
3250 } else {
3251 // Not a bitfield.
3252
3253 // validate II.
3254
3255 }
3256
Reid Spencer5f016e22007-07-11 17:01:13 +00003257 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003258 FieldDecl *NewFD;
3259
Douglas Gregor44b43212008-12-11 16:49:14 +00003260 NewFD = FieldDecl::Create(Context, Record,
3261 Loc, II, T, BitWidth,
3262 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003263 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003264
Douglas Gregor72de6672009-01-08 20:45:30 +00003265 if (II) {
3266 Decl *PrevDecl
Steve Naroff133147d2009-01-28 16:09:22 +00003267 = LookupDecl(II, Decl::IDNS_Member, S, 0, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003268 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3269 && !isa<TagDecl>(PrevDecl)) {
3270 Diag(Loc, diag::err_duplicate_member) << II;
3271 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3272 NewFD->setInvalidDecl();
3273 Record->setInvalidDecl();
3274 }
3275 }
3276
Sebastian Redl64b45f72009-01-05 20:52:13 +00003277 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003278 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003279 if (!T->isPODType())
3280 cast<CXXRecordDecl>(Record)->setPOD(false);
3281 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003282
Chris Lattner3ff30c82008-06-29 00:02:00 +00003283 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003284
Steve Naroff5912a352007-08-28 20:14:24 +00003285 if (D.getInvalidType() || InvalidDecl)
3286 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003287
Douglas Gregor72de6672009-01-08 20:45:30 +00003288 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003289 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003290 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003291 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003292
Steve Naroff5912a352007-08-28 20:14:24 +00003293 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003294}
3295
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003296/// TranslateIvarVisibility - Translate visibility from a token ID to an
3297/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003298static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003299TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003300 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003301 default: assert(0 && "Unknown visitibility kind");
3302 case tok::objc_private: return ObjCIvarDecl::Private;
3303 case tok::objc_public: return ObjCIvarDecl::Public;
3304 case tok::objc_protected: return ObjCIvarDecl::Protected;
3305 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003306 }
3307}
3308
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003309/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3310/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003311Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003312 SourceLocation DeclStart,
3313 Declarator &D, ExprTy *BitfieldWidth,
3314 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003315
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003316 IdentifierInfo *II = D.getIdentifier();
3317 Expr *BitWidth = (Expr*)BitfieldWidth;
3318 SourceLocation Loc = DeclStart;
3319 if (II) Loc = D.getIdentifierLoc();
3320
3321 // FIXME: Unnamed fields can be handled in various different ways, for
3322 // example, unnamed unions inject all members into the struct namespace!
3323
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003324 QualType T = GetTypeForDeclarator(D, S);
3325 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3326 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003327
3328 if (BitWidth) {
3329 // TODO: Validate.
3330 //printf("WARNING: BITFIELDS IGNORED!\n");
3331
3332 // 6.7.2.1p3
3333 // 6.7.2.1p4
3334
3335 } else {
3336 // Not a bitfield.
3337
3338 // validate II.
3339
3340 }
3341
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003342 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3343 // than a variably modified type.
3344 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003345 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003346 InvalidDecl = true;
3347 }
3348
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003349 // Get the visibility (access control) for this ivar.
3350 ObjCIvarDecl::AccessControl ac =
3351 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3352 : ObjCIvarDecl::None;
3353
3354 // Construct the decl.
3355 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003356 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003357
Douglas Gregor72de6672009-01-08 20:45:30 +00003358 if (II) {
3359 Decl *PrevDecl
Steve Naroff133147d2009-01-28 16:09:22 +00003360 = LookupDecl(II, Decl::IDNS_Member, S, 0, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003361 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3362 && !isa<TagDecl>(PrevDecl)) {
3363 Diag(Loc, diag::err_duplicate_member) << II;
3364 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3365 NewID->setInvalidDecl();
3366 }
3367 }
3368
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003369 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003370 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003371
3372 if (D.getInvalidType() || InvalidDecl)
3373 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003374
Douglas Gregor72de6672009-01-08 20:45:30 +00003375 if (II) {
3376 // FIXME: When interfaces are DeclContexts, we'll need to add
3377 // these to the interface.
3378 S->AddDecl(NewID);
3379 IdResolver.AddDecl(NewID);
3380 }
3381
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003382 return NewID;
3383}
3384
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003385void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003386 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003387 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003388 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003389 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003390 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3391 assert(EnclosingDecl && "missing record or interface decl");
3392 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3393
Reid Spencer5f016e22007-07-11 17:01:13 +00003394 // Verify that all the fields are okay.
3395 unsigned NumNamedMembers = 0;
3396 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003397
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003399 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3400 assert(FD && "missing field decl");
3401
Reid Spencer5f016e22007-07-11 17:01:13 +00003402 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003403 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003404
Douglas Gregor72de6672009-01-08 20:45:30 +00003405 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003406 // Remember all fields written by the user.
3407 RecFields.push_back(FD);
3408 }
Steve Narofff13271f2007-09-14 23:09:53 +00003409
Reid Spencer5f016e22007-07-11 17:01:13 +00003410 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003411 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003412 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003413 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003414 FD->setInvalidDecl();
3415 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003416 continue;
3417 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003418 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3419 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003420 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003421 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3422 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003423 FD->setInvalidDecl();
3424 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003425 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003426 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003427 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003428 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003429 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003430 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3431 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003432 FD->setInvalidDecl();
3433 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003434 continue;
3435 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003436 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003437 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003438 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003439 FD->setInvalidDecl();
3440 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003441 continue;
3442 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003443 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003444 if (Record)
3445 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003447 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3448 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003449 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003450 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3451 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003452 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003453 Record->setHasFlexibleArrayMember(true);
3454 } else {
3455 // If this is a struct/class and this is not the last element, reject
3456 // it. Note that GCC supports variable sized arrays in the middle of
3457 // structures.
3458 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003459 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003460 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003461 FD->setInvalidDecl();
3462 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003463 continue;
3464 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003465 // We support flexible arrays at the end of structs in other structs
3466 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003467 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003468 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003469 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003470 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003471 }
3472 }
3473 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003474 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003475 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003476 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003477 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003478 FD->setInvalidDecl();
3479 EnclosingDecl->setInvalidDecl();
3480 continue;
3481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003482 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003483 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003484 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003485 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003486
Reid Spencer5f016e22007-07-11 17:01:13 +00003487 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003488 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003489 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003490 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003491 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003492 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003493 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003494 // Must enforce the rule that ivars in the base classes may not be
3495 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003496 if (ID->getSuperClass()) {
3497 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3498 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3499 ObjCIvarDecl* Ivar = (*IVI);
3500 IdentifierInfo *II = Ivar->getIdentifier();
3501 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3502 if (prevIvar) {
3503 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003504 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003505 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003506 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003507 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003508 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003509 else if (ObjCImplementationDecl *IMPDecl =
3510 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003511 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3512 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003513 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003514 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003515 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003516
3517 if (Attr)
3518 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003519}
3520
Steve Naroff08d92e42007-09-15 18:49:24 +00003521Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003522 DeclTy *lastEnumConst,
3523 SourceLocation IdLoc, IdentifierInfo *Id,
3524 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003525 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003526 EnumConstantDecl *LastEnumConst =
3527 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3528 Expr *Val = static_cast<Expr*>(val);
3529
Chris Lattner31e05722007-08-26 06:24:45 +00003530 // The scope passed in may not be a decl scope. Zip up the scope tree until
3531 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003532 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003533
Reid Spencer5f016e22007-07-11 17:01:13 +00003534 // Verify that there isn't already something declared with this name in this
3535 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003536 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003537 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003538 // Maybe we will complain about the shadowed template parameter.
3539 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3540 // Just pretend that we didn't see the previous declaration.
3541 PrevDecl = 0;
3542 }
3543
3544 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003545 // When in C++, we may get a TagDecl with the same name; in this case the
3546 // enum constant will 'hide' the tag.
3547 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3548 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003549 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003550 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003551 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003552 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003553 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003554 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003555 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003556 return 0;
3557 }
3558 }
3559
3560 llvm::APSInt EnumVal(32);
3561 QualType EltTy;
3562 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003563 // Make sure to promote the operand type to int.
3564 UsualUnaryConversions(Val);
3565
Reid Spencer5f016e22007-07-11 17:01:13 +00003566 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3567 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003568 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003569 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003570 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003571 } else {
3572 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003573 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003574 }
3575
3576 if (!Val) {
3577 if (LastEnumConst) {
3578 // Assign the last value + 1.
3579 EnumVal = LastEnumConst->getInitVal();
3580 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003581
3582 // Check for overflow on increment.
3583 if (EnumVal < LastEnumConst->getInitVal())
3584 Diag(IdLoc, diag::warn_enum_value_overflow);
3585
Chris Lattnerb7416f92007-08-27 17:37:24 +00003586 EltTy = LastEnumConst->getType();
3587 } else {
3588 // First value, set to zero.
3589 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003590 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003591 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003592 }
3593
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003594 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003595 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003596 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003597
3598 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003599 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003600
Reid Spencer5f016e22007-07-11 17:01:13 +00003601 return New;
3602}
3603
Steve Naroff02408c62008-08-07 14:08:16 +00003604// FIXME: For consistency with ActOnFields(), we should have the parser
3605// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003606void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003607 DeclTy **Elements, unsigned NumElements) {
3608 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003609 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003610
Chris Lattnere37f0be2007-08-28 05:10:31 +00003611 // TODO: If the result value doesn't fit in an int, it must be a long or long
3612 // long value. ISO C does not support this, but GCC does as an extension,
3613 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003614 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003615
Chris Lattnerac609682007-08-28 06:15:15 +00003616 // Verify that all the values are okay, compute the size of the values, and
3617 // reverse the list.
3618 unsigned NumNegativeBits = 0;
3619 unsigned NumPositiveBits = 0;
3620
3621 // Keep track of whether all elements have type int.
3622 bool AllElementsInt = true;
3623
Reid Spencer5f016e22007-07-11 17:01:13 +00003624 for (unsigned i = 0; i != NumElements; ++i) {
3625 EnumConstantDecl *ECD =
3626 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3627 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003628
3629 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003630 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003631 assert(InitVal.getBitWidth() >= IntWidth &&
3632 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003633 if (InitVal.getBitWidth() > IntWidth) {
3634 llvm::APSInt V(InitVal);
3635 V.trunc(IntWidth);
3636 V.extend(InitVal.getBitWidth());
3637 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003638 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3639 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003640 }
Chris Lattnerac609682007-08-28 06:15:15 +00003641
3642 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003643 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003644 NumPositiveBits = std::max(NumPositiveBits,
3645 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003646 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003647 NumNegativeBits = std::max(NumNegativeBits,
3648 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003649
Chris Lattnerac609682007-08-28 06:15:15 +00003650 // Keep track of whether every enum element has type int (very commmon).
3651 if (AllElementsInt)
3652 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003653 }
3654
Chris Lattnerac609682007-08-28 06:15:15 +00003655 // Figure out the type that should be used for this enum.
3656 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3657 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003658 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003659
3660 if (NumNegativeBits) {
3661 // If there is a negative value, figure out the smallest integer type (of
3662 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003663 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003664 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003665 BestWidth = IntWidth;
3666 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003667 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003668
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003669 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003670 BestType = Context.LongTy;
3671 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003672 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003673
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003674 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003675 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3676 BestType = Context.LongLongTy;
3677 }
3678 }
3679 } else {
3680 // If there is no negative value, figure out which of uint, ulong, ulonglong
3681 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003682 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003683 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003684 BestWidth = IntWidth;
3685 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003686 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003687 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003688 } else {
3689 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003690 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003691 "How could an initializer get larger than ULL?");
3692 BestType = Context.UnsignedLongLongTy;
3693 }
3694 }
3695
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003696 // Loop over all of the enumerator constants, changing their types to match
3697 // the type of the enum if needed.
3698 for (unsigned i = 0; i != NumElements; ++i) {
3699 EnumConstantDecl *ECD =
3700 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3701 if (!ECD) continue; // Already issued a diagnostic.
3702
3703 // Standard C says the enumerators have int type, but we allow, as an
3704 // extension, the enumerators to be larger than int size. If each
3705 // enumerator value fits in an int, type it as an int, otherwise type it the
3706 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3707 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003708 if (ECD->getType() == Context.IntTy) {
3709 // Make sure the init value is signed.
3710 llvm::APSInt IV = ECD->getInitVal();
3711 IV.setIsSigned(true);
3712 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003713
3714 if (getLangOptions().CPlusPlus)
3715 // C++ [dcl.enum]p4: Following the closing brace of an
3716 // enum-specifier, each enumerator has the type of its
3717 // enumeration.
3718 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003719 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003720 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003721
3722 // Determine whether the value fits into an int.
3723 llvm::APSInt InitVal = ECD->getInitVal();
3724 bool FitsInInt;
3725 if (InitVal.isUnsigned() || !InitVal.isNegative())
3726 FitsInInt = InitVal.getActiveBits() < IntWidth;
3727 else
3728 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3729
3730 // If it fits into an integer type, force it. Otherwise force it to match
3731 // the enum decl type.
3732 QualType NewTy;
3733 unsigned NewWidth;
3734 bool NewSign;
3735 if (FitsInInt) {
3736 NewTy = Context.IntTy;
3737 NewWidth = IntWidth;
3738 NewSign = true;
3739 } else if (ECD->getType() == BestType) {
3740 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003741 if (getLangOptions().CPlusPlus)
3742 // C++ [dcl.enum]p4: Following the closing brace of an
3743 // enum-specifier, each enumerator has the type of its
3744 // enumeration.
3745 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003746 continue;
3747 } else {
3748 NewTy = BestType;
3749 NewWidth = BestWidth;
3750 NewSign = BestType->isSignedIntegerType();
3751 }
3752
3753 // Adjust the APSInt value.
3754 InitVal.extOrTrunc(NewWidth);
3755 InitVal.setIsSigned(NewSign);
3756 ECD->setInitVal(InitVal);
3757
3758 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003759 if (ECD->getInitExpr())
3760 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3761 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003762 if (getLangOptions().CPlusPlus)
3763 // C++ [dcl.enum]p4: Following the closing brace of an
3764 // enum-specifier, each enumerator has the type of its
3765 // enumeration.
3766 ECD->setType(EnumType);
3767 else
3768 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003769 }
Chris Lattnerac609682007-08-28 06:15:15 +00003770
Douglas Gregor44b43212008-12-11 16:49:14 +00003771 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003772}
3773
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003774Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003775 ExprArg expr) {
3776 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3777
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003778 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003779}
3780
Douglas Gregorf44515a2008-12-16 22:23:02 +00003781
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003782void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3783 ExprTy *alignment, SourceLocation PragmaLoc,
3784 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3785 Expr *Alignment = static_cast<Expr *>(alignment);
3786
3787 // If specified then alignment must be a "small" power of two.
3788 unsigned AlignmentVal = 0;
3789 if (Alignment) {
3790 llvm::APSInt Val;
3791 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3792 !Val.isPowerOf2() ||
3793 Val.getZExtValue() > 16) {
3794 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3795 delete Alignment;
3796 return; // Ignore
3797 }
3798
3799 AlignmentVal = (unsigned) Val.getZExtValue();
3800 }
3801
3802 switch (Kind) {
3803 case Action::PPK_Default: // pack([n])
3804 PackContext.setAlignment(AlignmentVal);
3805 break;
3806
3807 case Action::PPK_Show: // pack(show)
3808 // Show the current alignment, making sure to show the right value
3809 // for the default.
3810 AlignmentVal = PackContext.getAlignment();
3811 // FIXME: This should come from the target.
3812 if (AlignmentVal == 0)
3813 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003814 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003815 break;
3816
3817 case Action::PPK_Push: // pack(push [, id] [, [n])
3818 PackContext.push(Name);
3819 // Set the new alignment if specified.
3820 if (Alignment)
3821 PackContext.setAlignment(AlignmentVal);
3822 break;
3823
3824 case Action::PPK_Pop: // pack(pop [, id] [, n])
3825 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3826 // "#pragma pack(pop, identifier, n) is undefined"
3827 if (Alignment && Name)
3828 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3829
3830 // Do the pop.
3831 if (!PackContext.pop(Name)) {
3832 // If a name was specified then failure indicates the name
3833 // wasn't found. Otherwise failure indicates the stack was
3834 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003835 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3836 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003837
3838 // FIXME: Warn about popping named records as MSVC does.
3839 } else {
3840 // Pop succeeded, set the new alignment if specified.
3841 if (Alignment)
3842 PackContext.setAlignment(AlignmentVal);
3843 }
3844 break;
3845
3846 default:
3847 assert(0 && "Invalid #pragma pack kind.");
3848 }
3849}
3850
3851bool PragmaPackStack::pop(IdentifierInfo *Name) {
3852 if (Stack.empty())
3853 return false;
3854
3855 // If name is empty just pop top.
3856 if (!Name) {
3857 Alignment = Stack.back().first;
3858 Stack.pop_back();
3859 return true;
3860 }
3861
3862 // Otherwise, find the named record.
3863 for (unsigned i = Stack.size(); i != 0; ) {
3864 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003865 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003866 // Found it, pop up to and including this record.
3867 Alignment = Stack[i].first;
3868 Stack.erase(Stack.begin() + i, Stack.end());
3869 return true;
3870 }
3871 }
3872
3873 return false;
3874}