blob: 7746917e3b9d895473b4b727bb2cc2283ee2abd0 [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.
218 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
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,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000266 bool LookInParent,
267 bool NamespaceNameOnly) {
268 LookupCriteria::NameKind Kind;
269 if (NSI == Decl::IDNS_Ordinary) {
270 if (NamespaceNameOnly)
271 Kind = LookupCriteria::Namespace;
272 else
273 Kind = LookupCriteria::Ordinary;
274 } else if (NSI == Decl::IDNS_Tag)
275 Kind = LookupCriteria::Tag;
Chris Lattner95d58f32009-01-16 19:44:00 +0000276 else {
277 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000278 Kind = LookupCriteria::Member;
Chris Lattner95d58f32009-01-16 19:44:00 +0000279 }
280
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000281 if (LookupCtx)
282 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
283 LookupCriteria(Kind, !LookInParent,
284 getLangOptions().CPlusPlus));
Douglas Gregor72de6672009-01-08 20:45:30 +0000285
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000286 // Unqualified lookup
287 return LookupName(S, Name,
288 LookupCriteria(Kind, !LookInParent,
289 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000290}
291
Chris Lattner95e2c712008-05-05 22:18:14 +0000292void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000293 if (!Context.getBuiltinVaListType().isNull())
294 return;
295
296 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000297 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000298 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000299 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
300}
301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
303/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000304NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
305 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 Builtin::ID BID = (Builtin::ID)bid;
307
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000308 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000309 InitBuiltinVaListType();
310
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000311 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000312 FunctionDecl *New = FunctionDecl::Create(Context,
313 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000314 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000315 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
Chris Lattner95e2c712008-05-05 22:18:14 +0000317 // Create Decl objects for each parameter, adding them to the
318 // FunctionDecl.
319 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
320 llvm::SmallVector<ParmVarDecl*, 16> Params;
321 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
322 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000323 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000324 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000325 }
326
327
328
Chris Lattner7f925cc2008-04-11 07:00:53 +0000329 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000330 // FIXME: This is hideous. We need to teach PushOnScopeChains to
331 // relate Scopes to DeclContexts, and probably eliminate CurContext
332 // entirely, but we're not there yet.
333 DeclContext *SavedContext = CurContext;
334 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000335 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000336 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 return New;
338}
339
Sebastian Redlc42e1182008-11-11 11:37:55 +0000340/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
341/// everything from the standard library is defined.
342NamespaceDecl *Sema::GetStdNamespace() {
343 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000344 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000345 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroff939837f2009-01-28 15:51:12 +0000346 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary, 0, Global);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000347 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
348 }
349 return StdNamespace;
350}
351
Reid Spencer5f016e22007-07-11 17:01:13 +0000352/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
353/// and scope as a previous declaration 'Old'. Figure out how to resolve this
354/// situation, merging decls or emitting diagnostics as appropriate.
355///
Steve Naroffe8043c32008-04-01 23:04:06 +0000356TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000357 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000358 // Allow multiple definitions for ObjC built-in typedefs.
359 // FIXME: Verify the underlying types are equivalent!
360 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000361 const IdentifierInfo *TypeID = New->getIdentifier();
362 switch (TypeID->getLength()) {
363 default: break;
364 case 2:
365 if (!TypeID->isStr("id"))
366 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000367 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000368 objc_types = true;
369 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000370 case 5:
371 if (!TypeID->isStr("Class"))
372 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000373 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000374 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000375 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000376 case 3:
377 if (!TypeID->isStr("SEL"))
378 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000379 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000380 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000381 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000382 case 8:
383 if (!TypeID->isStr("Protocol"))
384 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000385 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000386 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000387 return New;
388 }
389 // Fall through - the typedef name was not a builtin type.
390 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000391 // Verify the old decl was also a typedef.
392 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
393 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000394 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000395 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000396 if (!objc_types)
397 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 return New;
399 }
400
Chris Lattner99cb9972008-07-25 18:44:27 +0000401 // If the typedef types are not identical, reject them in all languages and
402 // with any extensions enabled.
403 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
404 Context.getCanonicalType(Old->getUnderlyingType()) !=
405 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000406 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000407 << New->getUnderlyingType() << Old->getUnderlyingType();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000408 if (!objc_types)
409 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000410 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000411 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000412 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000413 if (getLangOptions().Microsoft) return New;
414
Douglas Gregorbbe27432008-11-21 16:29:06 +0000415 // C++ [dcl.typedef]p2:
416 // In a given non-class scope, a typedef specifier can be used to
417 // redefine the name of any type declared in that scope to refer
418 // to the type to which it already refers.
419 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
420 return New;
421
422 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000423 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
424 // *either* declaration is in a system header. The code below implements
425 // this adhoc compatibility rule. FIXME: The following code will not
426 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000427 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
428 SourceManager &SrcMgr = Context.getSourceManager();
429 if (SrcMgr.isInSystemHeader(Old->getLocation()))
430 return New;
431 if (SrcMgr.isInSystemHeader(New->getLocation()))
432 return New;
433 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000434
Chris Lattner08631c52008-11-23 21:45:46 +0000435 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000436 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 return New;
438}
439
Chris Lattner6b6b5372008-06-26 18:38:35 +0000440/// DeclhasAttr - returns true if decl Declaration already has the target
441/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000442static bool DeclHasAttr(const Decl *decl, const Attr *target) {
443 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
444 if (attr->getKind() == target->getKind())
445 return true;
446
447 return false;
448}
449
450/// MergeAttributes - append attributes from the Old decl to the New one.
451static void MergeAttributes(Decl *New, Decl *Old) {
452 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
453
Chris Lattnerddee4232008-03-03 03:28:21 +0000454 while (attr) {
455 tmp = attr;
456 attr = attr->getNext();
457
458 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000459 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000460 New->addAttr(tmp);
461 } else {
462 tmp->setNext(0);
463 delete(tmp);
464 }
465 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000466
467 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000468}
469
Chris Lattner04421082008-04-08 04:40:51 +0000470/// MergeFunctionDecl - We just parsed a function 'New' from
471/// declarator D which has the same name and scope as a previous
472/// declaration 'Old'. Figure out how to resolve this situation,
473/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474/// Redeclaration will be set true if this New is a redeclaration OldD.
475///
476/// In C++, New and Old must be declarations that are not
477/// overloaded. Use IsOverload to determine whether New and Old are
478/// overloaded, and to select the Old declaration that New should be
479/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000480FunctionDecl *
481Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 assert(!isa<OverloadedFunctionDecl>(OldD) &&
483 "Cannot merge with an overloaded function declaration");
484
Douglas Gregorf0097952008-04-21 02:02:58 +0000485 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 // Verify the old decl was also a function.
487 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
488 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000489 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000490 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000491 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 return New;
493 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494
495 // Determine whether the previous declaration was a definition,
496 // implicit declaration, or a declaration.
497 diag::kind PrevDiag;
498 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000499 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000500 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000501 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000503 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000504
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000505 QualType OldQType = Context.getCanonicalType(Old->getType());
506 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000507
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 if (getLangOptions().CPlusPlus) {
509 // (C++98 13.1p2):
510 // Certain function declarations cannot be overloaded:
511 // -- Function declarations that differ only in the return type
512 // cannot be overloaded.
513 QualType OldReturnType
514 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
515 QualType NewReturnType
516 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
517 if (OldReturnType != NewReturnType) {
518 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
519 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000520 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 return New;
522 }
523
524 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
525 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
526 if (OldMethod && NewMethod) {
527 // -- Member function declarations with the same name and the
528 // same parameter types cannot be overloaded if any of them
529 // is a static member function declaration.
530 if (OldMethod->isStatic() || NewMethod->isStatic()) {
531 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
532 Diag(Old->getLocation(), PrevDiag);
533 return New;
534 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000535
536 // C++ [class.mem]p1:
537 // [...] A member shall not be declared twice in the
538 // member-specification, except that a nested class or member
539 // class template can be declared and then later defined.
540 if (OldMethod->getLexicalDeclContext() ==
541 NewMethod->getLexicalDeclContext()) {
542 unsigned NewDiag;
543 if (isa<CXXConstructorDecl>(OldMethod))
544 NewDiag = diag::err_constructor_redeclared;
545 else if (isa<CXXDestructorDecl>(NewMethod))
546 NewDiag = diag::err_destructor_redeclared;
547 else if (isa<CXXConversionDecl>(NewMethod))
548 NewDiag = diag::err_conv_function_redeclared;
549 else
550 NewDiag = diag::err_member_redeclared;
551
552 Diag(New->getLocation(), NewDiag);
553 Diag(Old->getLocation(), PrevDiag);
554 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 }
556
557 // (C++98 8.3.5p3):
558 // All declarations for a function shall agree exactly in both the
559 // return type and the parameter-type-list.
560 if (OldQType == NewQType) {
561 // We have a redeclaration.
562 MergeAttributes(New, Old);
563 Redeclaration = true;
564 return MergeCXXFunctionDecl(New, Old);
565 }
566
567 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000568 }
Chris Lattner04421082008-04-08 04:40:51 +0000569
570 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000571 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000572 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000573 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000574 MergeAttributes(New, Old);
575 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000576 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000577 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000578
Steve Naroff837618c2008-01-16 15:01:34 +0000579 // A function that has already been declared has been redeclared or defined
580 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000581
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
583 // TODO: This is totally simplistic. It should handle merging functions
584 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000585 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000586 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 return New;
588}
589
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000590/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000591static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000592 if (VD->isFileVarDecl())
593 return (!VD->getInit() &&
594 (VD->getStorageClass() == VarDecl::None ||
595 VD->getStorageClass() == VarDecl::Static));
596 return false;
597}
598
599/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
600/// when dealing with C "tentative" external object definitions (C99 6.9.2).
601void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
602 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000603 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000604
Douglas Gregore21b9942009-01-07 16:34:42 +0000605 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000606 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000607 for (IdentifierResolver::iterator
608 I = IdResolver.begin(VD->getIdentifier(),
609 VD->getDeclContext(), false/*LookInParentCtx*/),
610 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000611 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000612 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
613
Steve Narofff855e6f2008-08-10 15:20:13 +0000614 // Handle the following case:
615 // int a[10];
616 // int a[]; - the code below makes sure we set the correct type.
617 // int a[11]; - this is an error, size isn't 10.
618 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
619 OldDecl->getType()->isConstantArrayType())
620 VD->setType(OldDecl->getType());
621
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000622 // Check for "tentative" definitions. We can't accomplish this in
623 // MergeVarDecl since the initializer hasn't been attached.
624 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
625 continue;
626
627 // Handle __private_extern__ just like extern.
628 if (OldDecl->getStorageClass() != VarDecl::Extern &&
629 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
630 VD->getStorageClass() != VarDecl::Extern &&
631 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000632 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000633 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000634 }
635 }
636 }
637}
638
Reid Spencer5f016e22007-07-11 17:01:13 +0000639/// MergeVarDecl - We just parsed a variable 'New' which has the same name
640/// and scope as a previous declaration 'Old'. Figure out how to resolve this
641/// situation, merging decls or emitting diagnostics as appropriate.
642///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000643/// Tentative definition rules (C99 6.9.2p2) are checked by
644/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
645/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000646///
Steve Naroffe8043c32008-04-01 23:04:06 +0000647VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 // Verify the old decl was also a variable.
649 VarDecl *Old = dyn_cast<VarDecl>(OldD);
650 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000651 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000652 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000653 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 return New;
655 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000656
657 MergeAttributes(New, Old);
658
Eli Friedman13ca96a2009-01-24 23:49:55 +0000659 // Merge the types
660 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
661 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000662 Diag(New->getLocation(), diag::err_redefinition_different_type)
663 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000664 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 return New;
666 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000667 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000668 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
669 if (New->getStorageClass() == VarDecl::Static &&
670 (Old->getStorageClass() == VarDecl::None ||
671 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000672 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000673 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000674 return New;
675 }
676 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
677 if (New->getStorageClass() != VarDecl::Static &&
678 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000679 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000680 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000681 return New;
682 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000683 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
684 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000685 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000686 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 }
688 return New;
689}
690
Chris Lattner04421082008-04-08 04:40:51 +0000691/// CheckParmsForFunctionDef - Check that the parameters of the given
692/// function are appropriate for the definition of a function. This
693/// takes care of any checks that cannot be performed on the
694/// declaration itself, e.g., that the types of each of the function
695/// parameters are complete.
696bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
697 bool HasInvalidParm = false;
698 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
699 ParmVarDecl *Param = FD->getParamDecl(p);
700
701 // C99 6.7.5.3p4: the parameters in a parameter type list in a
702 // function declarator that is part of a function definition of
703 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000704 if (!Param->isInvalidDecl() &&
705 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
706 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000707 Param->setInvalidDecl();
708 HasInvalidParm = true;
709 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000710
711 // C99 6.9.1p5: If the declarator includes a parameter type list, the
712 // declaration of each parameter shall include an identifier.
713 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
714 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000715 }
716
717 return HasInvalidParm;
718}
719
Reid Spencer5f016e22007-07-11 17:01:13 +0000720/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
721/// no declarator (e.g. "struct foo;") is parsed.
722Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000723 TagDecl *Tag
724 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
725 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
726 if (!Record->getDeclName() && Record->isDefinition() &&
727 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
728 return BuildAnonymousStructOrUnion(S, DS, Record);
729
730 // Microsoft allows unnamed struct/union fields. Don't complain
731 // about them.
732 // FIXME: Should we support Microsoft's extensions in this area?
733 if (Record->getDeclName() && getLangOptions().Microsoft)
734 return Tag;
735 }
736
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000737 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000738 // Warn about typedefs of enums without names, since this is an
739 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000740 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
741 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000742 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000743 << DS.getSourceRange();
744 return Tag;
745 }
746
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000747 // FIXME: This diagnostic is emitted even when various previous
748 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
749 // DeclSpec has no means of communicating this information, and the
750 // responsible parser functions are quite far apart.
751 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
752 << DS.getSourceRange();
753 return 0;
754 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000755
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000756 return Tag;
757}
758
759/// InjectAnonymousStructOrUnionMembers - Inject the members of the
760/// anonymous struct or union AnonRecord into the owning context Owner
761/// and scope S. This routine will be invoked just after we realize
762/// that an unnamed union or struct is actually an anonymous union or
763/// struct, e.g.,
764///
765/// @code
766/// union {
767/// int i;
768/// float f;
769/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
770/// // f into the surrounding scope.x
771/// @endcode
772///
773/// This routine is recursive, injecting the names of nested anonymous
774/// structs/unions into the owning context and scope as well.
775bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
776 RecordDecl *AnonRecord) {
777 bool Invalid = false;
778 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
779 FEnd = AnonRecord->field_end();
780 F != FEnd; ++F) {
781 if ((*F)->getDeclName()) {
782 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
Steve Naroff939837f2009-01-28 15:51:12 +0000783 S, Owner, false, false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000784 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
785 // C++ [class.union]p2:
786 // The names of the members of an anonymous union shall be
787 // distinct from the names of any other entity in the
788 // scope in which the anonymous union is declared.
789 unsigned diagKind
790 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
791 : diag::err_anonymous_struct_member_redecl;
792 Diag((*F)->getLocation(), diagKind)
793 << (*F)->getDeclName();
794 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
795 Invalid = true;
796 } else {
797 // C++ [class.union]p2:
798 // For the purpose of name lookup, after the anonymous union
799 // definition, the members of the anonymous union are
800 // considered to have been defined in the scope in which the
801 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000802 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000803 S->AddDecl(*F);
804 IdResolver.AddDecl(*F);
805 }
806 } else if (const RecordType *InnerRecordType
807 = (*F)->getType()->getAsRecordType()) {
808 RecordDecl *InnerRecord = InnerRecordType->getDecl();
809 if (InnerRecord->isAnonymousStructOrUnion())
810 Invalid = Invalid ||
811 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
812 }
813 }
814
815 return Invalid;
816}
817
818/// ActOnAnonymousStructOrUnion - Handle the declaration of an
819/// anonymous structure or union. Anonymous unions are a C++ feature
820/// (C++ [class.union]) and a GNU C extension; anonymous structures
821/// are a GNU C and GNU C++ extension.
822Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
823 RecordDecl *Record) {
824 DeclContext *Owner = Record->getDeclContext();
825
826 // Diagnose whether this anonymous struct/union is an extension.
827 if (Record->isUnion() && !getLangOptions().CPlusPlus)
828 Diag(Record->getLocation(), diag::ext_anonymous_union);
829 else if (!Record->isUnion())
830 Diag(Record->getLocation(), diag::ext_anonymous_struct);
831
832 // C and C++ require different kinds of checks for anonymous
833 // structs/unions.
834 bool Invalid = false;
835 if (getLangOptions().CPlusPlus) {
836 const char* PrevSpec = 0;
837 // C++ [class.union]p3:
838 // Anonymous unions declared in a named namespace or in the
839 // global namespace shall be declared static.
840 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
841 (isa<TranslationUnitDecl>(Owner) ||
842 (isa<NamespaceDecl>(Owner) &&
843 cast<NamespaceDecl>(Owner)->getDeclName()))) {
844 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
845 Invalid = true;
846
847 // Recover by adding 'static'.
848 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
849 }
850 // C++ [class.union]p3:
851 // A storage class is not allowed in a declaration of an
852 // anonymous union in a class scope.
853 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
854 isa<RecordDecl>(Owner)) {
855 Diag(DS.getStorageClassSpecLoc(),
856 diag::err_anonymous_union_with_storage_spec);
857 Invalid = true;
858
859 // Recover by removing the storage specifier.
860 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
861 PrevSpec);
862 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000863
864 // C++ [class.union]p2:
865 // The member-specification of an anonymous union shall only
866 // define non-static data members. [Note: nested types and
867 // functions cannot be declared within an anonymous union. ]
868 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
869 MemEnd = Record->decls_end();
870 Mem != MemEnd; ++Mem) {
871 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
872 // C++ [class.union]p3:
873 // An anonymous union shall not have private or protected
874 // members (clause 11).
875 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
876 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
877 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
878 Invalid = true;
879 }
880 } else if ((*Mem)->isImplicit()) {
881 // Any implicit members are fine.
882 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
883 if (!MemRecord->isAnonymousStructOrUnion() &&
884 MemRecord->getDeclName()) {
885 // This is a nested type declaration.
886 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
887 << (int)Record->isUnion();
888 Invalid = true;
889 }
890 } else {
891 // We have something that isn't a non-static data
892 // member. Complain about it.
893 unsigned DK = diag::err_anonymous_record_bad_member;
894 if (isa<TypeDecl>(*Mem))
895 DK = diag::err_anonymous_record_with_type;
896 else if (isa<FunctionDecl>(*Mem))
897 DK = diag::err_anonymous_record_with_function;
898 else if (isa<VarDecl>(*Mem))
899 DK = diag::err_anonymous_record_with_static;
900 Diag((*Mem)->getLocation(), DK)
901 << (int)Record->isUnion();
902 Invalid = true;
903 }
904 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000905 } else {
906 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000907 if (Record->isUnion() && !Owner->isRecord()) {
908 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
909 << (int)getLangOptions().CPlusPlus;
910 Invalid = true;
911 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000912 }
913
914 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000915 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
916 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000917 Invalid = true;
918 }
919
920 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000921 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000922 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
923 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
924 /*IdentifierInfo=*/0,
925 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000926 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000927 Anon->setAccess(AS_public);
928 if (getLangOptions().CPlusPlus)
929 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000930 } else {
931 VarDecl::StorageClass SC;
932 switch (DS.getStorageClassSpec()) {
933 default: assert(0 && "Unknown storage class!");
934 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
935 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
936 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
937 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
938 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
939 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
940 case DeclSpec::SCS_mutable:
941 // mutable can only appear on non-static class members, so it's always
942 // an error here
943 Diag(Record->getLocation(), diag::err_mutable_nonmember);
944 Invalid = true;
945 SC = VarDecl::None;
946 break;
947 }
948
949 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
950 /*IdentifierInfo=*/0,
951 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000952 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000953 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000954 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000955
956 // Add the anonymous struct/union object to the current
957 // context. We'll be referencing this object when we refer to one of
958 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000959 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000960
961 // Inject the members of the anonymous struct/union into the owning
962 // context and into the identifier resolver chain for name lookup
963 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000964 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
965 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000966
967 // Mark this as an anonymous struct/union type. Note that we do not
968 // do this until after we have already checked and injected the
969 // members of this anonymous struct/union type, because otherwise
970 // the members could be injected twice: once by DeclContext when it
971 // builds its lookup table, and once by
972 // InjectAnonymousStructOrUnionMembers.
973 Record->setAnonymousStructOrUnion(true);
974
975 if (Invalid)
976 Anon->setInvalidDecl();
977
978 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000979}
980
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000981bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
982 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000983 // Get the type before calling CheckSingleAssignmentConstraints(), since
984 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000985 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000986
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000987 if (getLangOptions().CPlusPlus) {
988 // FIXME: I dislike this error message. A lot.
989 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
990 return Diag(Init->getSourceRange().getBegin(),
991 diag::err_typecheck_convert_incompatible)
992 << DeclType << Init->getType() << "initializing"
993 << Init->getSourceRange();
994
995 return false;
996 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000997
Chris Lattner5cf216b2008-01-04 18:04:52 +0000998 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
999 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1000 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001001}
1002
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001003bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001004 const ArrayType *AT = Context.getAsArrayType(DeclT);
1005
1006 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001007 // C99 6.7.8p14. We have an array of character type with unknown size
1008 // being initialized to a string literal.
1009 llvm::APSInt ConstVal(32);
1010 ConstVal = strLiteral->getByteLength() + 1;
1011 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001012 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001013 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001014 } else {
1015 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001016 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001017 // FIXME: Avoid truncation for 64-bit length strings.
1018 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001019 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001020 diag::warn_initializer_string_for_char_array_too_long)
1021 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001022 }
1023 // Set type from "char *" to "constant array of char".
1024 strLiteral->setType(DeclT);
1025 // For now, we always return false (meaning success).
1026 return false;
1027}
1028
1029StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001030 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001031 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +00001032 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +00001033 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001034 return 0;
1035}
1036
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001037bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1038 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001039 DeclarationName InitEntity,
1040 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001041 if (DeclType->isDependentType() || Init->isTypeDependent())
1042 return false;
1043
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001044 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001045 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001046 // (8.3.2), shall be initialized by an object, or function, of
1047 // type T or by an object that can be converted into a T.
1048 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001049 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001050
Steve Naroffca107302008-01-21 23:53:58 +00001051 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1052 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001053 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001054 return Diag(InitLoc, diag::err_variable_object_no_init)
1055 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001056
Steve Naroff2fdc3742007-12-10 22:44:33 +00001057 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1058 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001059 // FIXME: Handle wide strings
1060 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1061 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001062
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001063 // C++ [dcl.init]p14:
1064 // -- If the destination type is a (possibly cv-qualified) class
1065 // type:
1066 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1067 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1068 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1069
1070 // -- If the initialization is direct-initialization, or if it is
1071 // copy-initialization where the cv-unqualified version of the
1072 // source type is the same class as, or a derived class of, the
1073 // class of the destination, constructors are considered.
1074 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1075 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1076 CXXConstructorDecl *Constructor
1077 = PerformInitializationByConstructor(DeclType, &Init, 1,
1078 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001079 InitEntity,
1080 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001081 return Constructor == 0;
1082 }
1083
1084 // -- Otherwise (i.e., for the remaining copy-initialization
1085 // cases), user-defined conversion sequences that can
1086 // convert from the source type to the destination type or
1087 // (when a conversion function is used) to a derived class
1088 // thereof are enumerated as described in 13.3.1.4, and the
1089 // best one is chosen through overload resolution
1090 // (13.3). If the conversion cannot be done or is
1091 // ambiguous, the initialization is ill-formed. The
1092 // function selected is called with the initializer
1093 // expression as its argument; if the function is a
1094 // constructor, the call initializes a temporary of the
1095 // destination type.
1096 // FIXME: We're pretending to do copy elision here; return to
1097 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001098 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001099 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001100
Douglas Gregor61366e92008-12-24 00:01:03 +00001101 if (InitEntity)
1102 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1103 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1104 << Init->getType() << Init->getSourceRange();
1105 else
1106 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1107 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1108 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001109 }
1110
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001111 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001112 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001113 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1114 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001115
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001116 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001117 } else if (getLangOptions().CPlusPlus) {
1118 // C++ [dcl.init]p14:
1119 // [...] If the class is an aggregate (8.5.1), and the initializer
1120 // is a brace-enclosed list, see 8.5.1.
1121 //
1122 // Note: 8.5.1 is handled below; here, we diagnose the case where
1123 // we have an initializer list and a destination type that is not
1124 // an aggregate.
1125 // FIXME: In C++0x, this is yet another form of initialization.
1126 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1127 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1128 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001129 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001130 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001131 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001132 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001133
Steve Naroff0cca7492008-05-01 22:18:59 +00001134 InitListChecker CheckInitList(this, InitList, DeclType);
1135 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001136}
1137
Douglas Gregor10bd3682008-11-17 22:58:34 +00001138/// GetNameForDeclarator - Determine the full declaration name for the
1139/// given Declarator.
1140DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1141 switch (D.getKind()) {
1142 case Declarator::DK_Abstract:
1143 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1144 return DeclarationName();
1145
1146 case Declarator::DK_Normal:
1147 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1148 return DeclarationName(D.getIdentifier());
1149
1150 case Declarator::DK_Constructor: {
1151 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1152 Ty = Context.getCanonicalType(Ty);
1153 return Context.DeclarationNames.getCXXConstructorName(Ty);
1154 }
1155
1156 case Declarator::DK_Destructor: {
1157 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1158 Ty = Context.getCanonicalType(Ty);
1159 return Context.DeclarationNames.getCXXDestructorName(Ty);
1160 }
1161
1162 case Declarator::DK_Conversion: {
1163 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1164 Ty = Context.getCanonicalType(Ty);
1165 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1166 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001167
1168 case Declarator::DK_Operator:
1169 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1170 return Context.DeclarationNames.getCXXOperatorName(
1171 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001172 }
1173
1174 assert(false && "Unknown name kind");
1175 return DeclarationName();
1176}
1177
Douglas Gregor584049d2008-12-15 23:53:10 +00001178/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1179/// functions Declaration and Definition are "nearly" matching. This
1180/// heuristic is used to improve diagnostics in the case where an
1181/// out-of-line member function definition doesn't match any
1182/// declaration within the class.
1183static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1184 FunctionDecl *Declaration,
1185 FunctionDecl *Definition) {
1186 if (Declaration->param_size() != Definition->param_size())
1187 return false;
1188 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1189 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1190 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1191
1192 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1193 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1194 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1195 return false;
1196 }
1197
1198 return true;
1199}
1200
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001201Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001202Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1203 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001204 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001205 DeclarationName Name = GetNameForDeclarator(D);
1206
Chris Lattnere80a59c2007-07-25 00:24:17 +00001207 // All of these full declarators require an identifier. If it doesn't have
1208 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001209 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001210 if (!D.getInvalidType()) // Reject this if we think it is valid.
1211 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001212 diag::err_declarator_need_ident)
1213 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001214 return 0;
1215 }
1216
Chris Lattner31e05722007-08-26 06:24:45 +00001217 // The scope passed in may not be a decl scope. Zip up the scope tree until
1218 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001219 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1220 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001221 S = S->getParent();
1222
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001223 DeclContext *DC;
1224 Decl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001225 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001226 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001227
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001228 // See if this is a redefinition of a variable in the same scope.
1229 if (!D.getCXXScopeSpec().isSet()) {
1230 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001231 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001232 } else { // Something like "int foo::x;"
1233 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001234 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001235
1236 // C++ 7.3.1.2p2:
1237 // Members (including explicit specializations of templates) of a named
1238 // namespace can also be defined outside that namespace by explicit
1239 // qualification of the name being defined, provided that the entity being
1240 // defined was already declared in the namespace and the definition appears
1241 // after the point of declaration in a namespace that encloses the
1242 // declarations namespace.
1243 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001244 // Note that we only check the context at this point. We don't yet
1245 // have enough information to make sure that PrevDecl is actually
1246 // the declaration we want to match. For example, given:
1247 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001248 // class X {
1249 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001250 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001251 // };
1252 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001253 // void X::f(int) { } // ill-formed
1254 //
1255 // In this case, PrevDecl will point to the overload set
1256 // containing the two f's declared in X, but neither of them
1257 // matches.
1258 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001259 // The qualifying scope doesn't enclose the original declaration.
1260 // Emit diagnostic based on current scope.
1261 SourceLocation L = D.getIdentifierLoc();
1262 SourceRange R = D.getCXXScopeSpec().getRange();
1263 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001264 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001265 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001266 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001267 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001268 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001269 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001270 }
1271 }
1272
Douglas Gregorf57172b2008-12-08 18:40:42 +00001273 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001274 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001275 InvalidDecl = InvalidDecl
1276 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001277 // Just pretend that we didn't see the previous declaration.
1278 PrevDecl = 0;
1279 }
1280
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001281 // In C++, the previous declaration we find might be a tag type
1282 // (class or enum). In this case, the new declaration will hide the
1283 // tag type.
1284 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1285 PrevDecl = 0;
1286
Chris Lattner41af0932007-11-14 06:34:38 +00001287 QualType R = GetTypeForDeclarator(D, S);
1288 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1289
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001291 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1292 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001293 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001294 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1295 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001297 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1298 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001300
1301 if (New == 0)
1302 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001303
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001304 // Set the lexical context. If the declarator has a C++ scope specifier, the
1305 // lexical context will be different from the semantic context.
1306 New->setLexicalDeclContext(CurContext);
1307
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001309 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001310 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001311 // If any semantic error occurred, mark the decl as invalid.
1312 if (D.getInvalidType() || InvalidDecl)
1313 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001314
1315 return New;
1316}
1317
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001318NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001319Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001320 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001321 Decl* PrevDecl, bool& InvalidDecl) {
1322 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1323 if (D.getCXXScopeSpec().isSet()) {
1324 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1325 << D.getCXXScopeSpec().getRange();
1326 InvalidDecl = true;
1327 // Pretend we didn't see the scope specifier.
1328 DC = 0;
1329 }
1330
1331 // Check that there are no default arguments (C++ only).
1332 if (getLangOptions().CPlusPlus)
1333 CheckExtraCXXDefaultArguments(D);
1334
1335 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1336 if (!NewTD) return 0;
1337
1338 // Handle attributes prior to checking for duplicates in MergeVarDecl
1339 ProcessDeclAttributes(NewTD, D);
1340 // Merge the decl with the existing one if appropriate. If the decl is
1341 // in an outer scope, it isn't the same thing.
1342 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1343 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1344 if (NewTD == 0) return 0;
1345 }
1346
1347 if (S->getFnParent() == 0) {
1348 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1349 // then it shall have block scope.
1350 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1351 if (NewTD->getUnderlyingType()->isVariableArrayType())
1352 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1353 else
1354 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1355
1356 InvalidDecl = true;
1357 }
1358 }
1359 return NewTD;
1360}
1361
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001362NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001363Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001364 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001365 Decl* PrevDecl, bool& InvalidDecl) {
1366 DeclarationName Name = GetNameForDeclarator(D);
1367
1368 // Check that there are no default arguments (C++ only).
1369 if (getLangOptions().CPlusPlus)
1370 CheckExtraCXXDefaultArguments(D);
1371
1372 if (R.getTypePtr()->isObjCInterfaceType()) {
1373 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1374 << D.getIdentifier();
1375 InvalidDecl = true;
1376 }
1377
1378 VarDecl *NewVD;
1379 VarDecl::StorageClass SC;
1380 switch (D.getDeclSpec().getStorageClassSpec()) {
1381 default: assert(0 && "Unknown storage class!");
1382 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1383 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1384 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1385 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1386 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1387 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1388 case DeclSpec::SCS_mutable:
1389 // mutable can only appear on non-static class members, so it's always
1390 // an error here
1391 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1392 InvalidDecl = true;
1393 SC = VarDecl::None;
1394 break;
1395 }
1396
1397 IdentifierInfo *II = Name.getAsIdentifierInfo();
1398 if (!II) {
1399 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1400 << Name.getAsString();
1401 return 0;
1402 }
1403
1404 if (DC->isRecord()) {
1405 // This is a static data member for a C++ class.
1406 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1407 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001408 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001409 } else {
1410 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1411 if (S->getFnParent() == 0) {
1412 // C99 6.9p2: The storage-class specifiers auto and register shall not
1413 // appear in the declaration specifiers in an external declaration.
1414 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1415 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1416 InvalidDecl = true;
1417 }
1418 }
1419 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001420 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001421 // FIXME: Move to DeclGroup...
1422 D.getDeclSpec().getSourceRange().getBegin());
1423 NewVD->setThreadSpecified(ThreadSpecified);
1424 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001425 NewVD->setNextDeclarator(LastDeclarator);
1426
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001427 // Handle attributes prior to checking for duplicates in MergeVarDecl
1428 ProcessDeclAttributes(NewVD, D);
1429
1430 // Handle GNU asm-label extension (encoded as an attribute).
1431 if (Expr *E = (Expr*) D.getAsmLabel()) {
1432 // The parser guarantees this is a string.
1433 StringLiteral *SE = cast<StringLiteral>(E);
1434 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1435 SE->getByteLength())));
1436 }
1437
1438 // Emit an error if an address space was applied to decl with local storage.
1439 // This includes arrays of objects with address space qualifiers, but not
1440 // automatic variables that point to other address spaces.
1441 // ISO/IEC TR 18037 S5.1.2
1442 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1443 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1444 InvalidDecl = true;
1445 }
1446 // Merge the decl with the existing one if appropriate. If the decl is
1447 // in an outer scope, it isn't the same thing.
1448 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1449 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1450 // The user tried to define a non-static data member
1451 // out-of-line (C++ [dcl.meaning]p1).
1452 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1453 << D.getCXXScopeSpec().getRange();
1454 NewVD->Destroy(Context);
1455 return 0;
1456 }
1457
1458 NewVD = MergeVarDecl(NewVD, PrevDecl);
1459 if (NewVD == 0) return 0;
1460
1461 if (D.getCXXScopeSpec().isSet()) {
1462 // No previous declaration in the qualifying scope.
1463 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1464 << Name << D.getCXXScopeSpec().getRange();
1465 InvalidDecl = true;
1466 }
1467 }
1468 return NewVD;
1469}
1470
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001471NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001472Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001473 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001474 Decl* PrevDecl, bool IsFunctionDefinition,
1475 bool& InvalidDecl) {
1476 assert(R.getTypePtr()->isFunctionType());
1477
1478 DeclarationName Name = GetNameForDeclarator(D);
1479 FunctionDecl::StorageClass SC = FunctionDecl::None;
1480 switch (D.getDeclSpec().getStorageClassSpec()) {
1481 default: assert(0 && "Unknown storage class!");
1482 case DeclSpec::SCS_auto:
1483 case DeclSpec::SCS_register:
1484 case DeclSpec::SCS_mutable:
1485 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1486 InvalidDecl = true;
1487 break;
1488 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1489 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1490 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1491 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1492 }
1493
1494 bool isInline = D.getDeclSpec().isInlineSpecified();
1495 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1496 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1497
1498 FunctionDecl *NewFD;
1499 if (D.getKind() == Declarator::DK_Constructor) {
1500 // This is a C++ constructor declaration.
1501 assert(DC->isRecord() &&
1502 "Constructors can only be declared in a member context");
1503
1504 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1505
1506 // Create the new declaration
1507 NewFD = CXXConstructorDecl::Create(Context,
1508 cast<CXXRecordDecl>(DC),
1509 D.getIdentifierLoc(), Name, R,
1510 isExplicit, isInline,
1511 /*isImplicitlyDeclared=*/false);
1512
1513 if (InvalidDecl)
1514 NewFD->setInvalidDecl();
1515 } else if (D.getKind() == Declarator::DK_Destructor) {
1516 // This is a C++ destructor declaration.
1517 if (DC->isRecord()) {
1518 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1519
1520 NewFD = CXXDestructorDecl::Create(Context,
1521 cast<CXXRecordDecl>(DC),
1522 D.getIdentifierLoc(), Name, R,
1523 isInline,
1524 /*isImplicitlyDeclared=*/false);
1525
1526 if (InvalidDecl)
1527 NewFD->setInvalidDecl();
1528 } else {
1529 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1530
1531 // Create a FunctionDecl to satisfy the function definition parsing
1532 // code path.
1533 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001534 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001535 // FIXME: Move to DeclGroup...
1536 D.getDeclSpec().getSourceRange().getBegin());
1537 InvalidDecl = true;
1538 NewFD->setInvalidDecl();
1539 }
1540 } else if (D.getKind() == Declarator::DK_Conversion) {
1541 if (!DC->isRecord()) {
1542 Diag(D.getIdentifierLoc(),
1543 diag::err_conv_function_not_member);
1544 return 0;
1545 } else {
1546 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1547
1548 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1549 D.getIdentifierLoc(), Name, R,
1550 isInline, isExplicit);
1551
1552 if (InvalidDecl)
1553 NewFD->setInvalidDecl();
1554 }
1555 } else if (DC->isRecord()) {
1556 // This is a C++ method declaration.
1557 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1558 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001559 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001560 } else {
1561 NewFD = FunctionDecl::Create(Context, DC,
1562 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001563 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001564 // FIXME: Move to DeclGroup...
1565 D.getDeclSpec().getSourceRange().getBegin());
1566 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001567 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001568
1569 // Set the lexical context. If the declarator has a C++
1570 // scope specifier, the lexical context will be different
1571 // from the semantic context.
1572 NewFD->setLexicalDeclContext(CurContext);
1573
1574 // Handle GNU asm-label extension (encoded as an attribute).
1575 if (Expr *E = (Expr*) D.getAsmLabel()) {
1576 // The parser guarantees this is a string.
1577 StringLiteral *SE = cast<StringLiteral>(E);
1578 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1579 SE->getByteLength())));
1580 }
1581
1582 // Copy the parameter declarations from the declarator D to
1583 // the function declaration NewFD, if they are available.
1584 if (D.getNumTypeObjects() > 0) {
1585 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1586
1587 // Create Decl objects for each parameter, adding them to the
1588 // FunctionDecl.
1589 llvm::SmallVector<ParmVarDecl*, 16> Params;
1590
1591 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1592 // function that takes no arguments, not a function that takes a
1593 // single void argument.
1594 // We let through "const void" here because Sema::GetTypeForDeclarator
1595 // already checks for that case.
1596 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1597 FTI.ArgInfo[0].Param &&
1598 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1599 // empty arg list, don't push any params.
1600 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1601
1602 // In C++, the empty parameter-type-list must be spelled "void"; a
1603 // typedef of void is not permitted.
1604 if (getLangOptions().CPlusPlus &&
1605 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1606 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1607 }
1608 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1609 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1610 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1611 }
1612
1613 NewFD->setParams(Context, &Params[0], Params.size());
1614 } else if (R->getAsTypedefType()) {
1615 // When we're declaring a function with a typedef, as in the
1616 // following example, we'll need to synthesize (unnamed)
1617 // parameters for use in the declaration.
1618 //
1619 // @code
1620 // typedef void fn(int);
1621 // fn f;
1622 // @endcode
1623 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1624 if (!FT) {
1625 // This is a typedef of a function with no prototype, so we
1626 // don't need to do anything.
1627 } else if ((FT->getNumArgs() == 0) ||
1628 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1629 FT->getArgType(0)->isVoidType())) {
1630 // This is a zero-argument function. We don't need to do anything.
1631 } else {
1632 // Synthesize a parameter for each argument type.
1633 llvm::SmallVector<ParmVarDecl*, 16> Params;
1634 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1635 ArgType != FT->arg_type_end(); ++ArgType) {
1636 Params.push_back(ParmVarDecl::Create(Context, DC,
1637 SourceLocation(), 0,
1638 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001639 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001640 }
1641
1642 NewFD->setParams(Context, &Params[0], Params.size());
1643 }
1644 }
1645
1646 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1647 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1648 else if (isa<CXXDestructorDecl>(NewFD)) {
1649 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1650 Record->setUserDeclaredDestructor(true);
1651 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1652 // user-defined destructor.
1653 Record->setPOD(false);
1654 } else if (CXXConversionDecl *Conversion =
1655 dyn_cast<CXXConversionDecl>(NewFD))
1656 ActOnConversionDeclarator(Conversion);
1657
1658 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1659 if (NewFD->isOverloadedOperator() &&
1660 CheckOverloadedOperatorDeclaration(NewFD))
1661 NewFD->setInvalidDecl();
1662
1663 // Merge the decl with the existing one if appropriate. Since C functions
1664 // are in a flat namespace, make sure we consider decls in outer scopes.
1665 if (PrevDecl &&
1666 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1667 bool Redeclaration = false;
1668
1669 // If C++, determine whether NewFD is an overload of PrevDecl or
1670 // a declaration that requires merging. If it's an overload,
1671 // there's no more work to do here; we'll just add the new
1672 // function to the scope.
1673 OverloadedFunctionDecl::function_iterator MatchedDecl;
1674 if (!getLangOptions().CPlusPlus ||
1675 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1676 Decl *OldDecl = PrevDecl;
1677
1678 // If PrevDecl was an overloaded function, extract the
1679 // FunctionDecl that matched.
1680 if (isa<OverloadedFunctionDecl>(PrevDecl))
1681 OldDecl = *MatchedDecl;
1682
1683 // NewFD and PrevDecl represent declarations that need to be
1684 // merged.
1685 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1686
1687 if (NewFD == 0) return 0;
1688 if (Redeclaration) {
1689 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1690
1691 // An out-of-line member function declaration must also be a
1692 // definition (C++ [dcl.meaning]p1).
1693 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1694 !InvalidDecl) {
1695 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1696 << D.getCXXScopeSpec().getRange();
1697 NewFD->setInvalidDecl();
1698 }
1699 }
1700 }
1701
1702 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1703 // The user tried to provide an out-of-line definition for a
1704 // member function, but there was no such member function
1705 // declared (C++ [class.mfct]p2). For example:
1706 //
1707 // class X {
1708 // void f() const;
1709 // };
1710 //
1711 // void X::f() { } // ill-formed
1712 //
1713 // Complain about this problem, and attempt to suggest close
1714 // matches (e.g., those that differ only in cv-qualifiers and
1715 // whether the parameter types are references).
1716 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1717 << cast<CXXRecordDecl>(DC)->getDeclName()
1718 << D.getCXXScopeSpec().getRange();
1719 InvalidDecl = true;
1720
1721 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1722 if (!PrevDecl) {
1723 // Nothing to suggest.
1724 } else if (OverloadedFunctionDecl *Ovl
1725 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1726 for (OverloadedFunctionDecl::function_iterator
1727 Func = Ovl->function_begin(),
1728 FuncEnd = Ovl->function_end();
1729 Func != FuncEnd; ++Func) {
1730 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1731 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1732
1733 }
1734 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1735 // Suggest this no matter how mismatched it is; it's the only
1736 // thing we have.
1737 unsigned diag;
1738 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1739 diag = diag::note_member_def_close_match;
1740 else if (Method->getBody())
1741 diag = diag::note_previous_definition;
1742 else
1743 diag = diag::note_previous_declaration;
1744 Diag(Method->getLocation(), diag);
1745 }
1746
1747 PrevDecl = 0;
1748 }
1749 }
1750 // Handle attributes. We need to have merged decls when handling attributes
1751 // (for example to check for conflicts, etc).
1752 ProcessDeclAttributes(NewFD, D);
1753
1754 if (getLangOptions().CPlusPlus) {
1755 // In C++, check default arguments now that we have merged decls.
1756 CheckCXXDefaultArguments(NewFD);
1757
1758 // An out-of-line member function declaration must also be a
1759 // definition (C++ [dcl.meaning]p1).
1760 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1761 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1762 << D.getCXXScopeSpec().getRange();
1763 InvalidDecl = true;
1764 }
1765 }
1766 return NewFD;
1767}
1768
Steve Naroff6594a702008-10-27 11:34:16 +00001769void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001770 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1771 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001772}
1773
Eli Friedmanc594b322008-05-20 13:48:25 +00001774bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1775 switch (Init->getStmtClass()) {
1776 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001777 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001778 return true;
1779 case Expr::ParenExprClass: {
1780 const ParenExpr* PE = cast<ParenExpr>(Init);
1781 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1782 }
1783 case Expr::CompoundLiteralExprClass:
1784 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001785 case Expr::DeclRefExprClass:
1786 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001787 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001788 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1789 if (VD->hasGlobalStorage())
1790 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001791 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001792 return true;
1793 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001794 if (isa<FunctionDecl>(D))
1795 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001796 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001797 return true;
1798 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001799 case Expr::MemberExprClass: {
1800 const MemberExpr *M = cast<MemberExpr>(Init);
1801 if (M->isArrow())
1802 return CheckAddressConstantExpression(M->getBase());
1803 return CheckAddressConstantExpressionLValue(M->getBase());
1804 }
1805 case Expr::ArraySubscriptExprClass: {
1806 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1807 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1808 return CheckAddressConstantExpression(ASE->getBase()) ||
1809 CheckArithmeticConstantExpression(ASE->getIdx());
1810 }
1811 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001812 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001813 return false;
1814 case Expr::UnaryOperatorClass: {
1815 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1816
1817 // C99 6.6p9
1818 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001819 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001820
Steve Naroff6594a702008-10-27 11:34:16 +00001821 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 return true;
1823 }
1824 }
1825}
1826
1827bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1828 switch (Init->getStmtClass()) {
1829 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001830 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001831 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001832 case Expr::ParenExprClass:
1833 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001834 case Expr::StringLiteralClass:
1835 case Expr::ObjCStringLiteralClass:
1836 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001837 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001838 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001839 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1840 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1841 Builtin::BI__builtin___CFStringMakeConstantString)
1842 return false;
1843
Steve Naroff6594a702008-10-27 11:34:16 +00001844 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001845 return true;
1846
Eli Friedmanc594b322008-05-20 13:48:25 +00001847 case Expr::UnaryOperatorClass: {
1848 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1849
1850 // C99 6.6p9
1851 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1852 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1853
1854 if (Exp->getOpcode() == UnaryOperator::Extension)
1855 return CheckAddressConstantExpression(Exp->getSubExpr());
1856
Steve Naroff6594a702008-10-27 11:34:16 +00001857 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001858 return true;
1859 }
1860 case Expr::BinaryOperatorClass: {
1861 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1862 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1863
1864 Expr *PExp = Exp->getLHS();
1865 Expr *IExp = Exp->getRHS();
1866 if (IExp->getType()->isPointerType())
1867 std::swap(PExp, IExp);
1868
1869 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1870 return CheckAddressConstantExpression(PExp) ||
1871 CheckArithmeticConstantExpression(IExp);
1872 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001873 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001874 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001875 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001876 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1877 // Check for implicit promotion
1878 if (SubExpr->getType()->isFunctionType() ||
1879 SubExpr->getType()->isArrayType())
1880 return CheckAddressConstantExpressionLValue(SubExpr);
1881 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001882
1883 // Check for pointer->pointer cast
1884 if (SubExpr->getType()->isPointerType())
1885 return CheckAddressConstantExpression(SubExpr);
1886
Eli Friedmanc3f07642008-08-25 20:46:57 +00001887 if (SubExpr->getType()->isIntegralType()) {
1888 // Check for the special-case of a pointer->int->pointer cast;
1889 // this isn't standard, but some code requires it. See
1890 // PR2720 for an example.
1891 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1892 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1893 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1894 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1895 if (IntWidth >= PointerWidth) {
1896 return CheckAddressConstantExpression(SubCast->getSubExpr());
1897 }
1898 }
1899 }
1900 }
1901 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001902 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001903 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001904
Steve Naroff6594a702008-10-27 11:34:16 +00001905 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001906 return true;
1907 }
1908 case Expr::ConditionalOperatorClass: {
1909 // FIXME: Should we pedwarn here?
1910 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1911 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001912 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001913 return true;
1914 }
1915 if (CheckArithmeticConstantExpression(Exp->getCond()))
1916 return true;
1917 if (Exp->getLHS() &&
1918 CheckAddressConstantExpression(Exp->getLHS()))
1919 return true;
1920 return CheckAddressConstantExpression(Exp->getRHS());
1921 }
1922 case Expr::AddrLabelExprClass:
1923 return false;
1924 }
1925}
1926
Eli Friedman4caf0552008-06-09 05:05:07 +00001927static const Expr* FindExpressionBaseAddress(const Expr* E);
1928
1929static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1930 switch (E->getStmtClass()) {
1931 default:
1932 return E;
1933 case Expr::ParenExprClass: {
1934 const ParenExpr* PE = cast<ParenExpr>(E);
1935 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1936 }
1937 case Expr::MemberExprClass: {
1938 const MemberExpr *M = cast<MemberExpr>(E);
1939 if (M->isArrow())
1940 return FindExpressionBaseAddress(M->getBase());
1941 return FindExpressionBaseAddressLValue(M->getBase());
1942 }
1943 case Expr::ArraySubscriptExprClass: {
1944 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1945 return FindExpressionBaseAddress(ASE->getBase());
1946 }
1947 case Expr::UnaryOperatorClass: {
1948 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1949
1950 if (Exp->getOpcode() == UnaryOperator::Deref)
1951 return FindExpressionBaseAddress(Exp->getSubExpr());
1952
1953 return E;
1954 }
1955 }
1956}
1957
1958static const Expr* FindExpressionBaseAddress(const Expr* E) {
1959 switch (E->getStmtClass()) {
1960 default:
1961 return E;
1962 case Expr::ParenExprClass: {
1963 const ParenExpr* PE = cast<ParenExpr>(E);
1964 return FindExpressionBaseAddress(PE->getSubExpr());
1965 }
1966 case Expr::UnaryOperatorClass: {
1967 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1968
1969 // C99 6.6p9
1970 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1971 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1972
1973 if (Exp->getOpcode() == UnaryOperator::Extension)
1974 return FindExpressionBaseAddress(Exp->getSubExpr());
1975
1976 return E;
1977 }
1978 case Expr::BinaryOperatorClass: {
1979 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1980
1981 Expr *PExp = Exp->getLHS();
1982 Expr *IExp = Exp->getRHS();
1983 if (IExp->getType()->isPointerType())
1984 std::swap(PExp, IExp);
1985
1986 return FindExpressionBaseAddress(PExp);
1987 }
1988 case Expr::ImplicitCastExprClass: {
1989 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1990
1991 // Check for implicit promotion
1992 if (SubExpr->getType()->isFunctionType() ||
1993 SubExpr->getType()->isArrayType())
1994 return FindExpressionBaseAddressLValue(SubExpr);
1995
1996 // Check for pointer->pointer cast
1997 if (SubExpr->getType()->isPointerType())
1998 return FindExpressionBaseAddress(SubExpr);
1999
2000 // We assume that we have an arithmetic expression here;
2001 // if we don't, we'll figure it out later
2002 return 0;
2003 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002004 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002005 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2006
2007 // Check for pointer->pointer cast
2008 if (SubExpr->getType()->isPointerType())
2009 return FindExpressionBaseAddress(SubExpr);
2010
2011 // We assume that we have an arithmetic expression here;
2012 // if we don't, we'll figure it out later
2013 return 0;
2014 }
2015 }
2016}
2017
Anders Carlsson51fe9962008-11-22 21:04:56 +00002018bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002019 switch (Init->getStmtClass()) {
2020 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002021 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002022 return true;
2023 case Expr::ParenExprClass: {
2024 const ParenExpr* PE = cast<ParenExpr>(Init);
2025 return CheckArithmeticConstantExpression(PE->getSubExpr());
2026 }
2027 case Expr::FloatingLiteralClass:
2028 case Expr::IntegerLiteralClass:
2029 case Expr::CharacterLiteralClass:
2030 case Expr::ImaginaryLiteralClass:
2031 case Expr::TypesCompatibleExprClass:
2032 case Expr::CXXBoolLiteralExprClass:
2033 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002034 case Expr::CallExprClass:
2035 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002036 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002037
2038 // Allow any constant foldable calls to builtins.
2039 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002040 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002041
Steve Naroff6594a702008-10-27 11:34:16 +00002042 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002043 return true;
2044 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002045 case Expr::DeclRefExprClass:
2046 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002047 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2048 if (isa<EnumConstantDecl>(D))
2049 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002050 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002051 return true;
2052 }
2053 case Expr::CompoundLiteralExprClass:
2054 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2055 // but vectors are allowed to be magic.
2056 if (Init->getType()->isVectorType())
2057 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002058 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002059 return true;
2060 case Expr::UnaryOperatorClass: {
2061 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2062
2063 switch (Exp->getOpcode()) {
2064 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2065 // See C99 6.6p3.
2066 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002067 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002068 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002069 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002070 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2071 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002072 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002073 return true;
2074 case UnaryOperator::Extension:
2075 case UnaryOperator::LNot:
2076 case UnaryOperator::Plus:
2077 case UnaryOperator::Minus:
2078 case UnaryOperator::Not:
2079 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2080 }
2081 }
Sebastian Redl05189992008-11-11 17:56:53 +00002082 case Expr::SizeOfAlignOfExprClass: {
2083 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002084 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002085 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002086 return false;
2087 // alignof always evaluates to a constant.
2088 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002089 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002090 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002091 return true;
2092 }
2093 return false;
2094 }
2095 case Expr::BinaryOperatorClass: {
2096 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2097
2098 if (Exp->getLHS()->getType()->isArithmeticType() &&
2099 Exp->getRHS()->getType()->isArithmeticType()) {
2100 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2101 CheckArithmeticConstantExpression(Exp->getRHS());
2102 }
2103
Eli Friedman4caf0552008-06-09 05:05:07 +00002104 if (Exp->getLHS()->getType()->isPointerType() &&
2105 Exp->getRHS()->getType()->isPointerType()) {
2106 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2107 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2108
2109 // Only allow a null (constant integer) base; we could
2110 // allow some additional cases if necessary, but this
2111 // is sufficient to cover offsetof-like constructs.
2112 if (!LHSBase && !RHSBase) {
2113 return CheckAddressConstantExpression(Exp->getLHS()) ||
2114 CheckAddressConstantExpression(Exp->getRHS());
2115 }
2116 }
2117
Steve Naroff6594a702008-10-27 11:34:16 +00002118 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002119 return true;
2120 }
2121 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002122 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002123 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002124 if (SubExpr->getType()->isArithmeticType())
2125 return CheckArithmeticConstantExpression(SubExpr);
2126
Eli Friedmanb529d832008-09-02 09:37:00 +00002127 if (SubExpr->getType()->isPointerType()) {
2128 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2129 // If the pointer has a null base, this is an offsetof-like construct
2130 if (!Base)
2131 return CheckAddressConstantExpression(SubExpr);
2132 }
2133
Steve Naroff6594a702008-10-27 11:34:16 +00002134 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002135 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002136 }
2137 case Expr::ConditionalOperatorClass: {
2138 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002139
2140 // If GNU extensions are disabled, we require all operands to be arithmetic
2141 // constant expressions.
2142 if (getLangOptions().NoExtensions) {
2143 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2144 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2145 CheckArithmeticConstantExpression(Exp->getRHS());
2146 }
2147
2148 // Otherwise, we have to emulate some of the behavior of fold here.
2149 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2150 // because it can constant fold things away. To retain compatibility with
2151 // GCC code, we see if we can fold the condition to a constant (which we
2152 // should always be able to do in theory). If so, we only require the
2153 // specified arm of the conditional to be a constant. This is a horrible
2154 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002155 Expr::EvalResult EvalResult;
2156 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2157 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002158 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002159 // won't be able to either. Use it to emit the diagnostic though.
2160 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002161 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002162 return Res;
2163 }
2164
2165 // Verify that the side following the condition is also a constant.
2166 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002167 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002168 std::swap(TrueSide, FalseSide);
2169
2170 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002171 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002172
2173 // Okay, the evaluated side evaluates to a constant, so we accept this.
2174 // Check to see if the other side is obviously not a constant. If so,
2175 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002176 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002177 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002178 diag::ext_typecheck_expression_not_constant_but_accepted)
2179 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002180 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002181 }
2182 }
2183}
2184
2185bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002186 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2187 Init = DIE->getInit();
2188
Nuno Lopes9a979c32008-07-07 16:46:50 +00002189 Init = Init->IgnoreParens();
2190
Nate Begeman59b5da62009-01-18 03:20:47 +00002191 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002192 return false;
2193
Eli Friedmanc594b322008-05-20 13:48:25 +00002194 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2195 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2196 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2197
Nuno Lopes9a979c32008-07-07 16:46:50 +00002198 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2199 return CheckForConstantInitializer(e->getInitializer(), DclT);
2200
Eli Friedmanc594b322008-05-20 13:48:25 +00002201 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2202 unsigned numInits = Exp->getNumInits();
2203 for (unsigned i = 0; i < numInits; i++) {
2204 // FIXME: Need to get the type of the declaration for C++,
2205 // because it could be a reference?
2206 if (CheckForConstantInitializer(Exp->getInit(i),
2207 Exp->getInit(i)->getType()))
2208 return true;
2209 }
2210 return false;
2211 }
2212
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002213 // FIXME: We can probably remove some of this code below, now that
2214 // Expr::Evaluate is doing the heavy lifting for scalars.
2215
Eli Friedmanc594b322008-05-20 13:48:25 +00002216 if (Init->isNullPointerConstant(Context))
2217 return false;
2218 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002219 QualType InitTy = Context.getCanonicalType(Init->getType())
2220 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002221 if (InitTy == Context.BoolTy) {
2222 // Special handling for pointers implicitly cast to bool;
2223 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2224 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2225 Expr* SubE = ICE->getSubExpr();
2226 if (SubE->getType()->isPointerType() ||
2227 SubE->getType()->isArrayType() ||
2228 SubE->getType()->isFunctionType()) {
2229 return CheckAddressConstantExpression(Init);
2230 }
2231 }
2232 } else if (InitTy->isIntegralType()) {
2233 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002234 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002235 SubE = CE->getSubExpr();
2236 // Special check for pointer cast to int; we allow as an extension
2237 // an address constant cast to an integer if the integer
2238 // is of an appropriate width (this sort of code is apparently used
2239 // in some places).
2240 // FIXME: Add pedwarn?
2241 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2242 if (SubE && (SubE->getType()->isPointerType() ||
2243 SubE->getType()->isArrayType() ||
2244 SubE->getType()->isFunctionType())) {
2245 unsigned IntWidth = Context.getTypeSize(Init->getType());
2246 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2247 if (IntWidth >= PointerWidth)
2248 return CheckAddressConstantExpression(Init);
2249 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002250 }
2251
2252 return CheckArithmeticConstantExpression(Init);
2253 }
2254
2255 if (Init->getType()->isPointerType())
2256 return CheckAddressConstantExpression(Init);
2257
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002258 // An array type at the top level that isn't an init-list must
2259 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002260 if (Init->getType()->isArrayType())
2261 return false;
2262
Nuno Lopes73419bf2008-09-01 18:42:41 +00002263 if (Init->getType()->isFunctionType())
2264 return false;
2265
Steve Naroff8af6a452008-10-02 17:12:56 +00002266 // Allow block exprs at top level.
2267 if (Init->getType()->isBlockPointerType())
2268 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002269
2270 // GCC cast to union extension
2271 // note: the validity of the cast expr is checked by CheckCastTypes()
2272 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2273 QualType T = C->getType();
2274 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2275 }
2276
Steve Naroff6594a702008-10-27 11:34:16 +00002277 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002278 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002279}
2280
Sebastian Redl798d1192008-12-13 16:23:55 +00002281void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002282 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2283}
2284
2285/// AddInitializerToDecl - Adds the initializer Init to the
2286/// declaration dcl. If DirectInit is true, this is C++ direct
2287/// initialization rather than copy initialization.
2288void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002289 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002290 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002291 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002292
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002293 // If there is no declaration, there was an error parsing it. Just ignore
2294 // the initializer.
2295 if (RealDecl == 0) {
2296 delete Init;
2297 return;
2298 }
Steve Naroffbb204692007-09-12 14:07:44 +00002299
Steve Naroff410e3e22007-09-12 20:13:48 +00002300 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2301 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002302 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002303 RealDecl->setInvalidDecl();
2304 return;
2305 }
Steve Naroffbb204692007-09-12 14:07:44 +00002306 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002307 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002308 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002309 if (VDecl->isBlockVarDecl()) {
2310 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002311 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002312 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002313 VDecl->setInvalidDecl();
2314 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002315 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002316 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002317 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002318
2319 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2320 if (!getLangOptions().CPlusPlus) {
2321 if (SC == VarDecl::Static) // C99 6.7.8p4.
2322 CheckForConstantInitializer(Init, DclT);
2323 }
Steve Naroffbb204692007-09-12 14:07:44 +00002324 }
Steve Naroff248a7532008-04-15 22:42:06 +00002325 } else if (VDecl->isFileVarDecl()) {
2326 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002327 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002328 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002329 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002330 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002331 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002332
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002333 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2334 if (!getLangOptions().CPlusPlus) {
2335 // C99 6.7.8p4. All file scoped initializers need to be constant.
2336 CheckForConstantInitializer(Init, DclT);
2337 }
Steve Naroffbb204692007-09-12 14:07:44 +00002338 }
2339 // If the type changed, it means we had an incomplete type that was
2340 // completed by the initializer. For example:
2341 // int ary[] = { 1, 3, 5 };
2342 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002343 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002344 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002345 Init->setType(DclT);
2346 }
Steve Naroffbb204692007-09-12 14:07:44 +00002347
2348 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002349 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002350 return;
2351}
2352
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002353void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2354 Decl *RealDecl = static_cast<Decl *>(dcl);
2355
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002356 // If there is no declaration, there was an error parsing it. Just ignore it.
2357 if (RealDecl == 0)
2358 return;
2359
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002360 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2361 QualType Type = Var->getType();
2362 // C++ [dcl.init.ref]p3:
2363 // The initializer can be omitted for a reference only in a
2364 // parameter declaration (8.3.5), in the declaration of a
2365 // function return type, in the declaration of a class member
2366 // within its class declaration (9.2), and where the extern
2367 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002368 if (Type->isReferenceType() &&
2369 Var->getStorageClass() != VarDecl::Extern &&
2370 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002371 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002372 << Var->getDeclName()
2373 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002374 Var->setInvalidDecl();
2375 return;
2376 }
2377
2378 // C++ [dcl.init]p9:
2379 //
2380 // If no initializer is specified for an object, and the object
2381 // is of (possibly cv-qualified) non-POD class type (or array
2382 // thereof), the object shall be default-initialized; if the
2383 // object is of const-qualified type, the underlying class type
2384 // shall have a user-declared default constructor.
2385 if (getLangOptions().CPlusPlus) {
2386 QualType InitType = Type;
2387 if (const ArrayType *Array = Context.getAsArrayType(Type))
2388 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002389 if (Var->getStorageClass() != VarDecl::Extern &&
2390 Var->getStorageClass() != VarDecl::PrivateExtern &&
2391 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002392 const CXXConstructorDecl *Constructor
2393 = PerformInitializationByConstructor(InitType, 0, 0,
2394 Var->getLocation(),
2395 SourceRange(Var->getLocation(),
2396 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002397 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002398 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002399 if (!Constructor)
2400 Var->setInvalidDecl();
2401 }
2402 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002403
Douglas Gregor818ce482008-10-29 13:50:18 +00002404#if 0
2405 // FIXME: Temporarily disabled because we are not properly parsing
2406 // linkage specifications on declarations, e.g.,
2407 //
2408 // extern "C" const CGPoint CGPointerZero;
2409 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002410 // C++ [dcl.init]p9:
2411 //
2412 // If no initializer is specified for an object, and the
2413 // object is of (possibly cv-qualified) non-POD class type (or
2414 // array thereof), the object shall be default-initialized; if
2415 // the object is of const-qualified type, the underlying class
2416 // type shall have a user-declared default
2417 // constructor. Otherwise, if no initializer is specified for
2418 // an object, the object and its subobjects, if any, have an
2419 // indeterminate initial value; if the object or any of its
2420 // subobjects are of const-qualified type, the program is
2421 // ill-formed.
2422 //
2423 // This isn't technically an error in C, so we don't diagnose it.
2424 //
2425 // FIXME: Actually perform the POD/user-defined default
2426 // constructor check.
2427 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002428 Context.getCanonicalType(Type).isConstQualified() &&
2429 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002430 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2431 << Var->getName()
2432 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002433#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002434 }
2435}
2436
Reid Spencer5f016e22007-07-11 17:01:13 +00002437/// The declarators are chained together backwards, reverse the list.
2438Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2439 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002440 Decl *GroupDecl = static_cast<Decl*>(group);
2441 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002442 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002443
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002444 Decl *Group = dyn_cast<Decl>(GroupDecl);
2445 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002446 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002448 else { // reverse the list.
2449 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002450 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002451 Group->setNextDeclarator(NewGroup);
2452 NewGroup = Group;
2453 Group = Next;
2454 }
2455 }
2456 // Perform semantic analysis that depends on having fully processed both
2457 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002458 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002459 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2460 if (!IDecl)
2461 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002462 QualType T = IDecl->getType();
2463
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002464 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002465 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002466
2467 // FIXME: This won't give the correct result for
2468 // int a[10][n];
2469 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002470 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002471 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2472 SizeRange;
2473
Eli Friedmanc5773c42008-02-15 18:16:39 +00002474 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002475 } else {
2476 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2477 // static storage duration, it shall not have a variable length array.
2478 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002479 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2480 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002481 IDecl->setInvalidDecl();
2482 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002483 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2484 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002485 IDecl->setInvalidDecl();
2486 }
2487 }
2488 } else if (T->isVariablyModifiedType()) {
2489 if (IDecl->isFileVarDecl()) {
2490 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2491 IDecl->setInvalidDecl();
2492 } else {
2493 if (IDecl->getStorageClass() == VarDecl::Extern) {
2494 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2495 IDecl->setInvalidDecl();
2496 }
Steve Naroffbb204692007-09-12 14:07:44 +00002497 }
2498 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002499
Steve Naroffbb204692007-09-12 14:07:44 +00002500 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2501 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002502 if (IDecl->isBlockVarDecl() &&
2503 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002504 if (!IDecl->isInvalidDecl() &&
2505 DiagnoseIncompleteType(IDecl->getLocation(), T,
2506 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002507 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002508 }
2509 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2510 // object that has file scope without an initializer, and without a
2511 // storage-class specifier or with the storage-class specifier "static",
2512 // constitutes a tentative definition. Note: A tentative definition with
2513 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002514 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002515 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002516 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2517 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002518 } else if (!IDecl->isInvalidDecl() &&
2519 DiagnoseIncompleteType(IDecl->getLocation(), T,
2520 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002521 // C99 6.9.2p3: If the declaration of an identifier for an object is
2522 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2523 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002524 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002525 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002526 if (IDecl->isFileVarDecl())
2527 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 }
2529 return NewGroup;
2530}
Steve Naroffe1223f72007-08-28 03:03:08 +00002531
Chris Lattner04421082008-04-08 04:40:51 +00002532/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2533/// to introduce parameters into function prototype scope.
2534Sema::DeclTy *
2535Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002536 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002537
Chris Lattner04421082008-04-08 04:40:51 +00002538 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002539 VarDecl::StorageClass StorageClass = VarDecl::None;
2540 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2541 StorageClass = VarDecl::Register;
2542 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002543 Diag(DS.getStorageClassSpecLoc(),
2544 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002545 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002546 }
2547 if (DS.isThreadSpecified()) {
2548 Diag(DS.getThreadSpecLoc(),
2549 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002550 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002551 }
2552
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002553 // Check that there are no default arguments inside the type of this
2554 // parameter (C++ only).
2555 if (getLangOptions().CPlusPlus)
2556 CheckExtraCXXDefaultArguments(D);
2557
Chris Lattner04421082008-04-08 04:40:51 +00002558 // In this context, we *do not* check D.getInvalidType(). If the declarator
2559 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2560 // though it will not reflect the user specified type.
2561 QualType parmDeclType = GetTypeForDeclarator(D, S);
2562
2563 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2564
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2566 // Can this happen for params? We already checked that they don't conflict
2567 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002568 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002569 if (II) {
2570 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2571 if (PrevDecl->isTemplateParameter()) {
2572 // Maybe we will complain about the shadowed template parameter.
2573 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2574 // Just pretend that we didn't see the previous declaration.
2575 PrevDecl = 0;
2576 } else if (S->isDeclScope(PrevDecl)) {
2577 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002578
Chris Lattnercf79b012009-01-21 02:38:50 +00002579 // Recover by removing the name
2580 II = 0;
2581 D.SetIdentifier(0, D.getIdentifierLoc());
2582 }
Chris Lattner04421082008-04-08 04:40:51 +00002583 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002584 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002585
2586 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2587 // Doing the promotion here has a win and a loss. The win is the type for
2588 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2589 // code generator). The loss is the orginal type isn't preserved. For example:
2590 //
2591 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2592 // int blockvardecl[5];
2593 // sizeof(parmvardecl); // size == 4
2594 // sizeof(blockvardecl); // size == 20
2595 // }
2596 //
2597 // For expressions, all implicit conversions are captured using the
2598 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2599 //
2600 // FIXME: If a source translation tool needs to see the original type, then
2601 // we need to consider storing both types (in ParmVarDecl)...
2602 //
Chris Lattnere6327742008-04-02 05:18:44 +00002603 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002604 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002605 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002606 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002607 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002608
Chris Lattner04421082008-04-08 04:40:51 +00002609 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2610 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002611 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002612 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002613
Chris Lattner04421082008-04-08 04:40:51 +00002614 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002615 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002616
Douglas Gregor584049d2008-12-15 23:53:10 +00002617 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2618 if (D.getCXXScopeSpec().isSet()) {
2619 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2620 << D.getCXXScopeSpec().getRange();
2621 New->setInvalidDecl();
2622 }
2623
Douglas Gregor44b43212008-12-11 16:49:14 +00002624 // Add the parameter declaration into this scope.
2625 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002626 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002627 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002628
Chris Lattner3ff30c82008-06-29 00:02:00 +00002629 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002630 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002631
Reid Spencer5f016e22007-07-11 17:01:13 +00002632}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002633
Douglas Gregorbe109b32009-01-23 16:23:13 +00002634void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2636 "Not a function declarator!");
2637 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002638
Reid Spencer5f016e22007-07-11 17:01:13 +00002639 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2640 // for a K&R function.
2641 if (!FTI.hasPrototype) {
2642 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002643 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002644 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2645 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 // Implicitly declare the argument as type 'int' for lack of a better
2647 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002648 DeclSpec DS;
2649 const char* PrevSpec; // unused
2650 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2651 PrevSpec);
2652 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2653 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002654 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 }
2656 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002657 }
2658}
2659
2660Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2661 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2662 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2663 "Not a function declarator!");
2664 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2665
2666 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002667 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 }
2669
Douglas Gregor584049d2008-12-15 23:53:10 +00002670 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002671
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002672 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002673 ActOnDeclarator(ParentScope, D, 0,
2674 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002675}
2676
2677Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2678 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002679 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002680
2681 // See if this is a redefinition.
2682 const FunctionDecl *Definition;
2683 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002684 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002685 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002686 }
2687
Douglas Gregor44b43212008-12-11 16:49:14 +00002688 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002689
Chris Lattner04421082008-04-08 04:40:51 +00002690 // Check the validity of our function parameters
2691 CheckParmsForFunctionDef(FD);
2692
2693 // Introduce our parameters into the function scope
2694 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2695 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002696 Param->setOwningFunction(FD);
2697
Chris Lattner04421082008-04-08 04:40:51 +00002698 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002699 if (Param->getIdentifier())
2700 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 }
Chris Lattner04421082008-04-08 04:40:51 +00002702
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002703 // Checking attributes of current function definition
2704 // dllimport attribute.
2705 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2706 // dllimport attribute cannot be applied to definition.
2707 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2708 Diag(FD->getLocation(),
2709 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2710 << "dllimport";
2711 FD->setInvalidDecl();
2712 return FD;
2713 } else {
2714 // If a symbol previously declared dllimport is later defined, the
2715 // attribute is ignored in subsequent references, and a warning is
2716 // emitted.
2717 Diag(FD->getLocation(),
2718 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2719 << FD->getNameAsCString() << "dllimport";
2720 }
2721 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 return FD;
2723}
2724
Sebastian Redl798d1192008-12-13 16:23:55 +00002725Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002726 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002727 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002728 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002729 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002730 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002731 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002732 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002733 } else
2734 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002735 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 // Verify and clean out per-function state.
2737
2738 // Check goto/label use.
2739 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2740 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2741 // Verify that we have no forward references left. If so, there was a goto
2742 // or address of a label taken, but no definition of it. Label fwd
2743 // definitions are indicated with a null substmt.
2744 if (I->second->getSubStmt() == 0) {
2745 LabelStmt *L = I->second;
2746 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002747 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002748
2749 // At this point, we have gotos that use the bogus label. Stitch it into
2750 // the function body so that they aren't leaked and that the AST is well
2751 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002752 if (Body) {
2753 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002754 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002755 } else {
2756 // The whole function wasn't parsed correctly, just delete this.
2757 delete L;
2758 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 }
2760 }
2761 LabelMap.clear();
2762
Steve Naroffd6d054d2007-11-11 23:20:51 +00002763 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002764}
2765
Reid Spencer5f016e22007-07-11 17:01:13 +00002766/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2767/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002768NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2769 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002770 // Extension in C99. Legal in C90, but warn about it.
2771 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002772 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002773 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002774 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002775
2776 // FIXME: handle stuff like:
2777 // void foo() { extern float X(); }
2778 // void bar() { X(); } <-- implicit decl for X in another scope.
2779
2780 // Set a Declarator for the implicit definition: int foo();
2781 const char *Dummy;
2782 DeclSpec DS;
2783 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2784 Error = Error; // Silence warning.
2785 assert(!Error && "Error setting up implicit decl!");
2786 Declarator D(DS, Declarator::BlockContext);
Chris Lattner5af2f352009-01-20 19:11:22 +00002787 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 D.SetIdentifier(&II, Loc);
2789
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002790 // Insert this function into translation-unit scope.
2791
2792 DeclContext *PrevDC = CurContext;
2793 CurContext = Context.getTranslationUnitDecl();
2794
Steve Naroffe2ef8152008-04-04 14:32:09 +00002795 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002796 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002797 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002798
2799 CurContext = PrevDC;
2800
Steve Naroffe2ef8152008-04-04 14:32:09 +00002801 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002802}
2803
2804
Chris Lattner41af0932007-11-14 06:34:38 +00002805TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002806 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002807 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002808 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002809
2810 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002811 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2812 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002813 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002814 T);
2815 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002816 if (D.getInvalidType())
2817 NewTD->setInvalidDecl();
2818 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002819}
2820
Steve Naroff08d92e42007-09-15 18:49:24 +00002821/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002822/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002823/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002824/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002825Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002826 SourceLocation KWLoc, const CXXScopeSpec &SS,
2827 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002828 AttributeList *Attr,
2829 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002830 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 assert((Name != 0 || TK == TK_Definition) &&
2832 "Nameless record must be a definition!");
2833
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002834 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002835 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002837 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2838 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2839 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2840 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 }
2842
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002843 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002844 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002845 DeclContext *LexicalContext = CurContext;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002846 Decl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002847
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002848 bool Invalid = false;
2849
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002850 if (Name && SS.isNotEmpty()) {
2851 // We have a nested-name tag ('struct foo::bar').
2852
2853 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002854 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002855 Name = 0;
2856 goto CreateNewDecl;
2857 }
2858
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002859 DC = static_cast<DeclContext*>(SS.getScopeRep());
2860 // Look-up name inside 'foo::'.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002861 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2862 .getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002863
2864 // A tag 'foo::bar' must already exist.
2865 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002866 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002867 Name = 0;
2868 goto CreateNewDecl;
2869 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002870 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002871 // If this is a named struct, check to see if there was a previous forward
2872 // declaration or definition.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002873 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
Chris Lattnercf79b012009-01-21 02:38:50 +00002874 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002875
2876 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2877 // FIXME: This makes sure that we ignore the contexts associated
2878 // with C structs, unions, and enums when looking for a matching
2879 // tag declaration or definition. See the similar lookup tweak
2880 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002881 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2882 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002883 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002884 }
2885
Douglas Gregorf57172b2008-12-08 18:40:42 +00002886 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002887 // Maybe we will complain about the shadowed template parameter.
2888 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2889 // Just pretend that we didn't see the previous declaration.
2890 PrevDecl = 0;
2891 }
2892
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002893 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002894 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2895 "unexpected Decl type");
2896 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002897 // If this is a use of a previous tag, or if the tag is already declared
2898 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002899 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002900 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002901 // Make sure that this wasn't declared as an enum and now used as a
2902 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002903 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002904 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002905 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002906 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002907 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002908 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002909 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002910 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002911 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002912
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002913 // FIXME: In the future, return a variant or some other clue
2914 // for the consumer of this Decl to know it doesn't own it.
2915 // For our current ASTs this shouldn't be a problem, but will
2916 // need to be changed with DeclGroups.
2917 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002918 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002919
2920 // Diagnose attempts to redefine a tag.
2921 if (TK == TK_Definition) {
2922 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2923 Diag(NameLoc, diag::err_redefinition) << Name;
2924 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002925 // If this is a redefinition, recover by making this
2926 // struct be anonymous, which will make any later
2927 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002928 Name = 0;
2929 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002930 Invalid = true;
2931 } else {
2932 // If the type is currently being defined, complain
2933 // about a nested redefinition.
2934 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2935 if (Tag->isBeingDefined()) {
2936 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2937 Diag(PrevTagDecl->getLocation(),
2938 diag::note_previous_definition);
2939 Name = 0;
2940 PrevDecl = 0;
2941 Invalid = true;
2942 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002943 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002944
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002945 // Okay, this is definition of a previously declared or referenced
2946 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002947 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002948 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002949 // If we get here we have (another) forward declaration or we
2950 // have a definition. Just create a new decl.
2951 } else {
2952 // If we get here, this is a definition of a new tag type in a nested
2953 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2954 // new decl/type. We set PrevDecl to NULL so that the entities
2955 // have distinct types.
2956 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002957 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002958 // If we get here, we're going to create a new Decl. If PrevDecl
2959 // is non-NULL, it's a definition of the tag declared by
2960 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002961 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002962 // PrevDecl is a namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002963 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002964 // The tag name clashes with a namespace name, issue an error and
2965 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002966 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002967 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002968 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002969 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002970 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002971 } else {
2972 // The existing declaration isn't relevant to us; we're in a
2973 // new scope, so clear out the previous declaration.
2974 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002975 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002976 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002977 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2978 (Kind != TagDecl::TK_enum)) {
2979 // C++ [basic.scope.pdecl]p5:
2980 // -- for an elaborated-type-specifier of the form
2981 //
2982 // class-key identifier
2983 //
2984 // if the elaborated-type-specifier is used in the
2985 // decl-specifier-seq or parameter-declaration-clause of a
2986 // function defined in namespace scope, the identifier is
2987 // declared as a class-name in the namespace that contains
2988 // the declaration; otherwise, except as a friend
2989 // declaration, the identifier is declared in the smallest
2990 // non-class, non-function-prototype scope that contains the
2991 // declaration.
2992 //
2993 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2994 // C structs and unions.
2995
2996 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002997 // FIXME: We would like to maintain the current DeclContext as the
2998 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002999 while (DC->isRecord())
3000 DC = DC->getParent();
3001 LexicalContext = DC;
3002
3003 // Find the scope where we'll be declaring the tag.
3004 while (S->isClassScope() ||
3005 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003006 ((S->getFlags() & Scope::DeclScope) == 0) ||
3007 (S->getEntity() &&
3008 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003009 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003011
Chris Lattnercc98eac2008-12-17 07:13:27 +00003012CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003013
3014 // If there is an identifier, use the location of the identifier as the
3015 // location of the decl, otherwise use the location of the struct/union
3016 // keyword.
3017 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3018
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003019 // Otherwise, create a new declaration. If there is a previous
3020 // declaration of the same entity, the two will be linked via
3021 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003023
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003024 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3026 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003027 New = EnumDecl::Create(Context, DC, Loc, Name,
3028 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 // If this is an undefined enum, warn.
3030 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003031 } else {
3032 // struct/union/class
3033
Reid Spencer5f016e22007-07-11 17:01:13 +00003034 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3035 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003036 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003037 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003038 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3039 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003040 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003041 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3042 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003043 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003044
3045 if (Kind != TagDecl::TK_enum) {
3046 // Handle #pragma pack: if the #pragma pack stack has non-default
3047 // alignment, make up a packed attribute for this decl. These
3048 // attributes are checked when the ASTContext lays out the
3049 // structure.
3050 //
3051 // It is important for implementing the correct semantics that this
3052 // happen here (in act on tag decl). The #pragma pack stack is
3053 // maintained as a result of parser callbacks which can occur at
3054 // many points during the parsing of a struct declaration (because
3055 // the #pragma tokens are effectively skipped over during the
3056 // parsing of the struct).
3057 if (unsigned Alignment = PackContext.getAlignment())
3058 New->addAttr(new PackedAttr(Alignment * 8));
3059 }
3060
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003061 if (Invalid)
3062 New->setInvalidDecl();
3063
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003064 if (Attr)
3065 ProcessDeclAttributeList(New, Attr);
3066
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003067 // If we're declaring or defining a tag in function prototype scope
3068 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003069 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3070 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3071
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003072 // Set the lexical context. If the tag has a C++ scope specifier, the
3073 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003074 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003075
3076 if (TK == TK_Definition)
3077 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003078
3079 // If this has an identifier, add it to the scope stack.
3080 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003081 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003082
3083 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003084 if (LexicalContext != CurContext) {
3085 // FIXME: PushOnScopeChains should not rely on CurContext!
3086 DeclContext *OldContext = CurContext;
3087 CurContext = LexicalContext;
3088 PushOnScopeChains(New, S);
3089 CurContext = OldContext;
3090 } else
3091 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003092 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003093 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003095
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 return New;
3097}
3098
Douglas Gregor72de6672009-01-08 20:45:30 +00003099void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3100 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3101
3102 // Enter the tag context.
3103 PushDeclContext(S, Tag);
3104
3105 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3106 FieldCollector->StartClass();
3107
3108 if (Record->getIdentifier()) {
3109 // C++ [class]p2:
3110 // [...] The class-name is also inserted into the scope of the
3111 // class itself; this is known as the injected-class-name. For
3112 // purposes of access checking, the injected-class-name is treated
3113 // as if it were a public member name.
3114 RecordDecl *InjectedClassName
3115 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3116 CurContext, Record->getLocation(),
3117 Record->getIdentifier(), Record);
3118 InjectedClassName->setImplicit();
3119 PushOnScopeChains(InjectedClassName, S);
3120 }
3121 }
3122}
3123
3124void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3125 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3126
3127 if (isa<CXXRecordDecl>(Tag))
3128 FieldCollector->FinishClass();
3129
3130 // Exit this scope of this tag's definition.
3131 PopDeclContext();
3132
3133 // Notify the consumer that we've defined a tag.
3134 Consumer.HandleTagDeclDefinition(Tag);
3135}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003136
Chris Lattner1d353ba2008-11-12 21:17:48 +00003137/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3138/// types into constant array types in certain situations which would otherwise
3139/// be errors (for GCC compatibility).
3140static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3141 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003142 // This method tries to turn a variable array into a constant
3143 // array even when the size isn't an ICE. This is necessary
3144 // for compatibility with code that depends on gcc's buggy
3145 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003146 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3147 if (!VLATy) return QualType();
3148
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003149 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003150 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003151 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003152 return QualType();
3153
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003154 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3155 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003156 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3157 return Context.getConstantArrayType(VLATy->getElementType(),
3158 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003159 return QualType();
3160}
3161
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003162bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003163 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003164 // FIXME: 6.7.2.1p4 - verify the field type.
3165
3166 llvm::APSInt Value;
3167 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3168 return true;
3169
Chris Lattnercd087072008-12-12 04:56:04 +00003170 // Zero-width bitfield is ok for anonymous field.
3171 if (Value == 0 && FieldName)
3172 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3173
3174 if (Value.isNegative())
3175 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003176
3177 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3178 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003179 if (TypeSize && Value.getZExtValue() > TypeSize)
3180 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3181 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003182
3183 return false;
3184}
3185
Steve Naroff08d92e42007-09-15 18:49:24 +00003186/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003187/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003188Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003189 SourceLocation DeclStart,
3190 Declarator &D, ExprTy *BitfieldWidth) {
3191 IdentifierInfo *II = D.getIdentifier();
3192 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003193 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003194 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003195 if (II) Loc = D.getIdentifierLoc();
3196
3197 // FIXME: Unnamed fields can be handled in various different ways, for
3198 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003199
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003201 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3202 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003203
Reid Spencer5f016e22007-07-11 17:01:13 +00003204 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3205 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003206 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003207 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003208 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003209 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003210 T = FixedTy;
3211 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003212 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003213 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003214 InvalidDecl = true;
3215 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003216 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003217
3218 if (BitWidth) {
3219 if (VerifyBitField(Loc, II, T, BitWidth))
3220 InvalidDecl = true;
3221 } else {
3222 // Not a bitfield.
3223
3224 // validate II.
3225
3226 }
3227
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003229 FieldDecl *NewFD;
3230
Douglas Gregor44b43212008-12-11 16:49:14 +00003231 NewFD = FieldDecl::Create(Context, Record,
3232 Loc, II, T, BitWidth,
3233 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003234 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003235
Douglas Gregor72de6672009-01-08 20:45:30 +00003236 if (II) {
3237 Decl *PrevDecl
Steve Naroff939837f2009-01-28 15:51:12 +00003238 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003239 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3240 && !isa<TagDecl>(PrevDecl)) {
3241 Diag(Loc, diag::err_duplicate_member) << II;
3242 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3243 NewFD->setInvalidDecl();
3244 Record->setInvalidDecl();
3245 }
3246 }
3247
Sebastian Redl64b45f72009-01-05 20:52:13 +00003248 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003249 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003250 if (!T->isPODType())
3251 cast<CXXRecordDecl>(Record)->setPOD(false);
3252 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003253
Chris Lattner3ff30c82008-06-29 00:02:00 +00003254 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003255
Steve Naroff5912a352007-08-28 20:14:24 +00003256 if (D.getInvalidType() || InvalidDecl)
3257 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003258
Douglas Gregor72de6672009-01-08 20:45:30 +00003259 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003260 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003261 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003262 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003263
Steve Naroff5912a352007-08-28 20:14:24 +00003264 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003265}
3266
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003267/// TranslateIvarVisibility - Translate visibility from a token ID to an
3268/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003269static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003270TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003271 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003272 default: assert(0 && "Unknown visitibility kind");
3273 case tok::objc_private: return ObjCIvarDecl::Private;
3274 case tok::objc_public: return ObjCIvarDecl::Public;
3275 case tok::objc_protected: return ObjCIvarDecl::Protected;
3276 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003277 }
3278}
3279
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003280/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3281/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003282Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003283 SourceLocation DeclStart,
3284 Declarator &D, ExprTy *BitfieldWidth,
3285 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003286
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003287 IdentifierInfo *II = D.getIdentifier();
3288 Expr *BitWidth = (Expr*)BitfieldWidth;
3289 SourceLocation Loc = DeclStart;
3290 if (II) Loc = D.getIdentifierLoc();
3291
3292 // FIXME: Unnamed fields can be handled in various different ways, for
3293 // example, unnamed unions inject all members into the struct namespace!
3294
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003295 QualType T = GetTypeForDeclarator(D, S);
3296 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3297 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003298
3299 if (BitWidth) {
3300 // TODO: Validate.
3301 //printf("WARNING: BITFIELDS IGNORED!\n");
3302
3303 // 6.7.2.1p3
3304 // 6.7.2.1p4
3305
3306 } else {
3307 // Not a bitfield.
3308
3309 // validate II.
3310
3311 }
3312
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003313 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3314 // than a variably modified type.
3315 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003316 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003317 InvalidDecl = true;
3318 }
3319
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003320 // Get the visibility (access control) for this ivar.
3321 ObjCIvarDecl::AccessControl ac =
3322 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3323 : ObjCIvarDecl::None;
3324
3325 // Construct the decl.
3326 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003327 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003328
Douglas Gregor72de6672009-01-08 20:45:30 +00003329 if (II) {
3330 Decl *PrevDecl
Steve Naroff939837f2009-01-28 15:51:12 +00003331 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003332 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3333 && !isa<TagDecl>(PrevDecl)) {
3334 Diag(Loc, diag::err_duplicate_member) << II;
3335 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3336 NewID->setInvalidDecl();
3337 }
3338 }
3339
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003340 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003341 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003342
3343 if (D.getInvalidType() || InvalidDecl)
3344 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003345
Douglas Gregor72de6672009-01-08 20:45:30 +00003346 if (II) {
3347 // FIXME: When interfaces are DeclContexts, we'll need to add
3348 // these to the interface.
3349 S->AddDecl(NewID);
3350 IdResolver.AddDecl(NewID);
3351 }
3352
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003353 return NewID;
3354}
3355
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003356void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003357 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003358 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003359 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003360 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003361 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3362 assert(EnclosingDecl && "missing record or interface decl");
3363 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3364
Reid Spencer5f016e22007-07-11 17:01:13 +00003365 // Verify that all the fields are okay.
3366 unsigned NumNamedMembers = 0;
3367 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003368
Reid Spencer5f016e22007-07-11 17:01:13 +00003369 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003370 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3371 assert(FD && "missing field decl");
3372
Reid Spencer5f016e22007-07-11 17:01:13 +00003373 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003374 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003375
Douglas Gregor72de6672009-01-08 20:45:30 +00003376 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003377 // Remember all fields written by the user.
3378 RecFields.push_back(FD);
3379 }
Steve Narofff13271f2007-09-14 23:09:53 +00003380
Reid Spencer5f016e22007-07-11 17:01:13 +00003381 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003382 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003383 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003385 FD->setInvalidDecl();
3386 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003387 continue;
3388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003389 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3390 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003391 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003392 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3393 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003394 FD->setInvalidDecl();
3395 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003396 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003397 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003398 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003399 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003400 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003401 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3402 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003403 FD->setInvalidDecl();
3404 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003405 continue;
3406 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003407 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003408 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003409 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003410 FD->setInvalidDecl();
3411 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003412 continue;
3413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003415 if (Record)
3416 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003418 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3419 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003420 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3422 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003423 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003424 Record->setHasFlexibleArrayMember(true);
3425 } else {
3426 // If this is a struct/class and this is not the last element, reject
3427 // it. Note that GCC supports variable sized arrays in the middle of
3428 // structures.
3429 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003430 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003431 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003432 FD->setInvalidDecl();
3433 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003434 continue;
3435 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003436 // We support flexible arrays at the end of structs in other structs
3437 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003438 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003439 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003440 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003441 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003442 }
3443 }
3444 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003445 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003446 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003447 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003448 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003449 FD->setInvalidDecl();
3450 EnclosingDecl->setInvalidDecl();
3451 continue;
3452 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003453 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003454 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003455 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003457
Reid Spencer5f016e22007-07-11 17:01:13 +00003458 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003459 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003460 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003461 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003462 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003463 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003464 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003465 // Must enforce the rule that ivars in the base classes may not be
3466 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003467 if (ID->getSuperClass()) {
3468 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3469 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3470 ObjCIvarDecl* Ivar = (*IVI);
3471 IdentifierInfo *II = Ivar->getIdentifier();
3472 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3473 if (prevIvar) {
3474 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003475 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003476 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003477 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003478 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003479 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003480 else if (ObjCImplementationDecl *IMPDecl =
3481 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003482 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3483 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003484 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003485 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003486 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003487
3488 if (Attr)
3489 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003490}
3491
Steve Naroff08d92e42007-09-15 18:49:24 +00003492Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003493 DeclTy *lastEnumConst,
3494 SourceLocation IdLoc, IdentifierInfo *Id,
3495 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003496 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003497 EnumConstantDecl *LastEnumConst =
3498 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3499 Expr *Val = static_cast<Expr*>(val);
3500
Chris Lattner31e05722007-08-26 06:24:45 +00003501 // The scope passed in may not be a decl scope. Zip up the scope tree until
3502 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003503 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003504
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 // Verify that there isn't already something declared with this name in this
3506 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003507 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003508 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003509 // Maybe we will complain about the shadowed template parameter.
3510 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3511 // Just pretend that we didn't see the previous declaration.
3512 PrevDecl = 0;
3513 }
3514
3515 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003516 // When in C++, we may get a TagDecl with the same name; in this case the
3517 // enum constant will 'hide' the tag.
3518 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3519 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003520 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003521 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003522 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003523 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003524 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003525 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003526 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003527 return 0;
3528 }
3529 }
3530
3531 llvm::APSInt EnumVal(32);
3532 QualType EltTy;
3533 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003534 // Make sure to promote the operand type to int.
3535 UsualUnaryConversions(Val);
3536
Reid Spencer5f016e22007-07-11 17:01:13 +00003537 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3538 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003539 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003540 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003541 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003542 } else {
3543 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003544 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003545 }
3546
3547 if (!Val) {
3548 if (LastEnumConst) {
3549 // Assign the last value + 1.
3550 EnumVal = LastEnumConst->getInitVal();
3551 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003552
3553 // Check for overflow on increment.
3554 if (EnumVal < LastEnumConst->getInitVal())
3555 Diag(IdLoc, diag::warn_enum_value_overflow);
3556
Chris Lattnerb7416f92007-08-27 17:37:24 +00003557 EltTy = LastEnumConst->getType();
3558 } else {
3559 // First value, set to zero.
3560 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003561 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003562 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003563 }
3564
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003565 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003566 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003567 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003568
3569 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003570 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003571
Reid Spencer5f016e22007-07-11 17:01:13 +00003572 return New;
3573}
3574
Steve Naroff02408c62008-08-07 14:08:16 +00003575// FIXME: For consistency with ActOnFields(), we should have the parser
3576// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003577void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003578 DeclTy **Elements, unsigned NumElements) {
3579 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003580 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003581
Chris Lattnere37f0be2007-08-28 05:10:31 +00003582 // TODO: If the result value doesn't fit in an int, it must be a long or long
3583 // long value. ISO C does not support this, but GCC does as an extension,
3584 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003585 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003586
Chris Lattnerac609682007-08-28 06:15:15 +00003587 // Verify that all the values are okay, compute the size of the values, and
3588 // reverse the list.
3589 unsigned NumNegativeBits = 0;
3590 unsigned NumPositiveBits = 0;
3591
3592 // Keep track of whether all elements have type int.
3593 bool AllElementsInt = true;
3594
Reid Spencer5f016e22007-07-11 17:01:13 +00003595 for (unsigned i = 0; i != NumElements; ++i) {
3596 EnumConstantDecl *ECD =
3597 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3598 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003599
3600 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003601 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003602 assert(InitVal.getBitWidth() >= IntWidth &&
3603 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003604 if (InitVal.getBitWidth() > IntWidth) {
3605 llvm::APSInt V(InitVal);
3606 V.trunc(IntWidth);
3607 V.extend(InitVal.getBitWidth());
3608 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003609 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3610 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003611 }
Chris Lattnerac609682007-08-28 06:15:15 +00003612
3613 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003614 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003615 NumPositiveBits = std::max(NumPositiveBits,
3616 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003617 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003618 NumNegativeBits = std::max(NumNegativeBits,
3619 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003620
Chris Lattnerac609682007-08-28 06:15:15 +00003621 // Keep track of whether every enum element has type int (very commmon).
3622 if (AllElementsInt)
3623 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003624 }
3625
Chris Lattnerac609682007-08-28 06:15:15 +00003626 // Figure out the type that should be used for this enum.
3627 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3628 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003629 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003630
3631 if (NumNegativeBits) {
3632 // If there is a negative value, figure out the smallest integer type (of
3633 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003634 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003635 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003636 BestWidth = IntWidth;
3637 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003638 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003639
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003640 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003641 BestType = Context.LongTy;
3642 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003643 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003644
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003645 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003646 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3647 BestType = Context.LongLongTy;
3648 }
3649 }
3650 } else {
3651 // If there is no negative value, figure out which of uint, ulong, ulonglong
3652 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003653 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003654 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003655 BestWidth = IntWidth;
3656 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003657 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003658 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003659 } else {
3660 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003661 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003662 "How could an initializer get larger than ULL?");
3663 BestType = Context.UnsignedLongLongTy;
3664 }
3665 }
3666
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003667 // Loop over all of the enumerator constants, changing their types to match
3668 // the type of the enum if needed.
3669 for (unsigned i = 0; i != NumElements; ++i) {
3670 EnumConstantDecl *ECD =
3671 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3672 if (!ECD) continue; // Already issued a diagnostic.
3673
3674 // Standard C says the enumerators have int type, but we allow, as an
3675 // extension, the enumerators to be larger than int size. If each
3676 // enumerator value fits in an int, type it as an int, otherwise type it the
3677 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3678 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003679 if (ECD->getType() == Context.IntTy) {
3680 // Make sure the init value is signed.
3681 llvm::APSInt IV = ECD->getInitVal();
3682 IV.setIsSigned(true);
3683 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003684
3685 if (getLangOptions().CPlusPlus)
3686 // C++ [dcl.enum]p4: Following the closing brace of an
3687 // enum-specifier, each enumerator has the type of its
3688 // enumeration.
3689 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003690 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003691 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003692
3693 // Determine whether the value fits into an int.
3694 llvm::APSInt InitVal = ECD->getInitVal();
3695 bool FitsInInt;
3696 if (InitVal.isUnsigned() || !InitVal.isNegative())
3697 FitsInInt = InitVal.getActiveBits() < IntWidth;
3698 else
3699 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3700
3701 // If it fits into an integer type, force it. Otherwise force it to match
3702 // the enum decl type.
3703 QualType NewTy;
3704 unsigned NewWidth;
3705 bool NewSign;
3706 if (FitsInInt) {
3707 NewTy = Context.IntTy;
3708 NewWidth = IntWidth;
3709 NewSign = true;
3710 } else if (ECD->getType() == BestType) {
3711 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003712 if (getLangOptions().CPlusPlus)
3713 // C++ [dcl.enum]p4: Following the closing brace of an
3714 // enum-specifier, each enumerator has the type of its
3715 // enumeration.
3716 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003717 continue;
3718 } else {
3719 NewTy = BestType;
3720 NewWidth = BestWidth;
3721 NewSign = BestType->isSignedIntegerType();
3722 }
3723
3724 // Adjust the APSInt value.
3725 InitVal.extOrTrunc(NewWidth);
3726 InitVal.setIsSigned(NewSign);
3727 ECD->setInitVal(InitVal);
3728
3729 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003730 if (ECD->getInitExpr())
3731 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3732 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003733 if (getLangOptions().CPlusPlus)
3734 // C++ [dcl.enum]p4: Following the closing brace of an
3735 // enum-specifier, each enumerator has the type of its
3736 // enumeration.
3737 ECD->setType(EnumType);
3738 else
3739 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003740 }
Chris Lattnerac609682007-08-28 06:15:15 +00003741
Douglas Gregor44b43212008-12-11 16:49:14 +00003742 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003743}
3744
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003745Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003746 ExprArg expr) {
3747 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3748
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003749 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003750}
3751
Douglas Gregorf44515a2008-12-16 22:23:02 +00003752
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003753void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3754 ExprTy *alignment, SourceLocation PragmaLoc,
3755 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3756 Expr *Alignment = static_cast<Expr *>(alignment);
3757
3758 // If specified then alignment must be a "small" power of two.
3759 unsigned AlignmentVal = 0;
3760 if (Alignment) {
3761 llvm::APSInt Val;
3762 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3763 !Val.isPowerOf2() ||
3764 Val.getZExtValue() > 16) {
3765 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3766 delete Alignment;
3767 return; // Ignore
3768 }
3769
3770 AlignmentVal = (unsigned) Val.getZExtValue();
3771 }
3772
3773 switch (Kind) {
3774 case Action::PPK_Default: // pack([n])
3775 PackContext.setAlignment(AlignmentVal);
3776 break;
3777
3778 case Action::PPK_Show: // pack(show)
3779 // Show the current alignment, making sure to show the right value
3780 // for the default.
3781 AlignmentVal = PackContext.getAlignment();
3782 // FIXME: This should come from the target.
3783 if (AlignmentVal == 0)
3784 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003785 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003786 break;
3787
3788 case Action::PPK_Push: // pack(push [, id] [, [n])
3789 PackContext.push(Name);
3790 // Set the new alignment if specified.
3791 if (Alignment)
3792 PackContext.setAlignment(AlignmentVal);
3793 break;
3794
3795 case Action::PPK_Pop: // pack(pop [, id] [, n])
3796 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3797 // "#pragma pack(pop, identifier, n) is undefined"
3798 if (Alignment && Name)
3799 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3800
3801 // Do the pop.
3802 if (!PackContext.pop(Name)) {
3803 // If a name was specified then failure indicates the name
3804 // wasn't found. Otherwise failure indicates the stack was
3805 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003806 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3807 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003808
3809 // FIXME: Warn about popping named records as MSVC does.
3810 } else {
3811 // Pop succeeded, set the new alignment if specified.
3812 if (Alignment)
3813 PackContext.setAlignment(AlignmentVal);
3814 }
3815 break;
3816
3817 default:
3818 assert(0 && "Invalid #pragma pack kind.");
3819 }
3820}
3821
3822bool PragmaPackStack::pop(IdentifierInfo *Name) {
3823 if (Stack.empty())
3824 return false;
3825
3826 // If name is empty just pop top.
3827 if (!Name) {
3828 Alignment = Stack.back().first;
3829 Stack.pop_back();
3830 return true;
3831 }
3832
3833 // Otherwise, find the named record.
3834 for (unsigned i = Stack.size(); i != 0; ) {
3835 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003836 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003837 // Found it, pop up to and including this record.
3838 Alignment = Stack[i].first;
3839 Stack.erase(Stack.begin() + i, Stack.end());
3840 return true;
3841 }
3842 }
3843
3844 return false;
3845}