blob: 3e501f450a8094dad5b6f68c1c72ef08eaa855d8 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner6953a072008-06-26 18:38:35 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000031
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Douglas Gregor1075a162009-02-04 17:00:24 +000034Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
35 Scope *S, const CXXScopeSpec *SS) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000036 Decl *IIDecl = 0;
Douglas Gregor52ae30c2009-01-30 01:04:22 +000037 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000038 switch (Result.getKind()) {
Steve Naroffa4e04982009-01-29 18:09:31 +000039 case LookupResult::NotFound:
40 case LookupResult::FoundOverloaded:
Douglas Gregor1075a162009-02-04 17:00:24 +000041 return 0;
42
Steve Naroffa4e04982009-01-29 18:09:31 +000043 case LookupResult::AmbiguousBaseSubobjectTypes:
44 case LookupResult::AmbiguousBaseSubobjects:
Douglas Gregor7a7be652009-02-03 19:21:40 +000045 case LookupResult::AmbiguousReference:
Douglas Gregor1075a162009-02-04 17:00:24 +000046 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
Steve Naroffa4e04982009-01-29 18:09:31 +000047 return 0;
Douglas Gregor1075a162009-02-04 17:00:24 +000048
Steve Naroffa4e04982009-01-29 18:09:31 +000049 case LookupResult::Found:
50 IIDecl = Result.getAsDecl();
51 break;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000052 }
53
Steve Naroffa4e04982009-01-29 18:09:31 +000054 if (IIDecl) {
55 if (isa<TypedefDecl>(IIDecl) ||
56 isa<ObjCInterfaceDecl>(IIDecl) ||
57 isa<TagDecl>(IIDecl) ||
58 isa<TemplateTypeParmDecl>(IIDecl))
59 return IIDecl;
60 }
Steve Naroff81f1bba2007-09-06 21:24:23 +000061 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000062}
63
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000064DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000065 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000066 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000067 if (MD->isOutOfLineDefinition())
68 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000069
70 // A C++ inline method is parsed *after* the topmost class it was declared in
71 // is fully parsed (it's "complete").
72 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000073 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000074 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
75 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000076 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000077 DC = RD;
78
79 // Return the declaration context of the topmost class the inline method is
80 // declared in.
81 return DC;
82 }
83
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000084 if (isa<ObjCMethodDecl>(DC))
85 return Context.getTranslationUnitDecl();
86
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000087 if (Decl *D = dyn_cast<Decl>(DC))
88 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000089
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000090 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000091}
92
Douglas Gregor8acb7272008-12-11 16:49:14 +000093void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000094 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000095 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000096 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000097 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000098}
99
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000100void Sema::PopDeclContext() {
101 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000102
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000103 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000104}
105
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000106/// Add this decl to the scope shadowed decl chains.
107void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000108 // Move up the scope chain until we find the nearest enclosing
109 // non-transparent context. The declaration will be introduced into this
110 // scope.
111 while (S->getEntity() &&
112 ((DeclContext *)S->getEntity())->isTransparentContext())
113 S = S->getParent();
114
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000115 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000116
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000117 // Add scoped declarations into their context, so that they can be
118 // found later. Declarations without a context won't be inserted
119 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000120 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000121
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000122 // C++ [basic.scope]p4:
123 // -- exactly one declaration shall declare a class name or
124 // enumeration name that is not a typedef name and the other
125 // declarations shall all refer to the same object or
126 // enumerator, or all refer to functions and function templates;
127 // in this case the class name or enumeration name is hidden.
128 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
129 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000130 if (CurContext->getLookupContext()
131 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000132 // We're pushing the tag into the current context, which might
133 // require some reshuffling in the identifier resolver.
134 IdentifierResolver::iterator
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000135 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000136 IEnd = IdResolver.end();
137 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
138 NamedDecl *PrevDecl = *I;
139 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
140 PrevDecl = *I, ++I) {
141 if (TD->declarationReplaces(*I)) {
142 // This is a redeclaration. Remove it from the chain and
143 // break out, so that we'll add in the shadowed
144 // declaration.
145 S->RemoveDecl(*I);
146 if (PrevDecl == *I) {
147 IdResolver.RemoveDecl(*I);
148 IdResolver.AddDecl(TD);
149 return;
150 } else {
151 IdResolver.RemoveDecl(*I);
152 break;
153 }
154 }
155 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000156
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000157 // There is already a declaration with the same name in the same
158 // scope, which is not a tag declaration. It must be found
159 // before we find the new declaration, so insert the new
160 // declaration at the end of the chain.
161 IdResolver.AddShadowedDecl(TD, PrevDecl);
162
163 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000164 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000165 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000166 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000167 // We are pushing the name of a function, which might be an
168 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000169 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000170 IdentifierResolver::iterator Redecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000171 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000172 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000173 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000174 FD));
175 if (Redecl != IdResolver.end()) {
176 // There is already a declaration of a function on our
177 // IdResolver chain. Replace it with this declaration.
178 S->RemoveDecl(*Redecl);
179 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000180 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000181 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000183 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000184}
185
Steve Naroff9637a9b2007-10-09 22:01:59 +0000186void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000187 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000188 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
189 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000190
Chris Lattner4b009652007-07-25 00:24:17 +0000191 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
192 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000193 Decl *TmpD = static_cast<Decl*>(*I);
194 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000195
Douglas Gregor8acb7272008-12-11 16:49:14 +0000196 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
197 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000198
Douglas Gregor8acb7272008-12-11 16:49:14 +0000199 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000200
Douglas Gregor8acb7272008-12-11 16:49:14 +0000201 // Remove this name from our lexical scope.
202 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000203 }
204}
205
Steve Naroffe57c21a2008-04-01 23:04:06 +0000206/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
207/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000208ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000209 // The third "scope" argument is 0 since we aren't enabling lazy built-in
210 // creation from this context.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000211 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000212
Steve Naroff6384a012008-04-02 14:35:35 +0000213 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000214}
215
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000216/// getNonFieldDeclScope - Retrieves the innermost scope, starting
217/// from S, where a non-field would be declared. This routine copes
218/// with the difference between C and C++ scoping rules in structs and
219/// unions. For example, the following code is well-formed in C but
220/// ill-formed in C++:
221/// @code
222/// struct S6 {
223/// enum { BAR } e;
224/// };
225///
226/// void test_S6() {
227/// struct S6 a;
228/// a.e = BAR;
229/// }
230/// @endcode
231/// For the declaration of BAR, this routine will return a different
232/// scope. The scope S will be the scope of the unnamed enumeration
233/// within S6. In C++, this routine will return the scope associated
234/// with S6, because the enumeration's scope is a transparent
235/// context but structures can contain non-field names. In C, this
236/// routine will return the translation unit scope, since the
237/// enumeration's scope is a transparent context and structures cannot
238/// contain non-field names.
239Scope *Sema::getNonFieldDeclScope(Scope *S) {
240 while (((S->getFlags() & Scope::DeclScope) == 0) ||
241 (S->getEntity() &&
242 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
243 (S->isClassScope() && !getLangOptions().CPlusPlus))
244 S = S->getParent();
245 return S;
246}
247
Chris Lattnera9c87f22008-05-05 22:18:14 +0000248void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000249 if (!Context.getBuiltinVaListType().isNull())
250 return;
251
252 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor09be81b2009-02-04 17:27:36 +0000253 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000254 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000255 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
256}
257
Chris Lattner4b009652007-07-25 00:24:17 +0000258/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
259/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000260NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
261 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000262 Builtin::ID BID = (Builtin::ID)bid;
263
Chris Lattnerb23469f2008-09-28 05:54:29 +0000264 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000265 InitBuiltinVaListType();
266
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000267 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000268 FunctionDecl *New = FunctionDecl::Create(Context,
269 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000270 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000271 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000272
Chris Lattnera9c87f22008-05-05 22:18:14 +0000273 // Create Decl objects for each parameter, adding them to the
274 // FunctionDecl.
275 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
276 llvm::SmallVector<ParmVarDecl*, 16> Params;
277 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
278 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000279 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000280 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000281 }
282
283
284
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000285 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000286 // FIXME: This is hideous. We need to teach PushOnScopeChains to
287 // relate Scopes to DeclContexts, and probably eliminate CurContext
288 // entirely, but we're not there yet.
289 DeclContext *SavedContext = CurContext;
290 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000291 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000292 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000293 return New;
294}
295
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000296/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
297/// everything from the standard library is defined.
298NamespaceDecl *Sema::GetStdNamespace() {
299 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000300 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000301 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000302 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000303 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
304 }
305 return StdNamespace;
306}
307
Chris Lattner4b009652007-07-25 00:24:17 +0000308/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
309/// and scope as a previous declaration 'Old'. Figure out how to resolve this
310/// situation, merging decls or emitting diagnostics as appropriate.
311///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000312TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000313 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000314 // Allow multiple definitions for ObjC built-in typedefs.
315 // FIXME: Verify the underlying types are equivalent!
316 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000317 const IdentifierInfo *TypeID = New->getIdentifier();
318 switch (TypeID->getLength()) {
319 default: break;
320 case 2:
321 if (!TypeID->isStr("id"))
322 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000323 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000324 objc_types = true;
325 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000326 case 5:
327 if (!TypeID->isStr("Class"))
328 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000329 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000330 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000331 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000332 case 3:
333 if (!TypeID->isStr("SEL"))
334 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000335 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000336 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000337 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000338 case 8:
339 if (!TypeID->isStr("Protocol"))
340 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000341 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000342 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000343 return New;
344 }
345 // Fall through - the typedef name was not a builtin type.
346 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000347 // Verify the old decl was also a type.
348 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000349 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000350 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000351 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000352 if (!objc_types)
353 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000354 return New;
355 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000356
357 // Determine the "old" type we'll use for checking and diagnostics.
358 QualType OldType;
359 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
360 OldType = OldTypedef->getUnderlyingType();
361 else
362 OldType = Context.getTypeDeclType(Old);
363
Chris Lattnerbef8d622008-07-25 18:44:27 +0000364 // If the typedef types are not identical, reject them in all languages and
365 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000366
367 if (OldType != New->getUnderlyingType() &&
368 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000369 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000370 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000371 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000372 if (!objc_types)
373 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000374 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000375 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000376 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000377 if (getLangOptions().Microsoft) return New;
378
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000379 // C++ [dcl.typedef]p2:
380 // In a given non-class scope, a typedef specifier can be used to
381 // redefine the name of any type declared in that scope to refer
382 // to the type to which it already refers.
383 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
384 return New;
385
386 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000387 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
388 // *either* declaration is in a system header. The code below implements
389 // this adhoc compatibility rule. FIXME: The following code will not
390 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000391 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
392 SourceManager &SrcMgr = Context.getSourceManager();
393 if (SrcMgr.isInSystemHeader(Old->getLocation()))
394 return New;
395 if (SrcMgr.isInSystemHeader(New->getLocation()))
396 return New;
397 }
Eli Friedman324d5032008-06-11 06:20:39 +0000398
Chris Lattnerb1753422008-11-23 21:45:46 +0000399 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000400 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000401 return New;
402}
403
Chris Lattner6953a072008-06-26 18:38:35 +0000404/// DeclhasAttr - returns true if decl Declaration already has the target
405/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000406static bool DeclHasAttr(const Decl *decl, const Attr *target) {
407 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
408 if (attr->getKind() == target->getKind())
409 return true;
410
411 return false;
412}
413
414/// MergeAttributes - append attributes from the Old decl to the New one.
415static void MergeAttributes(Decl *New, Decl *Old) {
416 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
417
Chris Lattner402b3372008-03-03 03:28:21 +0000418 while (attr) {
419 tmp = attr;
420 attr = attr->getNext();
421
422 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000423 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000424 New->addAttr(tmp);
425 } else {
426 tmp->setNext(0);
427 delete(tmp);
428 }
429 }
Nuno Lopes77654342008-06-01 22:53:53 +0000430
431 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000432}
433
Chris Lattner3e254fb2008-04-08 04:40:51 +0000434/// MergeFunctionDecl - We just parsed a function 'New' from
435/// declarator D which has the same name and scope as a previous
436/// declaration 'Old'. Figure out how to resolve this situation,
437/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000438/// Redeclaration will be set true if this New is a redeclaration OldD.
439///
440/// In C++, New and Old must be declarations that are not
441/// overloaded. Use IsOverload to determine whether New and Old are
442/// overloaded, and to select the Old declaration that New should be
443/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000444FunctionDecl *
445Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000446 assert(!isa<OverloadedFunctionDecl>(OldD) &&
447 "Cannot merge with an overloaded function declaration");
448
Douglas Gregor42214c52008-04-21 02:02:58 +0000449 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000450 // Verify the old decl was also a function.
451 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
452 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000453 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000454 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000455 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000456 return New;
457 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000458
459 // Determine whether the previous declaration was a definition,
460 // implicit declaration, or a declaration.
461 diag::kind PrevDiag;
462 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000463 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000464 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000465 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000466 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000467 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000468
Chris Lattner42a21742008-04-06 23:10:54 +0000469 QualType OldQType = Context.getCanonicalType(Old->getType());
470 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000471
Douglas Gregord2baafd2008-10-21 16:13:35 +0000472 if (getLangOptions().CPlusPlus) {
473 // (C++98 13.1p2):
474 // Certain function declarations cannot be overloaded:
475 // -- Function declarations that differ only in the return type
476 // cannot be overloaded.
477 QualType OldReturnType
478 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
479 QualType NewReturnType
480 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
481 if (OldReturnType != NewReturnType) {
482 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
483 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000484 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485 return New;
486 }
487
488 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
489 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
490 if (OldMethod && NewMethod) {
491 // -- Member function declarations with the same name and the
492 // same parameter types cannot be overloaded if any of them
493 // is a static member function declaration.
494 if (OldMethod->isStatic() || NewMethod->isStatic()) {
495 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
496 Diag(Old->getLocation(), PrevDiag);
497 return New;
498 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000499
500 // C++ [class.mem]p1:
501 // [...] A member shall not be declared twice in the
502 // member-specification, except that a nested class or member
503 // class template can be declared and then later defined.
504 if (OldMethod->getLexicalDeclContext() ==
505 NewMethod->getLexicalDeclContext()) {
506 unsigned NewDiag;
507 if (isa<CXXConstructorDecl>(OldMethod))
508 NewDiag = diag::err_constructor_redeclared;
509 else if (isa<CXXDestructorDecl>(NewMethod))
510 NewDiag = diag::err_destructor_redeclared;
511 else if (isa<CXXConversionDecl>(NewMethod))
512 NewDiag = diag::err_conv_function_redeclared;
513 else
514 NewDiag = diag::err_member_redeclared;
515
516 Diag(New->getLocation(), NewDiag);
517 Diag(Old->getLocation(), PrevDiag);
518 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000519 }
520
521 // (C++98 8.3.5p3):
522 // All declarations for a function shall agree exactly in both the
523 // return type and the parameter-type-list.
524 if (OldQType == NewQType) {
525 // We have a redeclaration.
526 MergeAttributes(New, Old);
527 Redeclaration = true;
528 return MergeCXXFunctionDecl(New, Old);
529 }
530
531 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000532 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000533
534 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000535 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000536 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000537 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000538 MergeAttributes(New, Old);
539 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000540 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000541 }
Chris Lattner1470b072007-11-06 06:07:26 +0000542
Steve Naroff6c9e7922008-01-16 15:01:34 +0000543 // A function that has already been declared has been redeclared or defined
544 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000545
Chris Lattner4b009652007-07-25 00:24:17 +0000546 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
547 // TODO: This is totally simplistic. It should handle merging functions
548 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000549 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000550 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000551 return New;
552}
553
Steve Naroffb5e78152008-08-08 17:50:35 +0000554/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000555static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000556 if (VD->isFileVarDecl())
557 return (!VD->getInit() &&
558 (VD->getStorageClass() == VarDecl::None ||
559 VD->getStorageClass() == VarDecl::Static));
560 return false;
561}
562
563/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
564/// when dealing with C "tentative" external object definitions (C99 6.9.2).
565void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
566 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000567 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000568
Douglas Gregor3a423132009-01-07 16:34:42 +0000569 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000570 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000571 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
572 E = IdResolver.end();
573 I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000574 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000575 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
576
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000577 // Handle the following case:
578 // int a[10];
579 // int a[]; - the code below makes sure we set the correct type.
580 // int a[11]; - this is an error, size isn't 10.
581 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
582 OldDecl->getType()->isConstantArrayType())
583 VD->setType(OldDecl->getType());
584
Steve Naroffb5e78152008-08-08 17:50:35 +0000585 // Check for "tentative" definitions. We can't accomplish this in
586 // MergeVarDecl since the initializer hasn't been attached.
587 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
588 continue;
589
590 // Handle __private_extern__ just like extern.
591 if (OldDecl->getStorageClass() != VarDecl::Extern &&
592 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
593 VD->getStorageClass() != VarDecl::Extern &&
594 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000595 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000596 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000597 }
598 }
599 }
600}
601
Chris Lattner4b009652007-07-25 00:24:17 +0000602/// MergeVarDecl - We just parsed a variable 'New' which has the same name
603/// and scope as a previous declaration 'Old'. Figure out how to resolve this
604/// situation, merging decls or emitting diagnostics as appropriate.
605///
Steve Naroffb5e78152008-08-08 17:50:35 +0000606/// Tentative definition rules (C99 6.9.2p2) are checked by
607/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
608/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000609///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000610VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000611 // Verify the old decl was also a variable.
612 VarDecl *Old = dyn_cast<VarDecl>(OldD);
613 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000614 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000615 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000616 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000617 return New;
618 }
Chris Lattner402b3372008-03-03 03:28:21 +0000619
620 MergeAttributes(New, Old);
621
Eli Friedman4a480d62009-01-24 23:49:55 +0000622 // Merge the types
623 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
624 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000625 Diag(New->getLocation(), diag::err_redefinition_different_type)
626 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000627 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000628 return New;
629 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000630 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000631 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
632 if (New->getStorageClass() == VarDecl::Static &&
633 (Old->getStorageClass() == VarDecl::None ||
634 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000635 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000636 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000637 return New;
638 }
639 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
640 if (New->getStorageClass() != VarDecl::Static &&
641 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000642 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000643 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000644 return New;
645 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000646 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
647 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000648 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000649 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
651 return New;
652}
653
Chris Lattner3e254fb2008-04-08 04:40:51 +0000654/// CheckParmsForFunctionDef - Check that the parameters of the given
655/// function are appropriate for the definition of a function. This
656/// takes care of any checks that cannot be performed on the
657/// declaration itself, e.g., that the types of each of the function
658/// parameters are complete.
659bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
660 bool HasInvalidParm = false;
661 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
662 ParmVarDecl *Param = FD->getParamDecl(p);
663
664 // C99 6.7.5.3p4: the parameters in a parameter type list in a
665 // function declarator that is part of a function definition of
666 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000667 if (!Param->isInvalidDecl() &&
668 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
669 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000670 Param->setInvalidDecl();
671 HasInvalidParm = true;
672 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000673
674 // C99 6.9.1p5: If the declarator includes a parameter type list, the
675 // declaration of each parameter shall include an identifier.
676 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
677 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000678 }
679
680 return HasInvalidParm;
681}
682
Chris Lattner4b009652007-07-25 00:24:17 +0000683/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
684/// no declarator (e.g. "struct foo;") is parsed.
685Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000686 TagDecl *Tag
687 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
688 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
689 if (!Record->getDeclName() && Record->isDefinition() &&
690 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
691 return BuildAnonymousStructOrUnion(S, DS, Record);
692
693 // Microsoft allows unnamed struct/union fields. Don't complain
694 // about them.
695 // FIXME: Should we support Microsoft's extensions in this area?
696 if (Record->getDeclName() && getLangOptions().Microsoft)
697 return Tag;
698 }
699
Sebastian Redlb7605e82008-12-28 15:28:59 +0000700 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000701 // Warn about typedefs of enums without names, since this is an
702 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000703 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
704 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000705 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000706 << DS.getSourceRange();
707 return Tag;
708 }
709
Sebastian Redlb7605e82008-12-28 15:28:59 +0000710 // FIXME: This diagnostic is emitted even when various previous
711 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
712 // DeclSpec has no means of communicating this information, and the
713 // responsible parser functions are quite far apart.
714 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
715 << DS.getSourceRange();
716 return 0;
717 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000718
Douglas Gregor723d3332009-01-07 00:43:41 +0000719 return Tag;
720}
721
722/// InjectAnonymousStructOrUnionMembers - Inject the members of the
723/// anonymous struct or union AnonRecord into the owning context Owner
724/// and scope S. This routine will be invoked just after we realize
725/// that an unnamed union or struct is actually an anonymous union or
726/// struct, e.g.,
727///
728/// @code
729/// union {
730/// int i;
731/// float f;
732/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
733/// // f into the surrounding scope.x
734/// @endcode
735///
736/// This routine is recursive, injecting the names of nested anonymous
737/// structs/unions into the owning context and scope as well.
738bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
739 RecordDecl *AnonRecord) {
740 bool Invalid = false;
741 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
742 FEnd = AnonRecord->field_end();
743 F != FEnd; ++F) {
744 if ((*F)->getDeclName()) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000745 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
746 LookupOrdinaryName, true);
Douglas Gregor723d3332009-01-07 00:43:41 +0000747 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
748 // C++ [class.union]p2:
749 // The names of the members of an anonymous union shall be
750 // distinct from the names of any other entity in the
751 // scope in which the anonymous union is declared.
752 unsigned diagKind
753 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
754 : diag::err_anonymous_struct_member_redecl;
755 Diag((*F)->getLocation(), diagKind)
756 << (*F)->getDeclName();
757 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
758 Invalid = true;
759 } else {
760 // C++ [class.union]p2:
761 // For the purpose of name lookup, after the anonymous union
762 // definition, the members of the anonymous union are
763 // considered to have been defined in the scope in which the
764 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000765 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000766 S->AddDecl(*F);
767 IdResolver.AddDecl(*F);
768 }
769 } else if (const RecordType *InnerRecordType
770 = (*F)->getType()->getAsRecordType()) {
771 RecordDecl *InnerRecord = InnerRecordType->getDecl();
772 if (InnerRecord->isAnonymousStructOrUnion())
773 Invalid = Invalid ||
774 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
775 }
776 }
777
778 return Invalid;
779}
780
781/// ActOnAnonymousStructOrUnion - Handle the declaration of an
782/// anonymous structure or union. Anonymous unions are a C++ feature
783/// (C++ [class.union]) and a GNU C extension; anonymous structures
784/// are a GNU C and GNU C++ extension.
785Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
786 RecordDecl *Record) {
787 DeclContext *Owner = Record->getDeclContext();
788
789 // Diagnose whether this anonymous struct/union is an extension.
790 if (Record->isUnion() && !getLangOptions().CPlusPlus)
791 Diag(Record->getLocation(), diag::ext_anonymous_union);
792 else if (!Record->isUnion())
793 Diag(Record->getLocation(), diag::ext_anonymous_struct);
794
795 // C and C++ require different kinds of checks for anonymous
796 // structs/unions.
797 bool Invalid = false;
798 if (getLangOptions().CPlusPlus) {
799 const char* PrevSpec = 0;
800 // C++ [class.union]p3:
801 // Anonymous unions declared in a named namespace or in the
802 // global namespace shall be declared static.
803 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
804 (isa<TranslationUnitDecl>(Owner) ||
805 (isa<NamespaceDecl>(Owner) &&
806 cast<NamespaceDecl>(Owner)->getDeclName()))) {
807 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
808 Invalid = true;
809
810 // Recover by adding 'static'.
811 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
812 }
813 // C++ [class.union]p3:
814 // A storage class is not allowed in a declaration of an
815 // anonymous union in a class scope.
816 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
817 isa<RecordDecl>(Owner)) {
818 Diag(DS.getStorageClassSpecLoc(),
819 diag::err_anonymous_union_with_storage_spec);
820 Invalid = true;
821
822 // Recover by removing the storage specifier.
823 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
824 PrevSpec);
825 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000826
827 // C++ [class.union]p2:
828 // The member-specification of an anonymous union shall only
829 // define non-static data members. [Note: nested types and
830 // functions cannot be declared within an anonymous union. ]
831 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
832 MemEnd = Record->decls_end();
833 Mem != MemEnd; ++Mem) {
834 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
835 // C++ [class.union]p3:
836 // An anonymous union shall not have private or protected
837 // members (clause 11).
838 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
839 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
840 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
841 Invalid = true;
842 }
843 } else if ((*Mem)->isImplicit()) {
844 // Any implicit members are fine.
Douglas Gregor2d87eb02009-02-03 00:34:39 +0000845 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
846 // This is a type that showed up in an
847 // elaborated-type-specifier inside the anonymous struct or
848 // union, but which actually declares a type outside of the
849 // anonymous struct or union. It's okay.
Douglas Gregorc7f01612009-01-07 19:46:03 +0000850 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
851 if (!MemRecord->isAnonymousStructOrUnion() &&
852 MemRecord->getDeclName()) {
853 // This is a nested type declaration.
854 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
855 << (int)Record->isUnion();
856 Invalid = true;
857 }
858 } else {
859 // We have something that isn't a non-static data
860 // member. Complain about it.
861 unsigned DK = diag::err_anonymous_record_bad_member;
862 if (isa<TypeDecl>(*Mem))
863 DK = diag::err_anonymous_record_with_type;
864 else if (isa<FunctionDecl>(*Mem))
865 DK = diag::err_anonymous_record_with_function;
866 else if (isa<VarDecl>(*Mem))
867 DK = diag::err_anonymous_record_with_static;
868 Diag((*Mem)->getLocation(), DK)
869 << (int)Record->isUnion();
870 Invalid = true;
871 }
872 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000873 } else {
874 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000875 if (Record->isUnion() && !Owner->isRecord()) {
876 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
877 << (int)getLangOptions().CPlusPlus;
878 Invalid = true;
879 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000880 }
881
882 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000883 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
884 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000885 Invalid = true;
886 }
887
888 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000889 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +0000890 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
891 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
892 /*IdentifierInfo=*/0,
893 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000894 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000895 Anon->setAccess(AS_public);
896 if (getLangOptions().CPlusPlus)
897 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000898 } else {
899 VarDecl::StorageClass SC;
900 switch (DS.getStorageClassSpec()) {
901 default: assert(0 && "Unknown storage class!");
902 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
903 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
904 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
905 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
906 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
907 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
908 case DeclSpec::SCS_mutable:
909 // mutable can only appear on non-static class members, so it's always
910 // an error here
911 Diag(Record->getLocation(), diag::err_mutable_nonmember);
912 Invalid = true;
913 SC = VarDecl::None;
914 break;
915 }
916
917 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
918 /*IdentifierInfo=*/0,
919 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000920 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +0000921 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000922 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000923
924 // Add the anonymous struct/union object to the current
925 // context. We'll be referencing this object when we refer to one of
926 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000927 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000928
929 // Inject the members of the anonymous struct/union into the owning
930 // context and into the identifier resolver chain for name lookup
931 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000932 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
933 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000934
935 // Mark this as an anonymous struct/union type. Note that we do not
936 // do this until after we have already checked and injected the
937 // members of this anonymous struct/union type, because otherwise
938 // the members could be injected twice: once by DeclContext when it
939 // builds its lookup table, and once by
940 // InjectAnonymousStructOrUnionMembers.
941 Record->setAnonymousStructOrUnion(true);
942
943 if (Invalid)
944 Anon->setInvalidDecl();
945
946 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000947}
948
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000949bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
950 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000951 // Get the type before calling CheckSingleAssignmentConstraints(), since
952 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000953 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000954
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000955 if (getLangOptions().CPlusPlus) {
956 // FIXME: I dislike this error message. A lot.
957 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
958 return Diag(Init->getSourceRange().getBegin(),
959 diag::err_typecheck_convert_incompatible)
960 << DeclType << Init->getType() << "initializing"
961 << Init->getSourceRange();
962
963 return false;
964 }
Douglas Gregor6fd35572008-12-19 17:40:08 +0000965
Chris Lattner005ed752008-01-04 18:04:52 +0000966 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
967 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
968 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000969}
970
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000971bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000972 const ArrayType *AT = Context.getAsArrayType(DeclT);
973
974 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000975 // C99 6.7.8p14. We have an array of character type with unknown size
976 // being initialized to a string literal.
977 llvm::APSInt ConstVal(32);
978 ConstVal = strLiteral->getByteLength() + 1;
979 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000980 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000981 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000982 } else {
983 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000984 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000985 // FIXME: Avoid truncation for 64-bit length strings.
986 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000987 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000988 diag::warn_initializer_string_for_char_array_too_long)
989 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000990 }
991 // Set type from "char *" to "constant array of char".
992 strLiteral->setType(DeclT);
993 // For now, we always return false (meaning success).
994 return false;
995}
996
997StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000998 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000999 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +00001000 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +00001001 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001002 return 0;
1003}
1004
Douglas Gregor6428e762008-11-05 15:29:30 +00001005bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1006 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001007 DeclarationName InitEntity,
1008 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001009 if (DeclType->isDependentType() || Init->isTypeDependent())
1010 return false;
1011
Douglas Gregor81c29152008-10-29 00:13:59 +00001012 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001013 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001014 // (8.3.2), shall be initialized by an object, or function, of
1015 // type T or by an object that can be converted into a T.
1016 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001017 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001018
Steve Naroff8e9337f2008-01-21 23:53:58 +00001019 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1020 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001021 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001022 return Diag(InitLoc, diag::err_variable_object_no_init)
1023 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001024
Steve Naroffcb69fb72007-12-10 22:44:33 +00001025 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1026 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001027 // FIXME: Handle wide strings
1028 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1029 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001030
Douglas Gregor6428e762008-11-05 15:29:30 +00001031 // C++ [dcl.init]p14:
1032 // -- If the destination type is a (possibly cv-qualified) class
1033 // type:
1034 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1035 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1036 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1037
1038 // -- If the initialization is direct-initialization, or if it is
1039 // copy-initialization where the cv-unqualified version of the
1040 // source type is the same class as, or a derived class of, the
1041 // class of the destination, constructors are considered.
1042 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1043 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1044 CXXConstructorDecl *Constructor
1045 = PerformInitializationByConstructor(DeclType, &Init, 1,
1046 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001047 InitEntity,
1048 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001049 return Constructor == 0;
1050 }
1051
1052 // -- Otherwise (i.e., for the remaining copy-initialization
1053 // cases), user-defined conversion sequences that can
1054 // convert from the source type to the destination type or
1055 // (when a conversion function is used) to a derived class
1056 // thereof are enumerated as described in 13.3.1.4, and the
1057 // best one is chosen through overload resolution
1058 // (13.3). If the conversion cannot be done or is
1059 // ambiguous, the initialization is ill-formed. The
1060 // function selected is called with the initializer
1061 // expression as its argument; if the function is a
1062 // constructor, the call initializes a temporary of the
1063 // destination type.
1064 // FIXME: We're pretending to do copy elision here; return to
1065 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001066 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001067 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001068
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001069 if (InitEntity)
1070 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1071 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1072 << Init->getType() << Init->getSourceRange();
1073 else
1074 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1075 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1076 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001077 }
1078
Steve Naroffb2f72412008-09-29 20:07:05 +00001079 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001080 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001081 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1082 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001083
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001084 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregord45210d2009-01-30 22:09:00 +00001085 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001086
Douglas Gregor849afc32009-01-29 00:45:39 +00001087 bool hadError = CheckInitList(InitList, DeclType);
1088 Init = InitList;
1089 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +00001090}
1091
Douglas Gregor6704b312008-11-17 22:58:34 +00001092/// GetNameForDeclarator - Determine the full declaration name for the
1093/// given Declarator.
1094DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1095 switch (D.getKind()) {
1096 case Declarator::DK_Abstract:
1097 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1098 return DeclarationName();
1099
1100 case Declarator::DK_Normal:
1101 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1102 return DeclarationName(D.getIdentifier());
1103
1104 case Declarator::DK_Constructor: {
1105 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1106 Ty = Context.getCanonicalType(Ty);
1107 return Context.DeclarationNames.getCXXConstructorName(Ty);
1108 }
1109
1110 case Declarator::DK_Destructor: {
1111 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1112 Ty = Context.getCanonicalType(Ty);
1113 return Context.DeclarationNames.getCXXDestructorName(Ty);
1114 }
1115
1116 case Declarator::DK_Conversion: {
1117 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1118 Ty = Context.getCanonicalType(Ty);
1119 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1120 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001121
1122 case Declarator::DK_Operator:
1123 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1124 return Context.DeclarationNames.getCXXOperatorName(
1125 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001126 }
1127
1128 assert(false && "Unknown name kind");
1129 return DeclarationName();
1130}
1131
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001132/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1133/// functions Declaration and Definition are "nearly" matching. This
1134/// heuristic is used to improve diagnostics in the case where an
1135/// out-of-line member function definition doesn't match any
1136/// declaration within the class.
1137static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1138 FunctionDecl *Declaration,
1139 FunctionDecl *Definition) {
1140 if (Declaration->param_size() != Definition->param_size())
1141 return false;
1142 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1143 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1144 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1145
1146 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1147 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1148 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1149 return false;
1150 }
1151
1152 return true;
1153}
1154
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001155Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001156Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1157 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001158 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001159 DeclarationName Name = GetNameForDeclarator(D);
1160
Chris Lattner4b009652007-07-25 00:24:17 +00001161 // All of these full declarators require an identifier. If it doesn't have
1162 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001163 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001164 if (!D.getInvalidType()) // Reject this if we think it is valid.
1165 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001166 diag::err_declarator_need_ident)
1167 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001168 return 0;
1169 }
1170
Chris Lattnera7549902007-08-26 06:24:45 +00001171 // The scope passed in may not be a decl scope. Zip up the scope tree until
1172 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001173 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregor279272e2009-02-04 19:02:06 +00001174 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001175 S = S->getParent();
1176
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001177 DeclContext *DC;
Douglas Gregor09be81b2009-02-04 17:27:36 +00001178 NamedDecl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001179 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001180 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001181
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001182 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001183 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001184 DC = CurContext;
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001185 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001186 } else { // Something like "int foo::x;"
1187 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001188 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001189
1190 // C++ 7.3.1.2p2:
1191 // Members (including explicit specializations of templates) of a named
1192 // namespace can also be defined outside that namespace by explicit
1193 // qualification of the name being defined, provided that the entity being
1194 // defined was already declared in the namespace and the definition appears
1195 // after the point of declaration in a namespace that encloses the
1196 // declarations namespace.
1197 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001198 // Note that we only check the context at this point. We don't yet
1199 // have enough information to make sure that PrevDecl is actually
1200 // the declaration we want to match. For example, given:
1201 //
Douglas Gregor98341042008-12-12 08:25:50 +00001202 // class X {
1203 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001204 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001205 // };
1206 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001207 // void X::f(int) { } // ill-formed
1208 //
1209 // In this case, PrevDecl will point to the overload set
1210 // containing the two f's declared in X, but neither of them
1211 // matches.
1212 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001213 // The qualifying scope doesn't enclose the original declaration.
1214 // Emit diagnostic based on current scope.
1215 SourceLocation L = D.getIdentifierLoc();
1216 SourceRange R = D.getCXXScopeSpec().getRange();
1217 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001218 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001219 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001220 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001221 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001222 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001223 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001224 }
1225 }
1226
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001227 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001228 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001229 InvalidDecl = InvalidDecl
1230 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001231 // Just pretend that we didn't see the previous declaration.
1232 PrevDecl = 0;
1233 }
1234
Douglas Gregor1d661552008-04-13 21:07:44 +00001235 // In C++, the previous declaration we find might be a tag type
1236 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001237 // tag type. Note that this does does not apply if we're declaring a
1238 // typedef (C++ [dcl.typedef]p4).
1239 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1240 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001241 PrevDecl = 0;
1242
Chris Lattner82bb4792007-11-14 06:34:38 +00001243 QualType R = GetTypeForDeclarator(D, S);
1244 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1245
Chris Lattner4b009652007-07-25 00:24:17 +00001246 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001247 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1248 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001249 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001250 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1251 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001252 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001253 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1254 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001255 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001256
1257 if (New == 0)
1258 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001259
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001260 // Set the lexical context. If the declarator has a C++ scope specifier, the
1261 // lexical context will be different from the semantic context.
1262 New->setLexicalDeclContext(CurContext);
1263
Chris Lattner4b009652007-07-25 00:24:17 +00001264 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001265 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001266 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001267 // If any semantic error occurred, mark the decl as invalid.
1268 if (D.getInvalidType() || InvalidDecl)
1269 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001270
1271 return New;
1272}
1273
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001274NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001275Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001276 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001277 Decl* PrevDecl, bool& InvalidDecl) {
1278 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1279 if (D.getCXXScopeSpec().isSet()) {
1280 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1281 << D.getCXXScopeSpec().getRange();
1282 InvalidDecl = true;
1283 // Pretend we didn't see the scope specifier.
1284 DC = 0;
1285 }
1286
1287 // Check that there are no default arguments (C++ only).
1288 if (getLangOptions().CPlusPlus)
1289 CheckExtraCXXDefaultArguments(D);
1290
1291 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1292 if (!NewTD) return 0;
1293
1294 // Handle attributes prior to checking for duplicates in MergeVarDecl
1295 ProcessDeclAttributes(NewTD, D);
1296 // Merge the decl with the existing one if appropriate. If the decl is
1297 // in an outer scope, it isn't the same thing.
1298 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1299 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1300 if (NewTD == 0) return 0;
1301 }
1302
1303 if (S->getFnParent() == 0) {
1304 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1305 // then it shall have block scope.
1306 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1307 if (NewTD->getUnderlyingType()->isVariableArrayType())
1308 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1309 else
1310 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1311
1312 InvalidDecl = true;
1313 }
1314 }
1315 return NewTD;
1316}
1317
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001318NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001319Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001320 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001321 Decl* PrevDecl, bool& InvalidDecl) {
1322 DeclarationName Name = GetNameForDeclarator(D);
1323
1324 // Check that there are no default arguments (C++ only).
1325 if (getLangOptions().CPlusPlus)
1326 CheckExtraCXXDefaultArguments(D);
1327
1328 if (R.getTypePtr()->isObjCInterfaceType()) {
1329 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1330 << D.getIdentifier();
1331 InvalidDecl = true;
1332 }
1333
1334 VarDecl *NewVD;
1335 VarDecl::StorageClass SC;
1336 switch (D.getDeclSpec().getStorageClassSpec()) {
1337 default: assert(0 && "Unknown storage class!");
1338 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1339 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1340 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1341 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1342 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1343 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1344 case DeclSpec::SCS_mutable:
1345 // mutable can only appear on non-static class members, so it's always
1346 // an error here
1347 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1348 InvalidDecl = true;
1349 SC = VarDecl::None;
1350 break;
1351 }
1352
1353 IdentifierInfo *II = Name.getAsIdentifierInfo();
1354 if (!II) {
1355 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1356 << Name.getAsString();
1357 return 0;
1358 }
1359
1360 if (DC->isRecord()) {
1361 // This is a static data member for a C++ class.
1362 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1363 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001364 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001365 } else {
1366 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1367 if (S->getFnParent() == 0) {
1368 // C99 6.9p2: The storage-class specifiers auto and register shall not
1369 // appear in the declaration specifiers in an external declaration.
1370 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1371 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1372 InvalidDecl = true;
1373 }
1374 }
1375 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001376 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001377 // FIXME: Move to DeclGroup...
1378 D.getDeclSpec().getSourceRange().getBegin());
1379 NewVD->setThreadSpecified(ThreadSpecified);
1380 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001381 NewVD->setNextDeclarator(LastDeclarator);
1382
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001383 // Handle attributes prior to checking for duplicates in MergeVarDecl
1384 ProcessDeclAttributes(NewVD, D);
1385
1386 // Handle GNU asm-label extension (encoded as an attribute).
1387 if (Expr *E = (Expr*) D.getAsmLabel()) {
1388 // The parser guarantees this is a string.
1389 StringLiteral *SE = cast<StringLiteral>(E);
1390 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1391 SE->getByteLength())));
1392 }
1393
1394 // Emit an error if an address space was applied to decl with local storage.
1395 // This includes arrays of objects with address space qualifiers, but not
1396 // automatic variables that point to other address spaces.
1397 // ISO/IEC TR 18037 S5.1.2
1398 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1399 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1400 InvalidDecl = true;
1401 }
1402 // Merge the decl with the existing one if appropriate. If the decl is
1403 // in an outer scope, it isn't the same thing.
1404 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1405 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1406 // The user tried to define a non-static data member
1407 // out-of-line (C++ [dcl.meaning]p1).
1408 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1409 << D.getCXXScopeSpec().getRange();
1410 NewVD->Destroy(Context);
1411 return 0;
1412 }
1413
1414 NewVD = MergeVarDecl(NewVD, PrevDecl);
1415 if (NewVD == 0) return 0;
1416
1417 if (D.getCXXScopeSpec().isSet()) {
1418 // No previous declaration in the qualifying scope.
1419 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1420 << Name << D.getCXXScopeSpec().getRange();
1421 InvalidDecl = true;
1422 }
1423 }
1424 return NewVD;
1425}
1426
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001427NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001428Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001429 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001430 Decl* PrevDecl, bool IsFunctionDefinition,
1431 bool& InvalidDecl) {
1432 assert(R.getTypePtr()->isFunctionType());
1433
1434 DeclarationName Name = GetNameForDeclarator(D);
1435 FunctionDecl::StorageClass SC = FunctionDecl::None;
1436 switch (D.getDeclSpec().getStorageClassSpec()) {
1437 default: assert(0 && "Unknown storage class!");
1438 case DeclSpec::SCS_auto:
1439 case DeclSpec::SCS_register:
1440 case DeclSpec::SCS_mutable:
1441 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1442 InvalidDecl = true;
1443 break;
1444 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1445 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1446 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1447 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1448 }
1449
1450 bool isInline = D.getDeclSpec().isInlineSpecified();
1451 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1452 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1453
1454 FunctionDecl *NewFD;
1455 if (D.getKind() == Declarator::DK_Constructor) {
1456 // This is a C++ constructor declaration.
1457 assert(DC->isRecord() &&
1458 "Constructors can only be declared in a member context");
1459
1460 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1461
1462 // Create the new declaration
1463 NewFD = CXXConstructorDecl::Create(Context,
1464 cast<CXXRecordDecl>(DC),
1465 D.getIdentifierLoc(), Name, R,
1466 isExplicit, isInline,
1467 /*isImplicitlyDeclared=*/false);
1468
1469 if (InvalidDecl)
1470 NewFD->setInvalidDecl();
1471 } else if (D.getKind() == Declarator::DK_Destructor) {
1472 // This is a C++ destructor declaration.
1473 if (DC->isRecord()) {
1474 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1475
1476 NewFD = CXXDestructorDecl::Create(Context,
1477 cast<CXXRecordDecl>(DC),
1478 D.getIdentifierLoc(), Name, R,
1479 isInline,
1480 /*isImplicitlyDeclared=*/false);
1481
1482 if (InvalidDecl)
1483 NewFD->setInvalidDecl();
1484 } else {
1485 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1486
1487 // Create a FunctionDecl to satisfy the function definition parsing
1488 // code path.
1489 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001490 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001491 // FIXME: Move to DeclGroup...
1492 D.getDeclSpec().getSourceRange().getBegin());
1493 InvalidDecl = true;
1494 NewFD->setInvalidDecl();
1495 }
1496 } else if (D.getKind() == Declarator::DK_Conversion) {
1497 if (!DC->isRecord()) {
1498 Diag(D.getIdentifierLoc(),
1499 diag::err_conv_function_not_member);
1500 return 0;
1501 } else {
1502 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1503
1504 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1505 D.getIdentifierLoc(), Name, R,
1506 isInline, isExplicit);
1507
1508 if (InvalidDecl)
1509 NewFD->setInvalidDecl();
1510 }
1511 } else if (DC->isRecord()) {
1512 // This is a C++ method declaration.
1513 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1514 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001515 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001516 } else {
1517 NewFD = FunctionDecl::Create(Context, DC,
1518 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001519 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001520 // FIXME: Move to DeclGroup...
1521 D.getDeclSpec().getSourceRange().getBegin());
1522 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001523 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001524
1525 // Set the lexical context. If the declarator has a C++
1526 // scope specifier, the lexical context will be different
1527 // from the semantic context.
1528 NewFD->setLexicalDeclContext(CurContext);
1529
1530 // Handle GNU asm-label extension (encoded as an attribute).
1531 if (Expr *E = (Expr*) D.getAsmLabel()) {
1532 // The parser guarantees this is a string.
1533 StringLiteral *SE = cast<StringLiteral>(E);
1534 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1535 SE->getByteLength())));
1536 }
1537
1538 // Copy the parameter declarations from the declarator D to
1539 // the function declaration NewFD, if they are available.
1540 if (D.getNumTypeObjects() > 0) {
1541 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1542
1543 // Create Decl objects for each parameter, adding them to the
1544 // FunctionDecl.
1545 llvm::SmallVector<ParmVarDecl*, 16> Params;
1546
1547 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1548 // function that takes no arguments, not a function that takes a
1549 // single void argument.
1550 // We let through "const void" here because Sema::GetTypeForDeclarator
1551 // already checks for that case.
1552 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1553 FTI.ArgInfo[0].Param &&
1554 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1555 // empty arg list, don't push any params.
1556 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1557
1558 // In C++, the empty parameter-type-list must be spelled "void"; a
1559 // typedef of void is not permitted.
1560 if (getLangOptions().CPlusPlus &&
1561 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1562 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1563 }
1564 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1565 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1566 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1567 }
1568
1569 NewFD->setParams(Context, &Params[0], Params.size());
1570 } else if (R->getAsTypedefType()) {
1571 // When we're declaring a function with a typedef, as in the
1572 // following example, we'll need to synthesize (unnamed)
1573 // parameters for use in the declaration.
1574 //
1575 // @code
1576 // typedef void fn(int);
1577 // fn f;
1578 // @endcode
1579 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1580 if (!FT) {
1581 // This is a typedef of a function with no prototype, so we
1582 // don't need to do anything.
1583 } else if ((FT->getNumArgs() == 0) ||
1584 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1585 FT->getArgType(0)->isVoidType())) {
1586 // This is a zero-argument function. We don't need to do anything.
1587 } else {
1588 // Synthesize a parameter for each argument type.
1589 llvm::SmallVector<ParmVarDecl*, 16> Params;
1590 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1591 ArgType != FT->arg_type_end(); ++ArgType) {
1592 Params.push_back(ParmVarDecl::Create(Context, DC,
1593 SourceLocation(), 0,
1594 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001595 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001596 }
1597
1598 NewFD->setParams(Context, &Params[0], Params.size());
1599 }
1600 }
1601
1602 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1603 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1604 else if (isa<CXXDestructorDecl>(NewFD)) {
1605 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1606 Record->setUserDeclaredDestructor(true);
1607 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1608 // user-defined destructor.
1609 Record->setPOD(false);
1610 } else if (CXXConversionDecl *Conversion =
1611 dyn_cast<CXXConversionDecl>(NewFD))
1612 ActOnConversionDeclarator(Conversion);
1613
1614 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1615 if (NewFD->isOverloadedOperator() &&
1616 CheckOverloadedOperatorDeclaration(NewFD))
1617 NewFD->setInvalidDecl();
1618
1619 // Merge the decl with the existing one if appropriate. Since C functions
1620 // are in a flat namespace, make sure we consider decls in outer scopes.
1621 if (PrevDecl &&
1622 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1623 bool Redeclaration = false;
1624
1625 // If C++, determine whether NewFD is an overload of PrevDecl or
1626 // a declaration that requires merging. If it's an overload,
1627 // there's no more work to do here; we'll just add the new
1628 // function to the scope.
1629 OverloadedFunctionDecl::function_iterator MatchedDecl;
1630 if (!getLangOptions().CPlusPlus ||
1631 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1632 Decl *OldDecl = PrevDecl;
1633
1634 // If PrevDecl was an overloaded function, extract the
1635 // FunctionDecl that matched.
1636 if (isa<OverloadedFunctionDecl>(PrevDecl))
1637 OldDecl = *MatchedDecl;
1638
1639 // NewFD and PrevDecl represent declarations that need to be
1640 // merged.
1641 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1642
1643 if (NewFD == 0) return 0;
1644 if (Redeclaration) {
1645 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1646
1647 // An out-of-line member function declaration must also be a
1648 // definition (C++ [dcl.meaning]p1).
1649 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1650 !InvalidDecl) {
1651 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1652 << D.getCXXScopeSpec().getRange();
1653 NewFD->setInvalidDecl();
1654 }
1655 }
1656 }
1657
1658 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1659 // The user tried to provide an out-of-line definition for a
1660 // member function, but there was no such member function
1661 // declared (C++ [class.mfct]p2). For example:
1662 //
1663 // class X {
1664 // void f() const;
1665 // };
1666 //
1667 // void X::f() { } // ill-formed
1668 //
1669 // Complain about this problem, and attempt to suggest close
1670 // matches (e.g., those that differ only in cv-qualifiers and
1671 // whether the parameter types are references).
1672 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1673 << cast<CXXRecordDecl>(DC)->getDeclName()
1674 << D.getCXXScopeSpec().getRange();
1675 InvalidDecl = true;
1676
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001677 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1678 true);
1679 assert(!Prev.isAmbiguous() &&
1680 "Cannot have an ambiguity in previous-declaration lookup");
1681 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1682 Func != FuncEnd; ++Func) {
1683 if (isa<CXXMethodDecl>(*Func) &&
1684 isNearlyMatchingMemberFunction(Context, cast<FunctionDecl>(*Func),
1685 NewFD))
1686 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001687 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001688
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001689 PrevDecl = 0;
1690 }
1691 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001692
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001693 // Handle attributes. We need to have merged decls when handling attributes
1694 // (for example to check for conflicts, etc).
1695 ProcessDeclAttributes(NewFD, D);
1696
1697 if (getLangOptions().CPlusPlus) {
1698 // In C++, check default arguments now that we have merged decls.
1699 CheckCXXDefaultArguments(NewFD);
1700
1701 // An out-of-line member function declaration must also be a
1702 // definition (C++ [dcl.meaning]p1).
1703 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1704 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1705 << D.getCXXScopeSpec().getRange();
1706 InvalidDecl = true;
1707 }
1708 }
1709 return NewFD;
1710}
1711
Steve Narofffc08f5e2008-10-27 11:34:16 +00001712void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001713 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1714 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001715}
1716
Eli Friedman02c22ce2008-05-20 13:48:25 +00001717bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1718 switch (Init->getStmtClass()) {
1719 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001720 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001721 return true;
1722 case Expr::ParenExprClass: {
1723 const ParenExpr* PE = cast<ParenExpr>(Init);
1724 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1725 }
1726 case Expr::CompoundLiteralExprClass:
1727 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001728 case Expr::DeclRefExprClass:
1729 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001730 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001731 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1732 if (VD->hasGlobalStorage())
1733 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001734 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001735 return true;
1736 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001737 if (isa<FunctionDecl>(D))
1738 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001739 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001740 return true;
1741 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001742 case Expr::MemberExprClass: {
1743 const MemberExpr *M = cast<MemberExpr>(Init);
1744 if (M->isArrow())
1745 return CheckAddressConstantExpression(M->getBase());
1746 return CheckAddressConstantExpressionLValue(M->getBase());
1747 }
1748 case Expr::ArraySubscriptExprClass: {
1749 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1750 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1751 return CheckAddressConstantExpression(ASE->getBase()) ||
1752 CheckArithmeticConstantExpression(ASE->getIdx());
1753 }
1754 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001755 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001756 return false;
1757 case Expr::UnaryOperatorClass: {
1758 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1759
1760 // C99 6.6p9
1761 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001762 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001763
Steve Narofffc08f5e2008-10-27 11:34:16 +00001764 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001765 return true;
1766 }
1767 }
1768}
1769
1770bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1771 switch (Init->getStmtClass()) {
1772 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001773 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001774 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001775 case Expr::ParenExprClass:
1776 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001777 case Expr::StringLiteralClass:
1778 case Expr::ObjCStringLiteralClass:
1779 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001780 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001781 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001782 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1783 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1784 Builtin::BI__builtin___CFStringMakeConstantString)
1785 return false;
1786
Steve Narofffc08f5e2008-10-27 11:34:16 +00001787 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001788 return true;
1789
Eli Friedman02c22ce2008-05-20 13:48:25 +00001790 case Expr::UnaryOperatorClass: {
1791 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1792
1793 // C99 6.6p9
1794 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1795 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1796
1797 if (Exp->getOpcode() == UnaryOperator::Extension)
1798 return CheckAddressConstantExpression(Exp->getSubExpr());
1799
Steve Narofffc08f5e2008-10-27 11:34:16 +00001800 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001801 return true;
1802 }
1803 case Expr::BinaryOperatorClass: {
1804 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1805 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1806
1807 Expr *PExp = Exp->getLHS();
1808 Expr *IExp = Exp->getRHS();
1809 if (IExp->getType()->isPointerType())
1810 std::swap(PExp, IExp);
1811
1812 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1813 return CheckAddressConstantExpression(PExp) ||
1814 CheckArithmeticConstantExpression(IExp);
1815 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001816 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001817 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001818 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001819 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1820 // Check for implicit promotion
1821 if (SubExpr->getType()->isFunctionType() ||
1822 SubExpr->getType()->isArrayType())
1823 return CheckAddressConstantExpressionLValue(SubExpr);
1824 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001825
1826 // Check for pointer->pointer cast
1827 if (SubExpr->getType()->isPointerType())
1828 return CheckAddressConstantExpression(SubExpr);
1829
Eli Friedman1fad3c62008-08-25 20:46:57 +00001830 if (SubExpr->getType()->isIntegralType()) {
1831 // Check for the special-case of a pointer->int->pointer cast;
1832 // this isn't standard, but some code requires it. See
1833 // PR2720 for an example.
1834 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1835 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1836 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1837 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1838 if (IntWidth >= PointerWidth) {
1839 return CheckAddressConstantExpression(SubCast->getSubExpr());
1840 }
1841 }
1842 }
1843 }
1844 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001845 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001846 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001847
Steve Narofffc08f5e2008-10-27 11:34:16 +00001848 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001849 return true;
1850 }
1851 case Expr::ConditionalOperatorClass: {
1852 // FIXME: Should we pedwarn here?
1853 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1854 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001855 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001856 return true;
1857 }
1858 if (CheckArithmeticConstantExpression(Exp->getCond()))
1859 return true;
1860 if (Exp->getLHS() &&
1861 CheckAddressConstantExpression(Exp->getLHS()))
1862 return true;
1863 return CheckAddressConstantExpression(Exp->getRHS());
1864 }
1865 case Expr::AddrLabelExprClass:
1866 return false;
1867 }
1868}
1869
Eli Friedman998dffb2008-06-09 05:05:07 +00001870static const Expr* FindExpressionBaseAddress(const Expr* E);
1871
1872static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1873 switch (E->getStmtClass()) {
1874 default:
1875 return E;
1876 case Expr::ParenExprClass: {
1877 const ParenExpr* PE = cast<ParenExpr>(E);
1878 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1879 }
1880 case Expr::MemberExprClass: {
1881 const MemberExpr *M = cast<MemberExpr>(E);
1882 if (M->isArrow())
1883 return FindExpressionBaseAddress(M->getBase());
1884 return FindExpressionBaseAddressLValue(M->getBase());
1885 }
1886 case Expr::ArraySubscriptExprClass: {
1887 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1888 return FindExpressionBaseAddress(ASE->getBase());
1889 }
1890 case Expr::UnaryOperatorClass: {
1891 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1892
1893 if (Exp->getOpcode() == UnaryOperator::Deref)
1894 return FindExpressionBaseAddress(Exp->getSubExpr());
1895
1896 return E;
1897 }
1898 }
1899}
1900
1901static const Expr* FindExpressionBaseAddress(const Expr* E) {
1902 switch (E->getStmtClass()) {
1903 default:
1904 return E;
1905 case Expr::ParenExprClass: {
1906 const ParenExpr* PE = cast<ParenExpr>(E);
1907 return FindExpressionBaseAddress(PE->getSubExpr());
1908 }
1909 case Expr::UnaryOperatorClass: {
1910 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1911
1912 // C99 6.6p9
1913 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1914 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1915
1916 if (Exp->getOpcode() == UnaryOperator::Extension)
1917 return FindExpressionBaseAddress(Exp->getSubExpr());
1918
1919 return E;
1920 }
1921 case Expr::BinaryOperatorClass: {
1922 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1923
1924 Expr *PExp = Exp->getLHS();
1925 Expr *IExp = Exp->getRHS();
1926 if (IExp->getType()->isPointerType())
1927 std::swap(PExp, IExp);
1928
1929 return FindExpressionBaseAddress(PExp);
1930 }
1931 case Expr::ImplicitCastExprClass: {
1932 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1933
1934 // Check for implicit promotion
1935 if (SubExpr->getType()->isFunctionType() ||
1936 SubExpr->getType()->isArrayType())
1937 return FindExpressionBaseAddressLValue(SubExpr);
1938
1939 // Check for pointer->pointer cast
1940 if (SubExpr->getType()->isPointerType())
1941 return FindExpressionBaseAddress(SubExpr);
1942
1943 // We assume that we have an arithmetic expression here;
1944 // if we don't, we'll figure it out later
1945 return 0;
1946 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001947 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001948 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1949
1950 // Check for pointer->pointer cast
1951 if (SubExpr->getType()->isPointerType())
1952 return FindExpressionBaseAddress(SubExpr);
1953
1954 // We assume that we have an arithmetic expression here;
1955 // if we don't, we'll figure it out later
1956 return 0;
1957 }
1958 }
1959}
1960
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001961bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001962 switch (Init->getStmtClass()) {
1963 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001964 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001965 return true;
1966 case Expr::ParenExprClass: {
1967 const ParenExpr* PE = cast<ParenExpr>(Init);
1968 return CheckArithmeticConstantExpression(PE->getSubExpr());
1969 }
1970 case Expr::FloatingLiteralClass:
1971 case Expr::IntegerLiteralClass:
1972 case Expr::CharacterLiteralClass:
1973 case Expr::ImaginaryLiteralClass:
1974 case Expr::TypesCompatibleExprClass:
1975 case Expr::CXXBoolLiteralExprClass:
1976 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001977 case Expr::CallExprClass:
1978 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001979 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001980
1981 // Allow any constant foldable calls to builtins.
1982 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001983 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001984
Steve Narofffc08f5e2008-10-27 11:34:16 +00001985 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001986 return true;
1987 }
Douglas Gregor566782a2009-01-06 05:10:23 +00001988 case Expr::DeclRefExprClass:
1989 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001990 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1991 if (isa<EnumConstantDecl>(D))
1992 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001993 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001994 return true;
1995 }
1996 case Expr::CompoundLiteralExprClass:
1997 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1998 // but vectors are allowed to be magic.
1999 if (Init->getType()->isVectorType())
2000 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002001 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002002 return true;
2003 case Expr::UnaryOperatorClass: {
2004 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2005
2006 switch (Exp->getOpcode()) {
2007 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2008 // See C99 6.6p3.
2009 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002010 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002011 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002012 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002013 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2014 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002015 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002016 return true;
2017 case UnaryOperator::Extension:
2018 case UnaryOperator::LNot:
2019 case UnaryOperator::Plus:
2020 case UnaryOperator::Minus:
2021 case UnaryOperator::Not:
2022 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2023 }
2024 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002025 case Expr::SizeOfAlignOfExprClass: {
2026 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002027 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002028 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002029 return false;
2030 // alignof always evaluates to a constant.
2031 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002032 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002033 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002034 return true;
2035 }
2036 return false;
2037 }
2038 case Expr::BinaryOperatorClass: {
2039 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2040
2041 if (Exp->getLHS()->getType()->isArithmeticType() &&
2042 Exp->getRHS()->getType()->isArithmeticType()) {
2043 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2044 CheckArithmeticConstantExpression(Exp->getRHS());
2045 }
2046
Eli Friedman998dffb2008-06-09 05:05:07 +00002047 if (Exp->getLHS()->getType()->isPointerType() &&
2048 Exp->getRHS()->getType()->isPointerType()) {
2049 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2050 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2051
2052 // Only allow a null (constant integer) base; we could
2053 // allow some additional cases if necessary, but this
2054 // is sufficient to cover offsetof-like constructs.
2055 if (!LHSBase && !RHSBase) {
2056 return CheckAddressConstantExpression(Exp->getLHS()) ||
2057 CheckAddressConstantExpression(Exp->getRHS());
2058 }
2059 }
2060
Steve Narofffc08f5e2008-10-27 11:34:16 +00002061 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002062 return true;
2063 }
2064 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002065 case Expr::CStyleCastExprClass: {
Nuno Lopes7dd54222009-02-02 22:57:15 +00002066 const CastExpr *CE = cast<CastExpr>(Init);
2067 const Expr *SubExpr = CE->getSubExpr();
2068
Eli Friedmand662caa2008-09-01 22:08:17 +00002069 if (SubExpr->getType()->isArithmeticType())
2070 return CheckArithmeticConstantExpression(SubExpr);
2071
Eli Friedman266df142008-09-02 09:37:00 +00002072 if (SubExpr->getType()->isPointerType()) {
2073 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopes7dd54222009-02-02 22:57:15 +00002074 if (Base) {
2075 // the cast is only valid if done to a wide enough type
2076 if (Context.getTypeSize(CE->getType()) >=
2077 Context.getTypeSize(SubExpr->getType()))
2078 return false;
2079 } else {
2080 // If the pointer has a null base, this is an offsetof-like construct
2081 return CheckAddressConstantExpression(SubExpr);
2082 }
Eli Friedman266df142008-09-02 09:37:00 +00002083 }
2084
Steve Narofffc08f5e2008-10-27 11:34:16 +00002085 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002086 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002087 }
2088 case Expr::ConditionalOperatorClass: {
2089 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002090
2091 // If GNU extensions are disabled, we require all operands to be arithmetic
2092 // constant expressions.
2093 if (getLangOptions().NoExtensions) {
2094 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2095 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2096 CheckArithmeticConstantExpression(Exp->getRHS());
2097 }
2098
2099 // Otherwise, we have to emulate some of the behavior of fold here.
2100 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2101 // because it can constant fold things away. To retain compatibility with
2102 // GCC code, we see if we can fold the condition to a constant (which we
2103 // should always be able to do in theory). If so, we only require the
2104 // specified arm of the conditional to be a constant. This is a horrible
2105 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002106 Expr::EvalResult EvalResult;
2107 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2108 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002109 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002110 // won't be able to either. Use it to emit the diagnostic though.
2111 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002112 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002113 return Res;
2114 }
2115
2116 // Verify that the side following the condition is also a constant.
2117 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002118 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002119 std::swap(TrueSide, FalseSide);
2120
2121 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002122 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002123
2124 // Okay, the evaluated side evaluates to a constant, so we accept this.
2125 // Check to see if the other side is obviously not a constant. If so,
2126 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002127 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002128 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002129 diag::ext_typecheck_expression_not_constant_but_accepted)
2130 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002131 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002132 }
2133 }
2134}
2135
2136bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002137 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2138 Init = DIE->getInit();
2139
Nuno Lopese7280452008-07-07 16:46:50 +00002140 Init = Init->IgnoreParens();
2141
Nate Begemand6d2f772009-01-18 03:20:47 +00002142 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002143 return false;
2144
Eli Friedman02c22ce2008-05-20 13:48:25 +00002145 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2146 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2147 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2148
Nuno Lopese7280452008-07-07 16:46:50 +00002149 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2150 return CheckForConstantInitializer(e->getInitializer(), DclT);
2151
Douglas Gregorc9e012a2009-01-29 17:44:32 +00002152 if (isa<ImplicitValueInitExpr>(Init)) {
2153 // FIXME: In C++, check for non-POD types.
2154 return false;
2155 }
2156
Eli Friedman02c22ce2008-05-20 13:48:25 +00002157 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2158 unsigned numInits = Exp->getNumInits();
2159 for (unsigned i = 0; i < numInits; i++) {
2160 // FIXME: Need to get the type of the declaration for C++,
2161 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002162
Eli Friedman02c22ce2008-05-20 13:48:25 +00002163 if (CheckForConstantInitializer(Exp->getInit(i),
2164 Exp->getInit(i)->getType()))
2165 return true;
2166 }
2167 return false;
2168 }
2169
Anders Carlssonf6791c62008-12-05 05:09:56 +00002170 // FIXME: We can probably remove some of this code below, now that
2171 // Expr::Evaluate is doing the heavy lifting for scalars.
2172
Eli Friedman02c22ce2008-05-20 13:48:25 +00002173 if (Init->isNullPointerConstant(Context))
2174 return false;
2175 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002176 QualType InitTy = Context.getCanonicalType(Init->getType())
2177 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002178 if (InitTy == Context.BoolTy) {
2179 // Special handling for pointers implicitly cast to bool;
2180 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2181 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2182 Expr* SubE = ICE->getSubExpr();
2183 if (SubE->getType()->isPointerType() ||
2184 SubE->getType()->isArrayType() ||
2185 SubE->getType()->isFunctionType()) {
2186 return CheckAddressConstantExpression(Init);
2187 }
2188 }
2189 } else if (InitTy->isIntegralType()) {
2190 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002191 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002192 SubE = CE->getSubExpr();
2193 // Special check for pointer cast to int; we allow as an extension
2194 // an address constant cast to an integer if the integer
2195 // is of an appropriate width (this sort of code is apparently used
2196 // in some places).
2197 // FIXME: Add pedwarn?
2198 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2199 if (SubE && (SubE->getType()->isPointerType() ||
2200 SubE->getType()->isArrayType() ||
2201 SubE->getType()->isFunctionType())) {
2202 unsigned IntWidth = Context.getTypeSize(Init->getType());
2203 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2204 if (IntWidth >= PointerWidth)
2205 return CheckAddressConstantExpression(Init);
2206 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002207 }
2208
2209 return CheckArithmeticConstantExpression(Init);
2210 }
2211
2212 if (Init->getType()->isPointerType())
2213 return CheckAddressConstantExpression(Init);
2214
Eli Friedman25086f02008-05-30 18:14:48 +00002215 // An array type at the top level that isn't an init-list must
2216 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002217 if (Init->getType()->isArrayType())
2218 return false;
2219
Nuno Lopes1dc26762008-09-01 18:42:41 +00002220 if (Init->getType()->isFunctionType())
2221 return false;
2222
Steve Naroffdff3fb22008-10-02 17:12:56 +00002223 // Allow block exprs at top level.
2224 if (Init->getType()->isBlockPointerType())
2225 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002226
2227 // GCC cast to union extension
2228 // note: the validity of the cast expr is checked by CheckCastTypes()
2229 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2230 QualType T = C->getType();
2231 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2232 }
2233
Steve Narofffc08f5e2008-10-27 11:34:16 +00002234 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002235 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002236}
2237
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002238void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002239 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2240}
2241
2242/// AddInitializerToDecl - Adds the initializer Init to the
2243/// declaration dcl. If DirectInit is true, this is C++ direct
2244/// initialization rather than copy initialization.
2245void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002246 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002247 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002248 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002249
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002250 // If there is no declaration, there was an error parsing it. Just ignore
2251 // the initializer.
2252 if (RealDecl == 0) {
2253 delete Init;
2254 return;
2255 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002256
Steve Naroff420d0f52007-09-12 20:13:48 +00002257 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2258 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002259 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002260 RealDecl->setInvalidDecl();
2261 return;
2262 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002263 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002264 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002265 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002266 if (VDecl->isBlockVarDecl()) {
2267 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002268 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002269 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002270 VDecl->setInvalidDecl();
2271 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002272 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002273 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002274 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002275
2276 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2277 if (!getLangOptions().CPlusPlus) {
2278 if (SC == VarDecl::Static) // C99 6.7.8p4.
2279 CheckForConstantInitializer(Init, DclT);
2280 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002281 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002282 } else if (VDecl->isFileVarDecl()) {
2283 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002284 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002285 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002286 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002287 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002288 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002289
Anders Carlssonea7140a2008-08-22 05:00:02 +00002290 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2291 if (!getLangOptions().CPlusPlus) {
2292 // C99 6.7.8p4. All file scoped initializers need to be constant.
2293 CheckForConstantInitializer(Init, DclT);
2294 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002295 }
2296 // If the type changed, it means we had an incomplete type that was
2297 // completed by the initializer. For example:
2298 // int ary[] = { 1, 3, 5 };
2299 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002300 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002301 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002302 Init->setType(DclT);
2303 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002304
2305 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002306 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002307 return;
2308}
2309
Douglas Gregor81c29152008-10-29 00:13:59 +00002310void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2311 Decl *RealDecl = static_cast<Decl *>(dcl);
2312
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002313 // If there is no declaration, there was an error parsing it. Just ignore it.
2314 if (RealDecl == 0)
2315 return;
2316
Douglas Gregor81c29152008-10-29 00:13:59 +00002317 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2318 QualType Type = Var->getType();
2319 // C++ [dcl.init.ref]p3:
2320 // The initializer can be omitted for a reference only in a
2321 // parameter declaration (8.3.5), in the declaration of a
2322 // function return type, in the declaration of a class member
2323 // within its class declaration (9.2), and where the extern
2324 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002325 if (Type->isReferenceType() &&
2326 Var->getStorageClass() != VarDecl::Extern &&
2327 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002328 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002329 << Var->getDeclName()
2330 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002331 Var->setInvalidDecl();
2332 return;
2333 }
2334
2335 // C++ [dcl.init]p9:
2336 //
2337 // If no initializer is specified for an object, and the object
2338 // is of (possibly cv-qualified) non-POD class type (or array
2339 // thereof), the object shall be default-initialized; if the
2340 // object is of const-qualified type, the underlying class type
2341 // shall have a user-declared default constructor.
2342 if (getLangOptions().CPlusPlus) {
2343 QualType InitType = Type;
2344 if (const ArrayType *Array = Context.getAsArrayType(Type))
2345 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002346 if (Var->getStorageClass() != VarDecl::Extern &&
2347 Var->getStorageClass() != VarDecl::PrivateExtern &&
2348 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002349 const CXXConstructorDecl *Constructor
2350 = PerformInitializationByConstructor(InitType, 0, 0,
2351 Var->getLocation(),
2352 SourceRange(Var->getLocation(),
2353 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002354 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002355 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002356 if (!Constructor)
2357 Var->setInvalidDecl();
2358 }
2359 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002360
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002361#if 0
2362 // FIXME: Temporarily disabled because we are not properly parsing
2363 // linkage specifications on declarations, e.g.,
2364 //
2365 // extern "C" const CGPoint CGPointerZero;
2366 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002367 // C++ [dcl.init]p9:
2368 //
2369 // If no initializer is specified for an object, and the
2370 // object is of (possibly cv-qualified) non-POD class type (or
2371 // array thereof), the object shall be default-initialized; if
2372 // the object is of const-qualified type, the underlying class
2373 // type shall have a user-declared default
2374 // constructor. Otherwise, if no initializer is specified for
2375 // an object, the object and its subobjects, if any, have an
2376 // indeterminate initial value; if the object or any of its
2377 // subobjects are of const-qualified type, the program is
2378 // ill-formed.
2379 //
2380 // This isn't technically an error in C, so we don't diagnose it.
2381 //
2382 // FIXME: Actually perform the POD/user-defined default
2383 // constructor check.
2384 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002385 Context.getCanonicalType(Type).isConstQualified() &&
2386 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002387 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2388 << Var->getName()
2389 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002390#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002391 }
2392}
2393
Chris Lattner4b009652007-07-25 00:24:17 +00002394/// The declarators are chained together backwards, reverse the list.
2395Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2396 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002397 Decl *GroupDecl = static_cast<Decl*>(group);
2398 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002399 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002400
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002401 Decl *Group = dyn_cast<Decl>(GroupDecl);
2402 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002403 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002404 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002405 else { // reverse the list.
2406 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002407 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002408 Group->setNextDeclarator(NewGroup);
2409 NewGroup = Group;
2410 Group = Next;
2411 }
2412 }
2413 // Perform semantic analysis that depends on having fully processed both
2414 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002415 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002416 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2417 if (!IDecl)
2418 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002419 QualType T = IDecl->getType();
2420
Anders Carlsson68adbd12008-12-07 00:20:55 +00002421 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002422 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002423
2424 // FIXME: This won't give the correct result for
2425 // int a[10][n];
2426 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002427 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002428 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2429 SizeRange;
2430
Eli Friedman8ff07782008-02-15 18:16:39 +00002431 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002432 } else {
2433 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2434 // static storage duration, it shall not have a variable length array.
2435 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002436 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2437 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002438 IDecl->setInvalidDecl();
2439 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002440 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2441 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002442 IDecl->setInvalidDecl();
2443 }
2444 }
2445 } else if (T->isVariablyModifiedType()) {
2446 if (IDecl->isFileVarDecl()) {
2447 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2448 IDecl->setInvalidDecl();
2449 } else {
2450 if (IDecl->getStorageClass() == VarDecl::Extern) {
2451 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2452 IDecl->setInvalidDecl();
2453 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002454 }
2455 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002456
Steve Naroff6a0e2092007-09-12 14:07:44 +00002457 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2458 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002459 if (IDecl->isBlockVarDecl() &&
2460 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002461 if (!IDecl->isInvalidDecl() &&
2462 DiagnoseIncompleteType(IDecl->getLocation(), T,
2463 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002464 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002465 }
2466 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2467 // object that has file scope without an initializer, and without a
2468 // storage-class specifier or with the storage-class specifier "static",
2469 // constitutes a tentative definition. Note: A tentative definition with
2470 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002471 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002472 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002473 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2474 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002475 } else if (!IDecl->isInvalidDecl() &&
2476 DiagnoseIncompleteType(IDecl->getLocation(), T,
2477 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002478 // C99 6.9.2p3: If the declaration of an identifier for an object is
2479 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2480 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002481 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002482 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002483 if (IDecl->isFileVarDecl())
2484 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002485 }
2486 return NewGroup;
2487}
Steve Naroff91b03f72007-08-28 03:03:08 +00002488
Chris Lattner3e254fb2008-04-08 04:40:51 +00002489/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2490/// to introduce parameters into function prototype scope.
2491Sema::DeclTy *
2492Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002493 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002494
Chris Lattner3e254fb2008-04-08 04:40:51 +00002495 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002496 VarDecl::StorageClass StorageClass = VarDecl::None;
2497 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2498 StorageClass = VarDecl::Register;
2499 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002500 Diag(DS.getStorageClassSpecLoc(),
2501 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002502 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002503 }
2504 if (DS.isThreadSpecified()) {
2505 Diag(DS.getThreadSpecLoc(),
2506 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002507 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002508 }
2509
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002510 // Check that there are no default arguments inside the type of this
2511 // parameter (C++ only).
2512 if (getLangOptions().CPlusPlus)
2513 CheckExtraCXXDefaultArguments(D);
2514
Chris Lattner3e254fb2008-04-08 04:40:51 +00002515 // In this context, we *do not* check D.getInvalidType(). If the declarator
2516 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2517 // though it will not reflect the user specified type.
2518 QualType parmDeclType = GetTypeForDeclarator(D, S);
2519
2520 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2521
Chris Lattner4b009652007-07-25 00:24:17 +00002522 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2523 // Can this happen for params? We already checked that they don't conflict
2524 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002525 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002526 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00002527 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002528 if (PrevDecl->isTemplateParameter()) {
2529 // Maybe we will complain about the shadowed template parameter.
2530 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2531 // Just pretend that we didn't see the previous declaration.
2532 PrevDecl = 0;
2533 } else if (S->isDeclScope(PrevDecl)) {
2534 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002535
Chris Lattner310dea32009-01-21 02:38:50 +00002536 // Recover by removing the name
2537 II = 0;
2538 D.SetIdentifier(0, D.getIdentifierLoc());
2539 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002540 }
Chris Lattner4b009652007-07-25 00:24:17 +00002541 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002542
2543 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2544 // Doing the promotion here has a win and a loss. The win is the type for
2545 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2546 // code generator). The loss is the orginal type isn't preserved. For example:
2547 //
2548 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2549 // int blockvardecl[5];
2550 // sizeof(parmvardecl); // size == 4
2551 // sizeof(blockvardecl); // size == 20
2552 // }
2553 //
2554 // For expressions, all implicit conversions are captured using the
2555 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2556 //
2557 // FIXME: If a source translation tool needs to see the original type, then
2558 // we need to consider storing both types (in ParmVarDecl)...
2559 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002560 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002561 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002562 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002563 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002564 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002565
Chris Lattner3e254fb2008-04-08 04:40:51 +00002566 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2567 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002568 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002569 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002570
Chris Lattner3e254fb2008-04-08 04:40:51 +00002571 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002572 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002573
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002574 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2575 if (D.getCXXScopeSpec().isSet()) {
2576 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2577 << D.getCXXScopeSpec().getRange();
2578 New->setInvalidDecl();
2579 }
2580
Douglas Gregor8acb7272008-12-11 16:49:14 +00002581 // Add the parameter declaration into this scope.
2582 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002583 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002584 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002585
Chris Lattner9b384ca2008-06-29 00:02:00 +00002586 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002587 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002588
Chris Lattner4b009652007-07-25 00:24:17 +00002589}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002590
Douglas Gregor65075ec2009-01-23 16:23:13 +00002591void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002592 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2593 "Not a function declarator!");
2594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002595
Chris Lattner4b009652007-07-25 00:24:17 +00002596 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2597 // for a K&R function.
2598 if (!FTI.hasPrototype) {
2599 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002600 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002601 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2602 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002603 // Implicitly declare the argument as type 'int' for lack of a better
2604 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002605 DeclSpec DS;
2606 const char* PrevSpec; // unused
2607 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2608 PrevSpec);
2609 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2610 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002611 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002612 }
2613 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002614 }
2615}
2616
2617Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2618 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2619 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2620 "Not a function declarator!");
2621 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2622
2623 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002624 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002625 }
2626
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002627 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002628
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002629 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002630 ActOnDeclarator(ParentScope, D, 0,
2631 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002632}
2633
2634Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2635 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002636 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002637
2638 // See if this is a redefinition.
2639 const FunctionDecl *Definition;
2640 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002641 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002642 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002643 }
2644
Douglas Gregor8acb7272008-12-11 16:49:14 +00002645 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002646
Chris Lattner3e254fb2008-04-08 04:40:51 +00002647 // Check the validity of our function parameters
2648 CheckParmsForFunctionDef(FD);
2649
2650 // Introduce our parameters into the function scope
2651 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2652 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002653 Param->setOwningFunction(FD);
2654
Chris Lattner3e254fb2008-04-08 04:40:51 +00002655 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002656 if (Param->getIdentifier())
2657 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002658 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002659
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002660 // Checking attributes of current function definition
2661 // dllimport attribute.
2662 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2663 // dllimport attribute cannot be applied to definition.
2664 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2665 Diag(FD->getLocation(),
2666 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2667 << "dllimport";
2668 FD->setInvalidDecl();
2669 return FD;
2670 } else {
2671 // If a symbol previously declared dllimport is later defined, the
2672 // attribute is ignored in subsequent references, and a warning is
2673 // emitted.
2674 Diag(FD->getLocation(),
2675 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2676 << FD->getNameAsCString() << "dllimport";
2677 }
2678 }
Chris Lattner4b009652007-07-25 00:24:17 +00002679 return FD;
2680}
2681
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002682Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002683 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002684 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002685 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002686 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002687 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002688 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002689 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002690 } else
2691 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002692 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002693 // Verify and clean out per-function state.
2694
2695 // Check goto/label use.
2696 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2697 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2698 // Verify that we have no forward references left. If so, there was a goto
2699 // or address of a label taken, but no definition of it. Label fwd
2700 // definitions are indicated with a null substmt.
2701 if (I->second->getSubStmt() == 0) {
2702 LabelStmt *L = I->second;
2703 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002704 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002705
2706 // At this point, we have gotos that use the bogus label. Stitch it into
2707 // the function body so that they aren't leaked and that the AST is well
2708 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002709 if (Body) {
2710 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002711 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002712 } else {
2713 // The whole function wasn't parsed correctly, just delete this.
2714 delete L;
2715 }
Chris Lattner4b009652007-07-25 00:24:17 +00002716 }
2717 }
2718 LabelMap.clear();
2719
Steve Naroff99ee4302007-11-11 23:20:51 +00002720 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002721}
2722
Chris Lattner4b009652007-07-25 00:24:17 +00002723/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2724/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002725NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2726 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002727 // Extension in C99. Legal in C90, but warn about it.
2728 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002729 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002730 else
Chris Lattner65cae292008-11-19 08:23:25 +00002731 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002732
2733 // FIXME: handle stuff like:
2734 // void foo() { extern float X(); }
2735 // void bar() { X(); } <-- implicit decl for X in another scope.
2736
2737 // Set a Declarator for the implicit definition: int foo();
2738 const char *Dummy;
2739 DeclSpec DS;
2740 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2741 Error = Error; // Silence warning.
2742 assert(!Error && "Error setting up implicit decl!");
2743 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002744 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002745 D.SetIdentifier(&II, Loc);
2746
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002747 // Insert this function into translation-unit scope.
2748
2749 DeclContext *PrevDC = CurContext;
2750 CurContext = Context.getTranslationUnitDecl();
2751
Steve Naroff9104f3c2008-04-04 14:32:09 +00002752 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002753 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002754 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002755
2756 CurContext = PrevDC;
2757
Steve Naroff9104f3c2008-04-04 14:32:09 +00002758 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002759}
2760
2761
Chris Lattner82bb4792007-11-14 06:34:38 +00002762TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002763 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002764 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002765 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002766
2767 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002768 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2769 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002770 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002771 T);
2772 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002773 if (D.getInvalidType())
2774 NewTD->setInvalidDecl();
2775 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002776}
2777
Steve Naroff0acc9c92007-09-15 18:49:24 +00002778/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002779/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002780/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002781/// reference/declaration/definition of a tag.
Douglas Gregor279272e2009-02-04 19:02:06 +00002782///
2783/// This creates and returns template declarations if any template parameter
2784/// lists are given.
Douglas Gregor98b27542009-01-17 00:42:38 +00002785Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002786 SourceLocation KWLoc, const CXXScopeSpec &SS,
2787 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002788 AttributeList *Attr,
2789 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002790 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002791 assert((Name != 0 || TK == TK_Definition) &&
2792 "Nameless record must be a definition!");
Douglas Gregor279272e2009-02-04 19:02:06 +00002793 assert((TemplateParameterLists.size() == 0 || TK != TK_Reference) &&
2794 "Can't have a reference to a template");
2795 assert((TemplateParameterLists.size() == 0 ||
2796 TagSpec != DeclSpec::TST_enum) &&
2797 "No such thing as an enum template");
2798
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002799 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002800 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002801 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002802 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2803 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2804 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2805 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002806 }
2807
Douglas Gregorb748fc52009-01-12 22:49:06 +00002808 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002809 DeclContext *DC = CurContext;
Douglas Gregor09be81b2009-02-04 17:27:36 +00002810 NamedDecl *PrevDecl = 0;
Douglas Gregor279272e2009-02-04 19:02:06 +00002811 TemplateDecl *PrevTemplate = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002812
Douglas Gregor98b27542009-01-17 00:42:38 +00002813 bool Invalid = false;
2814
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002815 if (Name && SS.isNotEmpty()) {
2816 // We have a nested-name tag ('struct foo::bar').
2817
2818 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002819 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002820 Name = 0;
2821 goto CreateNewDecl;
2822 }
2823
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002824 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor2d87eb02009-02-03 00:34:39 +00002825 SearchDC = DC;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002826 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002827 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor7a7be652009-02-03 19:21:40 +00002828 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002829
2830 // A tag 'foo::bar' must already exist.
2831 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002832 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002833 Name = 0;
2834 goto CreateNewDecl;
2835 }
Chris Lattner310dea32009-01-21 02:38:50 +00002836 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002837 // If this is a named struct, check to see if there was a previous forward
2838 // declaration or definition.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002839 // FIXME: We're looking into outer scopes here, even when we
2840 // shouldn't be. Doing so can result in ambiguities that we
2841 // shouldn't be diagnosing.
Douglas Gregor362c8952009-02-03 19:26:08 +00002842 LookupResult R = LookupName(S, Name, LookupTagName,
2843 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor7a7be652009-02-03 19:21:40 +00002844 if (R.isAmbiguous()) {
2845 DiagnoseAmbiguousLookup(R, Name, NameLoc);
2846 // FIXME: This is not best way to recover from case like:
2847 //
2848 // struct S s;
2849 //
2850 // causes needless err_ovl_no_viable_function_in_init latter.
2851 Name = 0;
2852 PrevDecl = 0;
2853 Invalid = true;
2854 }
2855 else
Douglas Gregor09be81b2009-02-04 17:27:36 +00002856 PrevDecl = R;
Douglas Gregordb568cf2009-01-08 20:45:30 +00002857
2858 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2859 // FIXME: This makes sure that we ignore the contexts associated
2860 // with C structs, unions, and enums when looking for a matching
2861 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002862 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002863 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2864 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002865 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002866 }
2867
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002868 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002869 // Maybe we will complain about the shadowed template parameter.
2870 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2871 // Just pretend that we didn't see the previous declaration.
2872 PrevDecl = 0;
2873 }
2874
Ted Kremenekd4434152008-09-02 21:26:19 +00002875 if (PrevDecl) {
Douglas Gregor279272e2009-02-04 19:02:06 +00002876 // If we found a template, keep track of the template and its
2877 // underlying declaration.
2878 if ((PrevTemplate = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl)))
2879 PrevDecl = PrevTemplate->getTemplatedDecl();
2880
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002881 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002882 // If this is a use of a previous tag, or if the tag is already declared
2883 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002884 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002885 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002886 // Make sure that this wasn't declared as an enum and now used as a
2887 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002888 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002889 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002890 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002891 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002892 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002893 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002894 Invalid = true;
Douglas Gregor279272e2009-02-04 19:02:06 +00002895 // FIXME: Add template/non-template redecl check
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002896 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002897 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002898
Douglas Gregorae644892008-12-15 16:32:14 +00002899 // FIXME: In the future, return a variant or some other clue
2900 // for the consumer of this Decl to know it doesn't own it.
2901 // For our current ASTs this shouldn't be a problem, but will
2902 // need to be changed with DeclGroups.
2903 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002904 return PrevDecl;
Douglas Gregor279272e2009-02-04 19:02:06 +00002905
Douglas Gregorae644892008-12-15 16:32:14 +00002906 // Diagnose attempts to redefine a tag.
2907 if (TK == TK_Definition) {
2908 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2909 Diag(NameLoc, diag::err_redefinition) << Name;
2910 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002911 // If this is a redefinition, recover by making this
2912 // struct be anonymous, which will make any later
2913 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002914 Name = 0;
2915 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002916 Invalid = true;
2917 } else {
2918 // If the type is currently being defined, complain
2919 // about a nested redefinition.
2920 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2921 if (Tag->isBeingDefined()) {
2922 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2923 Diag(PrevTagDecl->getLocation(),
2924 diag::note_previous_definition);
2925 Name = 0;
2926 PrevDecl = 0;
2927 Invalid = true;
2928 }
Douglas Gregorae644892008-12-15 16:32:14 +00002929 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002930
Douglas Gregorae644892008-12-15 16:32:14 +00002931 // Okay, this is definition of a previously declared or referenced
2932 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002933 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002934 }
Douglas Gregorae644892008-12-15 16:32:14 +00002935 // If we get here we have (another) forward declaration or we
2936 // have a definition. Just create a new decl.
2937 } else {
2938 // If we get here, this is a definition of a new tag type in a nested
2939 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2940 // new decl/type. We set PrevDecl to NULL so that the entities
2941 // have distinct types.
2942 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002943 }
Douglas Gregorae644892008-12-15 16:32:14 +00002944 // If we get here, we're going to create a new Decl. If PrevDecl
2945 // is non-NULL, it's a definition of the tag declared by
2946 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002947 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00002948 // PrevDecl is a namespace, template, or anything else
2949 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002950 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002951 // The tag name clashes with a namespace name, issue an error and
2952 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002953 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002954 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002955 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002956 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002957 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002958 } else {
2959 // The existing declaration isn't relevant to us; we're in a
2960 // new scope, so clear out the previous declaration.
2961 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002962 }
Chris Lattner4b009652007-07-25 00:24:17 +00002963 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002964 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2965 (Kind != TagDecl::TK_enum)) {
2966 // C++ [basic.scope.pdecl]p5:
2967 // -- for an elaborated-type-specifier of the form
2968 //
2969 // class-key identifier
2970 //
2971 // if the elaborated-type-specifier is used in the
2972 // decl-specifier-seq or parameter-declaration-clause of a
2973 // function defined in namespace scope, the identifier is
2974 // declared as a class-name in the namespace that contains
2975 // the declaration; otherwise, except as a friend
2976 // declaration, the identifier is declared in the smallest
2977 // non-class, non-function-prototype scope that contains the
2978 // declaration.
2979 //
2980 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2981 // C structs and unions.
2982
2983 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002984 // FIXME: We would like to maintain the current DeclContext as the
2985 // lexical context,
Douglas Gregor2d87eb02009-02-03 00:34:39 +00002986 while (SearchDC->isRecord())
2987 SearchDC = SearchDC->getParent();
Douglas Gregorcab994d2009-01-09 22:42:13 +00002988
2989 // Find the scope where we'll be declaring the tag.
2990 while (S->isClassScope() ||
2991 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00002992 ((S->getFlags() & Scope::DeclScope) == 0) ||
2993 (S->getEntity() &&
2994 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00002995 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00002996 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002997
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002998CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002999
3000 // If there is an identifier, use the location of the identifier as the
3001 // location of the decl, otherwise use the location of the struct/union
3002 // keyword.
3003 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3004
Douglas Gregorae644892008-12-15 16:32:14 +00003005 // Otherwise, create a new declaration. If there is a previous
3006 // declaration of the same entity, the two will be linked via
3007 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003008 TagDecl *New;
Douglas Gregor279272e2009-02-04 19:02:06 +00003009 ClassTemplateDecl *NewTemplate = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +00003010
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003011 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003012 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3013 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003014 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003015 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003016 // If this is an undefined enum, warn.
3017 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003018 } else {
3019 // struct/union/class
3020
Chris Lattner4b009652007-07-25 00:24:17 +00003021 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3022 // struct X { int A; } D; D should chain to X.
Douglas Gregor279272e2009-02-04 19:02:06 +00003023 if (getLangOptions().CPlusPlus) {
Ted Kremenek770b11d2008-09-05 17:39:33 +00003024 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003025 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003026 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor279272e2009-02-04 19:02:06 +00003027
3028 // If there's are template parameters, then this must be a class
3029 // template. Create the template decl node also.
3030 // FIXME: Do we always create template decls? We may not for forward
3031 // declarations.
3032 // FIXME: What are we actually going to do with the template decl?
3033 if (TemplateParameterLists.size() > 0) {
3034 // FIXME: The allocation of the parameters is probably incorrect.
3035 // FIXME: Does the TemplateDecl have the same name as the class?
3036 TemplateParameterList *Params =
3037 TemplateParameterList::Create(Context,
3038 (Decl **)TemplateParameterLists.get(),
3039 TemplateParameterLists.size());
3040 NewTemplate = ClassTemplateDecl::Create(Context, DC, Loc,
3041 DeclarationName(Name), Params,
3042 New);
3043 }
3044 } else
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003045 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003046 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003047 }
Douglas Gregorae644892008-12-15 16:32:14 +00003048
3049 if (Kind != TagDecl::TK_enum) {
3050 // Handle #pragma pack: if the #pragma pack stack has non-default
3051 // alignment, make up a packed attribute for this decl. These
3052 // attributes are checked when the ASTContext lays out the
3053 // structure.
3054 //
3055 // It is important for implementing the correct semantics that this
3056 // happen here (in act on tag decl). The #pragma pack stack is
3057 // maintained as a result of parser callbacks which can occur at
3058 // many points during the parsing of a struct declaration (because
3059 // the #pragma tokens are effectively skipped over during the
3060 // parsing of the struct).
3061 if (unsigned Alignment = PackContext.getAlignment())
3062 New->addAttr(new PackedAttr(Alignment * 8));
3063 }
3064
Douglas Gregorb31f2942009-01-28 17:15:10 +00003065 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3066 // C++ [dcl.typedef]p3:
3067 // [...] Similarly, in a given scope, a class or enumeration
3068 // shall not be declared with the same name as a typedef-name
3069 // that is declared in that scope and refers to a type other
3070 // than the class or enumeration itself.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003071 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregorb31f2942009-01-28 17:15:10 +00003072 TypedefDecl *PrevTypedef = 0;
3073 if (Lookup.getKind() == LookupResult::Found)
3074 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3075
3076 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3077 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3078 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3079 Diag(Loc, diag::err_tag_definition_of_typedef)
3080 << Context.getTypeDeclType(New)
3081 << PrevTypedef->getUnderlyingType();
3082 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3083 Invalid = true;
3084 }
3085 }
3086
Douglas Gregor98b27542009-01-17 00:42:38 +00003087 if (Invalid)
3088 New->setInvalidDecl();
3089
Douglas Gregorae644892008-12-15 16:32:14 +00003090 if (Attr)
3091 ProcessDeclAttributeList(New, Attr);
3092
Douglas Gregor98b27542009-01-17 00:42:38 +00003093 // If we're declaring or defining a tag in function prototype scope
3094 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003095 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3096 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3097
Douglas Gregorae644892008-12-15 16:32:14 +00003098 // Set the lexical context. If the tag has a C++ scope specifier, the
3099 // lexical context will be different from the semantic context.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003100 New->setLexicalDeclContext(CurContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003101
3102 if (TK == TK_Definition)
3103 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003104
3105 // If this has an identifier, add it to the scope stack.
3106 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003107 S = getNonFieldDeclScope(S);
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003108 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003109 } else {
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003110 CurContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003111 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003112
Chris Lattner4b009652007-07-25 00:24:17 +00003113 return New;
3114}
3115
Douglas Gregordb568cf2009-01-08 20:45:30 +00003116void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003117 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003118 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3119
3120 // Enter the tag context.
3121 PushDeclContext(S, Tag);
3122
3123 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3124 FieldCollector->StartClass();
3125
3126 if (Record->getIdentifier()) {
3127 // C++ [class]p2:
3128 // [...] The class-name is also inserted into the scope of the
3129 // class itself; this is known as the injected-class-name. For
3130 // purposes of access checking, the injected-class-name is treated
3131 // as if it were a public member name.
3132 RecordDecl *InjectedClassName
3133 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3134 CurContext, Record->getLocation(),
3135 Record->getIdentifier(), Record);
3136 InjectedClassName->setImplicit();
3137 PushOnScopeChains(InjectedClassName, S);
3138 }
3139 }
3140}
3141
3142void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003143 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003144 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3145
3146 if (isa<CXXRecordDecl>(Tag))
3147 FieldCollector->FinishClass();
3148
3149 // Exit this scope of this tag's definition.
3150 PopDeclContext();
3151
3152 // Notify the consumer that we've defined a tag.
3153 Consumer.HandleTagDeclDefinition(Tag);
3154}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003155
Chris Lattnera73e2202008-11-12 21:17:48 +00003156/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3157/// types into constant array types in certain situations which would otherwise
3158/// be errors (for GCC compatibility).
3159static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3160 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003161 // This method tries to turn a variable array into a constant
3162 // array even when the size isn't an ICE. This is necessary
3163 // for compatibility with code that depends on gcc's buggy
3164 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003165 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3166 if (!VLATy) return QualType();
3167
Anders Carlsson8c3de802008-12-19 20:58:05 +00003168 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003169 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003170 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003171 return QualType();
3172
Anders Carlsson8c3de802008-12-19 20:58:05 +00003173 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3174 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes5ba3b262009-02-02 22:32:08 +00003175 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3176 return Context.getConstantArrayType(VLATy->getElementType(),
3177 Res, ArrayType::Normal, 0);
3178 return QualType();
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003179}
3180
Anders Carlsson108229a2008-12-06 20:33:04 +00003181bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003182 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003183 // FIXME: 6.7.2.1p4 - verify the field type.
3184
3185 llvm::APSInt Value;
3186 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3187 return true;
3188
Chris Lattner8464c372008-12-12 04:56:04 +00003189 // Zero-width bitfield is ok for anonymous field.
3190 if (Value == 0 && FieldName)
3191 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3192
3193 if (Value.isNegative())
3194 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003195
3196 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3197 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003198 if (TypeSize && Value.getZExtValue() > TypeSize)
3199 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3200 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003201
3202 return false;
3203}
3204
Steve Naroff0acc9c92007-09-15 18:49:24 +00003205/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003206/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003207Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003208 SourceLocation DeclStart,
3209 Declarator &D, ExprTy *BitfieldWidth) {
3210 IdentifierInfo *II = D.getIdentifier();
3211 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003212 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003213 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003214 if (II) Loc = D.getIdentifierLoc();
3215
3216 // FIXME: Unnamed fields can be handled in various different ways, for
3217 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003218
Chris Lattner4b009652007-07-25 00:24:17 +00003219 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003220 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3221 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003222
Chris Lattner4b009652007-07-25 00:24:17 +00003223 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3224 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003225 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003226 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003227 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003228 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003229 T = FixedTy;
3230 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003231 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003232 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003233 InvalidDecl = true;
3234 }
Chris Lattner4b009652007-07-25 00:24:17 +00003235 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003236
3237 if (BitWidth) {
3238 if (VerifyBitField(Loc, II, T, BitWidth))
3239 InvalidDecl = true;
3240 } else {
3241 // Not a bitfield.
3242
3243 // validate II.
3244
3245 }
3246
Chris Lattner4b009652007-07-25 00:24:17 +00003247 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003248 FieldDecl *NewFD;
3249
Douglas Gregor8acb7272008-12-11 16:49:14 +00003250 NewFD = FieldDecl::Create(Context, Record,
3251 Loc, II, T, BitWidth,
3252 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003253 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003254
Douglas Gregordb568cf2009-01-08 20:45:30 +00003255 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003256 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003257 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3258 && !isa<TagDecl>(PrevDecl)) {
3259 Diag(Loc, diag::err_duplicate_member) << II;
3260 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3261 NewFD->setInvalidDecl();
3262 Record->setInvalidDecl();
3263 }
3264 }
3265
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003266 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003267 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003268 if (!T->isPODType())
3269 cast<CXXRecordDecl>(Record)->setPOD(false);
3270 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003271
Chris Lattner9b384ca2008-06-29 00:02:00 +00003272 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003273
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003274 if (D.getInvalidType() || InvalidDecl)
3275 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003276
Douglas Gregordb568cf2009-01-08 20:45:30 +00003277 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003278 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003279 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003280 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003281
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003282 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003283}
3284
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003285/// TranslateIvarVisibility - Translate visibility from a token ID to an
3286/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003287static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003288TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003289 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003290 default: assert(0 && "Unknown visitibility kind");
3291 case tok::objc_private: return ObjCIvarDecl::Private;
3292 case tok::objc_public: return ObjCIvarDecl::Public;
3293 case tok::objc_protected: return ObjCIvarDecl::Protected;
3294 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003295 }
3296}
3297
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003298/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3299/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003300Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003301 SourceLocation DeclStart,
3302 Declarator &D, ExprTy *BitfieldWidth,
3303 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003304
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003305 IdentifierInfo *II = D.getIdentifier();
3306 Expr *BitWidth = (Expr*)BitfieldWidth;
3307 SourceLocation Loc = DeclStart;
3308 if (II) Loc = D.getIdentifierLoc();
3309
3310 // FIXME: Unnamed fields can be handled in various different ways, for
3311 // example, unnamed unions inject all members into the struct namespace!
3312
Anders Carlsson108229a2008-12-06 20:33:04 +00003313 QualType T = GetTypeForDeclarator(D, S);
3314 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3315 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003316
3317 if (BitWidth) {
3318 // TODO: Validate.
3319 //printf("WARNING: BITFIELDS IGNORED!\n");
3320
3321 // 6.7.2.1p3
3322 // 6.7.2.1p4
3323
3324 } else {
3325 // Not a bitfield.
3326
3327 // validate II.
3328
3329 }
3330
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003331 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3332 // than a variably modified type.
3333 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003334 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003335 InvalidDecl = true;
3336 }
3337
Ted Kremenek173dd312008-07-23 18:04:17 +00003338 // Get the visibility (access control) for this ivar.
3339 ObjCIvarDecl::AccessControl ac =
3340 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3341 : ObjCIvarDecl::None;
3342
3343 // Construct the decl.
3344 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003345 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003346
Douglas Gregordb568cf2009-01-08 20:45:30 +00003347 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003348 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003349 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3350 && !isa<TagDecl>(PrevDecl)) {
3351 Diag(Loc, diag::err_duplicate_member) << II;
3352 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3353 NewID->setInvalidDecl();
3354 }
3355 }
3356
Ted Kremenek173dd312008-07-23 18:04:17 +00003357 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003358 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003359
3360 if (D.getInvalidType() || InvalidDecl)
3361 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003362
Douglas Gregordb568cf2009-01-08 20:45:30 +00003363 if (II) {
3364 // FIXME: When interfaces are DeclContexts, we'll need to add
3365 // these to the interface.
3366 S->AddDecl(NewID);
3367 IdResolver.AddDecl(NewID);
3368 }
3369
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003370 return NewID;
3371}
3372
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003373void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003374 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003375 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003376 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003377 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003378 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3379 assert(EnclosingDecl && "missing record or interface decl");
3380 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3381
Chris Lattner4b009652007-07-25 00:24:17 +00003382 // Verify that all the fields are okay.
3383 unsigned NumNamedMembers = 0;
3384 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003385
Chris Lattner4b009652007-07-25 00:24:17 +00003386 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003387 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3388 assert(FD && "missing field decl");
3389
Chris Lattner4b009652007-07-25 00:24:17 +00003390 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003391 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003392
Douglas Gregordb568cf2009-01-08 20:45:30 +00003393 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003394 // Remember all fields written by the user.
3395 RecFields.push_back(FD);
3396 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003397
Chris Lattner4b009652007-07-25 00:24:17 +00003398 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003399 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003400 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003401 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003402 FD->setInvalidDecl();
3403 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003404 continue;
3405 }
Chris Lattner4b009652007-07-25 00:24:17 +00003406 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3407 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003408 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003409 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3410 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003411 FD->setInvalidDecl();
3412 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003413 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003414 }
Chris Lattner4b009652007-07-25 00:24:17 +00003415 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003416 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003417 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003418 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3419 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003420 FD->setInvalidDecl();
3421 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003422 continue;
3423 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003424 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003425 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003426 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003427 FD->setInvalidDecl();
3428 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003429 continue;
3430 }
Chris Lattner4b009652007-07-25 00:24:17 +00003431 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003432 if (Record)
3433 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003434 }
Chris Lattner4b009652007-07-25 00:24:17 +00003435 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3436 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003437 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003438 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3439 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003440 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003441 Record->setHasFlexibleArrayMember(true);
3442 } else {
3443 // If this is a struct/class and this is not the last element, reject
3444 // it. Note that GCC supports variable sized arrays in the middle of
3445 // structures.
3446 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003447 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003448 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003449 FD->setInvalidDecl();
3450 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003451 continue;
3452 }
Chris Lattner4b009652007-07-25 00:24:17 +00003453 // We support flexible arrays at the end of structs in other structs
3454 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003455 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003456 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003457 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003458 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003459 }
3460 }
3461 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003462 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003463 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003464 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003465 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003466 FD->setInvalidDecl();
3467 EnclosingDecl->setInvalidDecl();
3468 continue;
3469 }
Chris Lattner4b009652007-07-25 00:24:17 +00003470 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003471 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003472 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003473 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003474
Chris Lattner4b009652007-07-25 00:24:17 +00003475 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003476 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003477 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003478 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003479 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003480 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003481 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003482 // Must enforce the rule that ivars in the base classes may not be
3483 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003484 if (ID->getSuperClass()) {
3485 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3486 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3487 ObjCIvarDecl* Ivar = (*IVI);
3488 IdentifierInfo *II = Ivar->getIdentifier();
3489 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3490 if (prevIvar) {
3491 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003492 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003493 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003494 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003495 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003496 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003497 else if (ObjCImplementationDecl *IMPDecl =
3498 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003499 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3500 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003501 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003502 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003503 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003504
3505 if (Attr)
3506 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003507}
3508
Steve Naroff0acc9c92007-09-15 18:49:24 +00003509Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003510 DeclTy *lastEnumConst,
3511 SourceLocation IdLoc, IdentifierInfo *Id,
3512 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003513 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003514 EnumConstantDecl *LastEnumConst =
3515 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3516 Expr *Val = static_cast<Expr*>(val);
3517
Chris Lattnera7549902007-08-26 06:24:45 +00003518 // The scope passed in may not be a decl scope. Zip up the scope tree until
3519 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003520 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003521
Chris Lattner4b009652007-07-25 00:24:17 +00003522 // Verify that there isn't already something declared with this name in this
3523 // scope.
Douglas Gregor09be81b2009-02-04 17:27:36 +00003524 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003525 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003526 // Maybe we will complain about the shadowed template parameter.
3527 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3528 // Just pretend that we didn't see the previous declaration.
3529 PrevDecl = 0;
3530 }
3531
3532 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003533 // When in C++, we may get a TagDecl with the same name; in this case the
3534 // enum constant will 'hide' the tag.
3535 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3536 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003537 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003538 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003539 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003540 else
Chris Lattner65cae292008-11-19 08:23:25 +00003541 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003542 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003543 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003544 return 0;
3545 }
3546 }
3547
3548 llvm::APSInt EnumVal(32);
3549 QualType EltTy;
3550 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003551 // Make sure to promote the operand type to int.
3552 UsualUnaryConversions(Val);
3553
Chris Lattner4b009652007-07-25 00:24:17 +00003554 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3555 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003556 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003557 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003558 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003559 } else {
3560 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003561 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003562 }
3563
3564 if (!Val) {
3565 if (LastEnumConst) {
3566 // Assign the last value + 1.
3567 EnumVal = LastEnumConst->getInitVal();
3568 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003569
3570 // Check for overflow on increment.
3571 if (EnumVal < LastEnumConst->getInitVal())
3572 Diag(IdLoc, diag::warn_enum_value_overflow);
3573
Chris Lattnere7f53a42007-08-27 17:37:24 +00003574 EltTy = LastEnumConst->getType();
3575 } else {
3576 // First value, set to zero.
3577 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003578 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003579 }
Chris Lattner4b009652007-07-25 00:24:17 +00003580 }
3581
Chris Lattnere4650482008-03-15 06:12:44 +00003582 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003583 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003584 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003585
3586 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003587 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003588
Chris Lattner4b009652007-07-25 00:24:17 +00003589 return New;
3590}
3591
Steve Naroffb0726b82008-08-07 14:08:16 +00003592// FIXME: For consistency with ActOnFields(), we should have the parser
3593// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003594void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003595 DeclTy **Elements, unsigned NumElements) {
3596 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003597 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003598
Chris Lattner435c3fd2007-08-28 05:10:31 +00003599 // TODO: If the result value doesn't fit in an int, it must be a long or long
3600 // long value. ISO C does not support this, but GCC does as an extension,
3601 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003602 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003603
Chris Lattner206754a2007-08-28 06:15:15 +00003604 // Verify that all the values are okay, compute the size of the values, and
3605 // reverse the list.
3606 unsigned NumNegativeBits = 0;
3607 unsigned NumPositiveBits = 0;
3608
3609 // Keep track of whether all elements have type int.
3610 bool AllElementsInt = true;
3611
Chris Lattner4b009652007-07-25 00:24:17 +00003612 for (unsigned i = 0; i != NumElements; ++i) {
3613 EnumConstantDecl *ECD =
3614 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3615 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003616
3617 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003618 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003619 assert(InitVal.getBitWidth() >= IntWidth &&
3620 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003621 if (InitVal.getBitWidth() > IntWidth) {
3622 llvm::APSInt V(InitVal);
3623 V.trunc(IntWidth);
3624 V.extend(InitVal.getBitWidth());
3625 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003626 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3627 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003628 }
Chris Lattner206754a2007-08-28 06:15:15 +00003629
3630 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003631 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003632 NumPositiveBits = std::max(NumPositiveBits,
3633 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003634 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003635 NumNegativeBits = std::max(NumNegativeBits,
3636 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003637
Chris Lattner206754a2007-08-28 06:15:15 +00003638 // Keep track of whether every enum element has type int (very commmon).
3639 if (AllElementsInt)
3640 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003641 }
3642
Chris Lattner206754a2007-08-28 06:15:15 +00003643 // Figure out the type that should be used for this enum.
3644 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3645 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003646 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003647
3648 if (NumNegativeBits) {
3649 // If there is a negative value, figure out the smallest integer type (of
3650 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003651 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003652 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003653 BestWidth = IntWidth;
3654 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003655 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003656
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003657 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003658 BestType = Context.LongTy;
3659 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003660 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003661
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003662 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003663 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3664 BestType = Context.LongLongTy;
3665 }
3666 }
3667 } else {
3668 // If there is no negative value, figure out which of uint, ulong, ulonglong
3669 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003670 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003671 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003672 BestWidth = IntWidth;
3673 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003674 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003675 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003676 } else {
3677 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003678 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003679 "How could an initializer get larger than ULL?");
3680 BestType = Context.UnsignedLongLongTy;
3681 }
3682 }
3683
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003684 // Loop over all of the enumerator constants, changing their types to match
3685 // the type of the enum if needed.
3686 for (unsigned i = 0; i != NumElements; ++i) {
3687 EnumConstantDecl *ECD =
3688 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3689 if (!ECD) continue; // Already issued a diagnostic.
3690
3691 // Standard C says the enumerators have int type, but we allow, as an
3692 // extension, the enumerators to be larger than int size. If each
3693 // enumerator value fits in an int, type it as an int, otherwise type it the
3694 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3695 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003696 if (ECD->getType() == Context.IntTy) {
3697 // Make sure the init value is signed.
3698 llvm::APSInt IV = ECD->getInitVal();
3699 IV.setIsSigned(true);
3700 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003701
3702 if (getLangOptions().CPlusPlus)
3703 // C++ [dcl.enum]p4: Following the closing brace of an
3704 // enum-specifier, each enumerator has the type of its
3705 // enumeration.
3706 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003707 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003708 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003709
3710 // Determine whether the value fits into an int.
3711 llvm::APSInt InitVal = ECD->getInitVal();
3712 bool FitsInInt;
3713 if (InitVal.isUnsigned() || !InitVal.isNegative())
3714 FitsInInt = InitVal.getActiveBits() < IntWidth;
3715 else
3716 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3717
3718 // If it fits into an integer type, force it. Otherwise force it to match
3719 // the enum decl type.
3720 QualType NewTy;
3721 unsigned NewWidth;
3722 bool NewSign;
3723 if (FitsInInt) {
3724 NewTy = Context.IntTy;
3725 NewWidth = IntWidth;
3726 NewSign = true;
3727 } else if (ECD->getType() == BestType) {
3728 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003729 if (getLangOptions().CPlusPlus)
3730 // C++ [dcl.enum]p4: Following the closing brace of an
3731 // enum-specifier, each enumerator has the type of its
3732 // enumeration.
3733 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003734 continue;
3735 } else {
3736 NewTy = BestType;
3737 NewWidth = BestWidth;
3738 NewSign = BestType->isSignedIntegerType();
3739 }
3740
3741 // Adjust the APSInt value.
3742 InitVal.extOrTrunc(NewWidth);
3743 InitVal.setIsSigned(NewSign);
3744 ECD->setInitVal(InitVal);
3745
3746 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003747 if (ECD->getInitExpr())
3748 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3749 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003750 if (getLangOptions().CPlusPlus)
3751 // C++ [dcl.enum]p4: Following the closing brace of an
3752 // enum-specifier, each enumerator has the type of its
3753 // enumeration.
3754 ECD->setType(EnumType);
3755 else
3756 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003757 }
Chris Lattner206754a2007-08-28 06:15:15 +00003758
Douglas Gregor8acb7272008-12-11 16:49:14 +00003759 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003760}
3761
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003762Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003763 ExprArg expr) {
3764 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3765
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003766 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003767}
3768
Douglas Gregorad17e372008-12-16 22:23:02 +00003769
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003770void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3771 ExprTy *alignment, SourceLocation PragmaLoc,
3772 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3773 Expr *Alignment = static_cast<Expr *>(alignment);
3774
3775 // If specified then alignment must be a "small" power of two.
3776 unsigned AlignmentVal = 0;
3777 if (Alignment) {
3778 llvm::APSInt Val;
3779 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3780 !Val.isPowerOf2() ||
3781 Val.getZExtValue() > 16) {
3782 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3783 delete Alignment;
3784 return; // Ignore
3785 }
3786
3787 AlignmentVal = (unsigned) Val.getZExtValue();
3788 }
3789
3790 switch (Kind) {
3791 case Action::PPK_Default: // pack([n])
3792 PackContext.setAlignment(AlignmentVal);
3793 break;
3794
3795 case Action::PPK_Show: // pack(show)
3796 // Show the current alignment, making sure to show the right value
3797 // for the default.
3798 AlignmentVal = PackContext.getAlignment();
3799 // FIXME: This should come from the target.
3800 if (AlignmentVal == 0)
3801 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003802 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003803 break;
3804
3805 case Action::PPK_Push: // pack(push [, id] [, [n])
3806 PackContext.push(Name);
3807 // Set the new alignment if specified.
3808 if (Alignment)
3809 PackContext.setAlignment(AlignmentVal);
3810 break;
3811
3812 case Action::PPK_Pop: // pack(pop [, id] [, n])
3813 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3814 // "#pragma pack(pop, identifier, n) is undefined"
3815 if (Alignment && Name)
3816 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3817
3818 // Do the pop.
3819 if (!PackContext.pop(Name)) {
3820 // If a name was specified then failure indicates the name
3821 // wasn't found. Otherwise failure indicates the stack was
3822 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003823 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3824 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003825
3826 // FIXME: Warn about popping named records as MSVC does.
3827 } else {
3828 // Pop succeeded, set the new alignment if specified.
3829 if (Alignment)
3830 PackContext.setAlignment(AlignmentVal);
3831 }
3832 break;
3833
3834 default:
3835 assert(0 && "Invalid #pragma pack kind.");
3836 }
3837}
3838
3839bool PragmaPackStack::pop(IdentifierInfo *Name) {
3840 if (Stack.empty())
3841 return false;
3842
3843 // If name is empty just pop top.
3844 if (!Name) {
3845 Alignment = Stack.back().first;
3846 Stack.pop_back();
3847 return true;
3848 }
3849
3850 // Otherwise, find the named record.
3851 for (unsigned i = Stack.size(); i != 0; ) {
3852 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003853 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003854 // Found it, pop up to and including this record.
3855 Alignment = Stack[i].first;
3856 Stack.erase(Stack.begin() + i, Stack.end());
3857 return true;
3858 }
3859 }
3860
3861 return false;
3862}