blob: 22b8ef2b1f7d24bd3ce3a409cc37e0db42a2272b [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 Gregorf2dbdca2009-02-04 19:16:12 +000034/// \brief If the identifier refers to a type name within this scope,
35/// return the declaration of that type.
36///
37/// This routine performs ordinary name lookup of the identifier II
38/// within the given scope, with optional C++ scope specifier SS, to
39/// determine whether the name refers to a type. If so, returns the
40/// declaration corresponding to that type. Otherwise, returns NULL.
41///
42/// If name lookup results in an ambiguity, this routine will complain
43/// and then return NULL.
44Sema::DeclTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor1075a162009-02-04 17:00:24 +000045 Scope *S, const CXXScopeSpec *SS) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000046 Decl *IIDecl = 0;
Douglas Gregor52ae30c2009-01-30 01:04:22 +000047 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000048 switch (Result.getKind()) {
Steve Naroffa4e04982009-01-29 18:09:31 +000049 case LookupResult::NotFound:
50 case LookupResult::FoundOverloaded:
Douglas Gregor1075a162009-02-04 17:00:24 +000051 return 0;
52
Steve Naroffa4e04982009-01-29 18:09:31 +000053 case LookupResult::AmbiguousBaseSubobjectTypes:
54 case LookupResult::AmbiguousBaseSubobjects:
Douglas Gregor7a7be652009-02-03 19:21:40 +000055 case LookupResult::AmbiguousReference:
Douglas Gregor1075a162009-02-04 17:00:24 +000056 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
Steve Naroffa4e04982009-01-29 18:09:31 +000057 return 0;
Douglas Gregor1075a162009-02-04 17:00:24 +000058
Steve Naroffa4e04982009-01-29 18:09:31 +000059 case LookupResult::Found:
60 IIDecl = Result.getAsDecl();
61 break;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000062 }
63
Steve Naroffa4e04982009-01-29 18:09:31 +000064 if (IIDecl) {
65 if (isa<TypedefDecl>(IIDecl) ||
66 isa<ObjCInterfaceDecl>(IIDecl) ||
67 isa<TagDecl>(IIDecl) ||
68 isa<TemplateTypeParmDecl>(IIDecl))
69 return IIDecl;
70 }
Steve Naroff81f1bba2007-09-06 21:24:23 +000071 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000072}
73
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000074DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000075 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000076 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000077 if (MD->isOutOfLineDefinition())
78 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000079
80 // A C++ inline method is parsed *after* the topmost class it was declared in
81 // is fully parsed (it's "complete").
82 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000083 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000084 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
85 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000086 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000087 DC = RD;
88
89 // Return the declaration context of the topmost class the inline method is
90 // declared in.
91 return DC;
92 }
93
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000094 if (isa<ObjCMethodDecl>(DC))
95 return Context.getTranslationUnitDecl();
96
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000097 if (Decl *D = dyn_cast<Decl>(DC))
98 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000099
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +0000100 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000101}
102
Douglas Gregor8acb7272008-12-11 16:49:14 +0000103void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000104 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +0000105 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000106 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000107 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000108}
109
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000110void Sema::PopDeclContext() {
111 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000112
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000113 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000114}
115
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000116/// Add this decl to the scope shadowed decl chains.
117void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000118 // Move up the scope chain until we find the nearest enclosing
119 // non-transparent context. The declaration will be introduced into this
120 // scope.
121 while (S->getEntity() &&
122 ((DeclContext *)S->getEntity())->isTransparentContext())
123 S = S->getParent();
124
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000125 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000126
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000127 // Add scoped declarations into their context, so that they can be
128 // found later. Declarations without a context won't be inserted
129 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000130 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000131
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000132 // C++ [basic.scope]p4:
133 // -- exactly one declaration shall declare a class name or
134 // enumeration name that is not a typedef name and the other
135 // declarations shall all refer to the same object or
136 // enumerator, or all refer to functions and function templates;
137 // in this case the class name or enumeration name is hidden.
138 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
139 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000140 if (CurContext->getLookupContext()
141 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000142 // We're pushing the tag into the current context, which might
143 // require some reshuffling in the identifier resolver.
144 IdentifierResolver::iterator
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000145 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000146 IEnd = IdResolver.end();
147 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
148 NamedDecl *PrevDecl = *I;
149 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
150 PrevDecl = *I, ++I) {
151 if (TD->declarationReplaces(*I)) {
152 // This is a redeclaration. Remove it from the chain and
153 // break out, so that we'll add in the shadowed
154 // declaration.
155 S->RemoveDecl(*I);
156 if (PrevDecl == *I) {
157 IdResolver.RemoveDecl(*I);
158 IdResolver.AddDecl(TD);
159 return;
160 } else {
161 IdResolver.RemoveDecl(*I);
162 break;
163 }
164 }
165 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000166
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000167 // There is already a declaration with the same name in the same
168 // scope, which is not a tag declaration. It must be found
169 // before we find the new declaration, so insert the new
170 // declaration at the end of the chain.
171 IdResolver.AddShadowedDecl(TD, PrevDecl);
172
173 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000174 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000175 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000176 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000177 // We are pushing the name of a function, which might be an
178 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000179 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000180 IdentifierResolver::iterator Redecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000181 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000182 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000192
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000194}
195
Steve Naroff9637a9b2007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000200
Chris Lattner4b009652007-07-25 00:24:17 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000205
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000210
Douglas Gregor8acb7272008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000213 }
214}
215
Steve Naroffe57c21a2008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000221 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222
Steve Naroff6384a012008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000224}
225
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Chris Lattnera9c87f22008-05-05 22:18:14 +0000258void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000259 if (!Context.getBuiltinVaListType().isNull())
260 return;
261
262 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor09be81b2009-02-04 17:27:36 +0000263 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000264 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000265 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
266}
267
Chris Lattner4b009652007-07-25 00:24:17 +0000268/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
269/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000270NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
271 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000272 Builtin::ID BID = (Builtin::ID)bid;
273
Chris Lattnerb23469f2008-09-28 05:54:29 +0000274 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000275 InitBuiltinVaListType();
276
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000277 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000278 FunctionDecl *New = FunctionDecl::Create(Context,
279 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000280 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000281 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000282
Chris Lattnera9c87f22008-05-05 22:18:14 +0000283 // Create Decl objects for each parameter, adding them to the
284 // FunctionDecl.
285 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
286 llvm::SmallVector<ParmVarDecl*, 16> Params;
287 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
288 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000289 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000290 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000291 }
292
293
294
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000295 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000296 // FIXME: This is hideous. We need to teach PushOnScopeChains to
297 // relate Scopes to DeclContexts, and probably eliminate CurContext
298 // entirely, but we're not there yet.
299 DeclContext *SavedContext = CurContext;
300 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000301 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000302 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000303 return New;
304}
305
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000306/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
307/// everything from the standard library is defined.
308NamespaceDecl *Sema::GetStdNamespace() {
309 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000310 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000311 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000312 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000313 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
314 }
315 return StdNamespace;
316}
317
Chris Lattner4b009652007-07-25 00:24:17 +0000318/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
319/// and scope as a previous declaration 'Old'. Figure out how to resolve this
320/// situation, merging decls or emitting diagnostics as appropriate.
321///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000322TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000323 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000324 // Allow multiple definitions for ObjC built-in typedefs.
325 // FIXME: Verify the underlying types are equivalent!
326 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000327 const IdentifierInfo *TypeID = New->getIdentifier();
328 switch (TypeID->getLength()) {
329 default: break;
330 case 2:
331 if (!TypeID->isStr("id"))
332 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000333 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000334 objc_types = true;
335 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000336 case 5:
337 if (!TypeID->isStr("Class"))
338 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000339 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000340 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000341 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000342 case 3:
343 if (!TypeID->isStr("SEL"))
344 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000345 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000346 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000347 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000348 case 8:
349 if (!TypeID->isStr("Protocol"))
350 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000351 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000352 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000353 return New;
354 }
355 // Fall through - the typedef name was not a builtin type.
356 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000357 // Verify the old decl was also a type.
358 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000359 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000360 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000361 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000362 if (!objc_types)
363 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000364 return New;
365 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000366
367 // Determine the "old" type we'll use for checking and diagnostics.
368 QualType OldType;
369 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
370 OldType = OldTypedef->getUnderlyingType();
371 else
372 OldType = Context.getTypeDeclType(Old);
373
Chris Lattnerbef8d622008-07-25 18:44:27 +0000374 // If the typedef types are not identical, reject them in all languages and
375 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000376
377 if (OldType != New->getUnderlyingType() &&
378 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000379 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000380 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000381 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000382 if (!objc_types)
383 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000384 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000385 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000386 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000387 if (getLangOptions().Microsoft) return New;
388
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000389 // C++ [dcl.typedef]p2:
390 // In a given non-class scope, a typedef specifier can be used to
391 // redefine the name of any type declared in that scope to refer
392 // to the type to which it already refers.
393 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
394 return New;
395
396 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000397 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
398 // *either* declaration is in a system header. The code below implements
399 // this adhoc compatibility rule. FIXME: The following code will not
400 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000401 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
402 SourceManager &SrcMgr = Context.getSourceManager();
403 if (SrcMgr.isInSystemHeader(Old->getLocation()))
404 return New;
405 if (SrcMgr.isInSystemHeader(New->getLocation()))
406 return New;
407 }
Eli Friedman324d5032008-06-11 06:20:39 +0000408
Chris Lattnerb1753422008-11-23 21:45:46 +0000409 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000410 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000411 return New;
412}
413
Chris Lattner6953a072008-06-26 18:38:35 +0000414/// DeclhasAttr - returns true if decl Declaration already has the target
415/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000416static bool DeclHasAttr(const Decl *decl, const Attr *target) {
417 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
418 if (attr->getKind() == target->getKind())
419 return true;
420
421 return false;
422}
423
424/// MergeAttributes - append attributes from the Old decl to the New one.
425static void MergeAttributes(Decl *New, Decl *Old) {
426 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
427
Chris Lattner402b3372008-03-03 03:28:21 +0000428 while (attr) {
429 tmp = attr;
430 attr = attr->getNext();
431
432 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000433 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000434 New->addAttr(tmp);
435 } else {
436 tmp->setNext(0);
437 delete(tmp);
438 }
439 }
Nuno Lopes77654342008-06-01 22:53:53 +0000440
441 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000442}
443
Chris Lattner3e254fb2008-04-08 04:40:51 +0000444/// MergeFunctionDecl - We just parsed a function 'New' from
445/// declarator D which has the same name and scope as a previous
446/// declaration 'Old'. Figure out how to resolve this situation,
447/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000448/// Redeclaration will be set true if this New is a redeclaration OldD.
449///
450/// In C++, New and Old must be declarations that are not
451/// overloaded. Use IsOverload to determine whether New and Old are
452/// overloaded, and to select the Old declaration that New should be
453/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000454FunctionDecl *
455Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000456 assert(!isa<OverloadedFunctionDecl>(OldD) &&
457 "Cannot merge with an overloaded function declaration");
458
Douglas Gregor42214c52008-04-21 02:02:58 +0000459 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000460 // Verify the old decl was also a function.
461 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
462 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000463 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000464 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000465 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000466 return New;
467 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000468
469 // Determine whether the previous declaration was a definition,
470 // implicit declaration, or a declaration.
471 diag::kind PrevDiag;
472 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000473 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000474 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000475 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000476 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000477 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000478
Chris Lattner42a21742008-04-06 23:10:54 +0000479 QualType OldQType = Context.getCanonicalType(Old->getType());
480 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000481
Douglas Gregord2baafd2008-10-21 16:13:35 +0000482 if (getLangOptions().CPlusPlus) {
483 // (C++98 13.1p2):
484 // Certain function declarations cannot be overloaded:
485 // -- Function declarations that differ only in the return type
486 // cannot be overloaded.
487 QualType OldReturnType
488 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
489 QualType NewReturnType
490 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
491 if (OldReturnType != NewReturnType) {
492 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
493 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000494 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000495 return New;
496 }
497
498 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
499 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
500 if (OldMethod && NewMethod) {
501 // -- Member function declarations with the same name and the
502 // same parameter types cannot be overloaded if any of them
503 // is a static member function declaration.
504 if (OldMethod->isStatic() || NewMethod->isStatic()) {
505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
506 Diag(Old->getLocation(), PrevDiag);
507 return New;
508 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000509
510 // C++ [class.mem]p1:
511 // [...] A member shall not be declared twice in the
512 // member-specification, except that a nested class or member
513 // class template can be declared and then later defined.
514 if (OldMethod->getLexicalDeclContext() ==
515 NewMethod->getLexicalDeclContext()) {
516 unsigned NewDiag;
517 if (isa<CXXConstructorDecl>(OldMethod))
518 NewDiag = diag::err_constructor_redeclared;
519 else if (isa<CXXDestructorDecl>(NewMethod))
520 NewDiag = diag::err_destructor_redeclared;
521 else if (isa<CXXConversionDecl>(NewMethod))
522 NewDiag = diag::err_conv_function_redeclared;
523 else
524 NewDiag = diag::err_member_redeclared;
525
526 Diag(New->getLocation(), NewDiag);
527 Diag(Old->getLocation(), PrevDiag);
528 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000529 }
530
531 // (C++98 8.3.5p3):
532 // All declarations for a function shall agree exactly in both the
533 // return type and the parameter-type-list.
534 if (OldQType == NewQType) {
535 // We have a redeclaration.
536 MergeAttributes(New, Old);
537 Redeclaration = true;
538 return MergeCXXFunctionDecl(New, Old);
539 }
540
541 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000542 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000543
544 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000545 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000546 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000547 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000548 MergeAttributes(New, Old);
549 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000550 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000551 }
Chris Lattner1470b072007-11-06 06:07:26 +0000552
Steve Naroff6c9e7922008-01-16 15:01:34 +0000553 // A function that has already been declared has been redeclared or defined
554 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000555
Chris Lattner4b009652007-07-25 00:24:17 +0000556 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
557 // TODO: This is totally simplistic. It should handle merging functions
558 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000559 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000560 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000561 return New;
562}
563
Steve Naroffb5e78152008-08-08 17:50:35 +0000564/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000565static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000566 if (VD->isFileVarDecl())
567 return (!VD->getInit() &&
568 (VD->getStorageClass() == VarDecl::None ||
569 VD->getStorageClass() == VarDecl::Static));
570 return false;
571}
572
573/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
574/// when dealing with C "tentative" external object definitions (C99 6.9.2).
575void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
576 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000577 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000578
Douglas Gregor3a423132009-01-07 16:34:42 +0000579 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000580 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000581 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
582 E = IdResolver.end();
583 I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000584 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000585 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
586
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000587 // Handle the following case:
588 // int a[10];
589 // int a[]; - the code below makes sure we set the correct type.
590 // int a[11]; - this is an error, size isn't 10.
591 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
592 OldDecl->getType()->isConstantArrayType())
593 VD->setType(OldDecl->getType());
594
Steve Naroffb5e78152008-08-08 17:50:35 +0000595 // Check for "tentative" definitions. We can't accomplish this in
596 // MergeVarDecl since the initializer hasn't been attached.
597 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
598 continue;
599
600 // Handle __private_extern__ just like extern.
601 if (OldDecl->getStorageClass() != VarDecl::Extern &&
602 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
603 VD->getStorageClass() != VarDecl::Extern &&
604 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000605 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000606 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000607 }
608 }
609 }
610}
611
Chris Lattner4b009652007-07-25 00:24:17 +0000612/// MergeVarDecl - We just parsed a variable 'New' which has the same name
613/// and scope as a previous declaration 'Old'. Figure out how to resolve this
614/// situation, merging decls or emitting diagnostics as appropriate.
615///
Steve Naroffb5e78152008-08-08 17:50:35 +0000616/// Tentative definition rules (C99 6.9.2p2) are checked by
617/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
618/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000619///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000620VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 // Verify the old decl was also a variable.
622 VarDecl *Old = dyn_cast<VarDecl>(OldD);
623 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000624 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000625 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000626 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 return New;
628 }
Chris Lattner402b3372008-03-03 03:28:21 +0000629
630 MergeAttributes(New, Old);
631
Eli Friedman4a480d62009-01-24 23:49:55 +0000632 // Merge the types
633 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
634 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000635 Diag(New->getLocation(), diag::err_redefinition_different_type)
636 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000637 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000638 return New;
639 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000640 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000641 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
642 if (New->getStorageClass() == VarDecl::Static &&
643 (Old->getStorageClass() == VarDecl::None ||
644 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000645 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000646 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000647 return New;
648 }
649 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
650 if (New->getStorageClass() != VarDecl::Static &&
651 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000652 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000653 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000654 return New;
655 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000656 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
657 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000658 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000659 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000660 }
661 return New;
662}
663
Chris Lattner3e254fb2008-04-08 04:40:51 +0000664/// CheckParmsForFunctionDef - Check that the parameters of the given
665/// function are appropriate for the definition of a function. This
666/// takes care of any checks that cannot be performed on the
667/// declaration itself, e.g., that the types of each of the function
668/// parameters are complete.
669bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
670 bool HasInvalidParm = false;
671 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
672 ParmVarDecl *Param = FD->getParamDecl(p);
673
674 // C99 6.7.5.3p4: the parameters in a parameter type list in a
675 // function declarator that is part of a function definition of
676 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000677 if (!Param->isInvalidDecl() &&
678 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
679 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000680 Param->setInvalidDecl();
681 HasInvalidParm = true;
682 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000683
684 // C99 6.9.1p5: If the declarator includes a parameter type list, the
685 // declaration of each parameter shall include an identifier.
686 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
687 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000688 }
689
690 return HasInvalidParm;
691}
692
Chris Lattner4b009652007-07-25 00:24:17 +0000693/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
694/// no declarator (e.g. "struct foo;") is parsed.
695Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000696 TagDecl *Tag
697 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
698 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
699 if (!Record->getDeclName() && Record->isDefinition() &&
700 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
701 return BuildAnonymousStructOrUnion(S, DS, Record);
702
703 // Microsoft allows unnamed struct/union fields. Don't complain
704 // about them.
705 // FIXME: Should we support Microsoft's extensions in this area?
706 if (Record->getDeclName() && getLangOptions().Microsoft)
707 return Tag;
708 }
709
Sebastian Redlb7605e82008-12-28 15:28:59 +0000710 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000711 // Warn about typedefs of enums without names, since this is an
712 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000713 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
714 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000715 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000716 << DS.getSourceRange();
717 return Tag;
718 }
719
Sebastian Redlb7605e82008-12-28 15:28:59 +0000720 // FIXME: This diagnostic is emitted even when various previous
721 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
722 // DeclSpec has no means of communicating this information, and the
723 // responsible parser functions are quite far apart.
724 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
725 << DS.getSourceRange();
726 return 0;
727 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000728
Douglas Gregor723d3332009-01-07 00:43:41 +0000729 return Tag;
730}
731
732/// InjectAnonymousStructOrUnionMembers - Inject the members of the
733/// anonymous struct or union AnonRecord into the owning context Owner
734/// and scope S. This routine will be invoked just after we realize
735/// that an unnamed union or struct is actually an anonymous union or
736/// struct, e.g.,
737///
738/// @code
739/// union {
740/// int i;
741/// float f;
742/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
743/// // f into the surrounding scope.x
744/// @endcode
745///
746/// This routine is recursive, injecting the names of nested anonymous
747/// structs/unions into the owning context and scope as well.
748bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
749 RecordDecl *AnonRecord) {
750 bool Invalid = false;
751 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
752 FEnd = AnonRecord->field_end();
753 F != FEnd; ++F) {
754 if ((*F)->getDeclName()) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000755 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
756 LookupOrdinaryName, true);
Douglas Gregor723d3332009-01-07 00:43:41 +0000757 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
758 // C++ [class.union]p2:
759 // The names of the members of an anonymous union shall be
760 // distinct from the names of any other entity in the
761 // scope in which the anonymous union is declared.
762 unsigned diagKind
763 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
764 : diag::err_anonymous_struct_member_redecl;
765 Diag((*F)->getLocation(), diagKind)
766 << (*F)->getDeclName();
767 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
768 Invalid = true;
769 } else {
770 // C++ [class.union]p2:
771 // For the purpose of name lookup, after the anonymous union
772 // definition, the members of the anonymous union are
773 // considered to have been defined in the scope in which the
774 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000775 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000776 S->AddDecl(*F);
777 IdResolver.AddDecl(*F);
778 }
779 } else if (const RecordType *InnerRecordType
780 = (*F)->getType()->getAsRecordType()) {
781 RecordDecl *InnerRecord = InnerRecordType->getDecl();
782 if (InnerRecord->isAnonymousStructOrUnion())
783 Invalid = Invalid ||
784 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
785 }
786 }
787
788 return Invalid;
789}
790
791/// ActOnAnonymousStructOrUnion - Handle the declaration of an
792/// anonymous structure or union. Anonymous unions are a C++ feature
793/// (C++ [class.union]) and a GNU C extension; anonymous structures
794/// are a GNU C and GNU C++ extension.
795Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
796 RecordDecl *Record) {
797 DeclContext *Owner = Record->getDeclContext();
798
799 // Diagnose whether this anonymous struct/union is an extension.
800 if (Record->isUnion() && !getLangOptions().CPlusPlus)
801 Diag(Record->getLocation(), diag::ext_anonymous_union);
802 else if (!Record->isUnion())
803 Diag(Record->getLocation(), diag::ext_anonymous_struct);
804
805 // C and C++ require different kinds of checks for anonymous
806 // structs/unions.
807 bool Invalid = false;
808 if (getLangOptions().CPlusPlus) {
809 const char* PrevSpec = 0;
810 // C++ [class.union]p3:
811 // Anonymous unions declared in a named namespace or in the
812 // global namespace shall be declared static.
813 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
814 (isa<TranslationUnitDecl>(Owner) ||
815 (isa<NamespaceDecl>(Owner) &&
816 cast<NamespaceDecl>(Owner)->getDeclName()))) {
817 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
818 Invalid = true;
819
820 // Recover by adding 'static'.
821 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
822 }
823 // C++ [class.union]p3:
824 // A storage class is not allowed in a declaration of an
825 // anonymous union in a class scope.
826 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
827 isa<RecordDecl>(Owner)) {
828 Diag(DS.getStorageClassSpecLoc(),
829 diag::err_anonymous_union_with_storage_spec);
830 Invalid = true;
831
832 // Recover by removing the storage specifier.
833 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
834 PrevSpec);
835 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000836
837 // C++ [class.union]p2:
838 // The member-specification of an anonymous union shall only
839 // define non-static data members. [Note: nested types and
840 // functions cannot be declared within an anonymous union. ]
841 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
842 MemEnd = Record->decls_end();
843 Mem != MemEnd; ++Mem) {
844 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
845 // C++ [class.union]p3:
846 // An anonymous union shall not have private or protected
847 // members (clause 11).
848 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
849 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
850 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
851 Invalid = true;
852 }
853 } else if ((*Mem)->isImplicit()) {
854 // Any implicit members are fine.
Douglas Gregor2d87eb02009-02-03 00:34:39 +0000855 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
856 // This is a type that showed up in an
857 // elaborated-type-specifier inside the anonymous struct or
858 // union, but which actually declares a type outside of the
859 // anonymous struct or union. It's okay.
Douglas Gregorc7f01612009-01-07 19:46:03 +0000860 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
861 if (!MemRecord->isAnonymousStructOrUnion() &&
862 MemRecord->getDeclName()) {
863 // This is a nested type declaration.
864 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
865 << (int)Record->isUnion();
866 Invalid = true;
867 }
868 } else {
869 // We have something that isn't a non-static data
870 // member. Complain about it.
871 unsigned DK = diag::err_anonymous_record_bad_member;
872 if (isa<TypeDecl>(*Mem))
873 DK = diag::err_anonymous_record_with_type;
874 else if (isa<FunctionDecl>(*Mem))
875 DK = diag::err_anonymous_record_with_function;
876 else if (isa<VarDecl>(*Mem))
877 DK = diag::err_anonymous_record_with_static;
878 Diag((*Mem)->getLocation(), DK)
879 << (int)Record->isUnion();
880 Invalid = true;
881 }
882 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000883 } else {
884 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000885 if (Record->isUnion() && !Owner->isRecord()) {
886 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
887 << (int)getLangOptions().CPlusPlus;
888 Invalid = true;
889 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000890 }
891
892 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000893 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
894 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000895 Invalid = true;
896 }
897
898 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000899 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +0000900 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
901 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
902 /*IdentifierInfo=*/0,
903 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000904 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000905 Anon->setAccess(AS_public);
906 if (getLangOptions().CPlusPlus)
907 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000908 } else {
909 VarDecl::StorageClass SC;
910 switch (DS.getStorageClassSpec()) {
911 default: assert(0 && "Unknown storage class!");
912 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
913 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
914 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
915 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
916 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
917 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
918 case DeclSpec::SCS_mutable:
919 // mutable can only appear on non-static class members, so it's always
920 // an error here
921 Diag(Record->getLocation(), diag::err_mutable_nonmember);
922 Invalid = true;
923 SC = VarDecl::None;
924 break;
925 }
926
927 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
928 /*IdentifierInfo=*/0,
929 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000930 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +0000931 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000932 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000933
934 // Add the anonymous struct/union object to the current
935 // context. We'll be referencing this object when we refer to one of
936 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000937 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000938
939 // Inject the members of the anonymous struct/union into the owning
940 // context and into the identifier resolver chain for name lookup
941 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000942 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
943 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000944
945 // Mark this as an anonymous struct/union type. Note that we do not
946 // do this until after we have already checked and injected the
947 // members of this anonymous struct/union type, because otherwise
948 // the members could be injected twice: once by DeclContext when it
949 // builds its lookup table, and once by
950 // InjectAnonymousStructOrUnionMembers.
951 Record->setAnonymousStructOrUnion(true);
952
953 if (Invalid)
954 Anon->setInvalidDecl();
955
956 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000957}
958
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000959bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
960 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000961 // Get the type before calling CheckSingleAssignmentConstraints(), since
962 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000963 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000964
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000965 if (getLangOptions().CPlusPlus) {
966 // FIXME: I dislike this error message. A lot.
967 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
968 return Diag(Init->getSourceRange().getBegin(),
969 diag::err_typecheck_convert_incompatible)
970 << DeclType << Init->getType() << "initializing"
971 << Init->getSourceRange();
972
973 return false;
974 }
Douglas Gregor6fd35572008-12-19 17:40:08 +0000975
Chris Lattner005ed752008-01-04 18:04:52 +0000976 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
977 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
978 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000979}
980
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000981bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000982 const ArrayType *AT = Context.getAsArrayType(DeclT);
983
984 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000985 // C99 6.7.8p14. We have an array of character type with unknown size
986 // being initialized to a string literal.
987 llvm::APSInt ConstVal(32);
988 ConstVal = strLiteral->getByteLength() + 1;
989 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000990 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000991 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000992 } else {
993 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000994 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000995 // FIXME: Avoid truncation for 64-bit length strings.
996 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000997 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000998 diag::warn_initializer_string_for_char_array_too_long)
999 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001000 }
1001 // Set type from "char *" to "constant array of char".
1002 strLiteral->setType(DeclT);
1003 // For now, we always return false (meaning success).
1004 return false;
1005}
1006
1007StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001008 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001009 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +00001010 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +00001011 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001012 return 0;
1013}
1014
Douglas Gregor6428e762008-11-05 15:29:30 +00001015bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1016 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001017 DeclarationName InitEntity,
1018 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001019 if (DeclType->isDependentType() || Init->isTypeDependent())
1020 return false;
1021
Douglas Gregor81c29152008-10-29 00:13:59 +00001022 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001023 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001024 // (8.3.2), shall be initialized by an object, or function, of
1025 // type T or by an object that can be converted into a T.
1026 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001027 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001028
Steve Naroff8e9337f2008-01-21 23:53:58 +00001029 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1030 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001031 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001032 return Diag(InitLoc, diag::err_variable_object_no_init)
1033 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001034
Steve Naroffcb69fb72007-12-10 22:44:33 +00001035 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1036 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001037 // FIXME: Handle wide strings
1038 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1039 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001040
Douglas Gregor6428e762008-11-05 15:29:30 +00001041 // C++ [dcl.init]p14:
1042 // -- If the destination type is a (possibly cv-qualified) class
1043 // type:
1044 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1045 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1046 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1047
1048 // -- If the initialization is direct-initialization, or if it is
1049 // copy-initialization where the cv-unqualified version of the
1050 // source type is the same class as, or a derived class of, the
1051 // class of the destination, constructors are considered.
1052 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1053 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1054 CXXConstructorDecl *Constructor
1055 = PerformInitializationByConstructor(DeclType, &Init, 1,
1056 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001057 InitEntity,
1058 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001059 return Constructor == 0;
1060 }
1061
1062 // -- Otherwise (i.e., for the remaining copy-initialization
1063 // cases), user-defined conversion sequences that can
1064 // convert from the source type to the destination type or
1065 // (when a conversion function is used) to a derived class
1066 // thereof are enumerated as described in 13.3.1.4, and the
1067 // best one is chosen through overload resolution
1068 // (13.3). If the conversion cannot be done or is
1069 // ambiguous, the initialization is ill-formed. The
1070 // function selected is called with the initializer
1071 // expression as its argument; if the function is a
1072 // constructor, the call initializes a temporary of the
1073 // destination type.
1074 // FIXME: We're pretending to do copy elision here; return to
1075 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001076 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001077 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001078
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001079 if (InitEntity)
1080 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1081 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1082 << Init->getType() << Init->getSourceRange();
1083 else
1084 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1085 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1086 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001087 }
1088
Steve Naroffb2f72412008-09-29 20:07:05 +00001089 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001090 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001091 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1092 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001093
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001094 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregord45210d2009-01-30 22:09:00 +00001095 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001096
Douglas Gregor849afc32009-01-29 00:45:39 +00001097 bool hadError = CheckInitList(InitList, DeclType);
1098 Init = InitList;
1099 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +00001100}
1101
Douglas Gregor6704b312008-11-17 22:58:34 +00001102/// GetNameForDeclarator - Determine the full declaration name for the
1103/// given Declarator.
1104DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1105 switch (D.getKind()) {
1106 case Declarator::DK_Abstract:
1107 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1108 return DeclarationName();
1109
1110 case Declarator::DK_Normal:
1111 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1112 return DeclarationName(D.getIdentifier());
1113
1114 case Declarator::DK_Constructor: {
1115 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1116 Ty = Context.getCanonicalType(Ty);
1117 return Context.DeclarationNames.getCXXConstructorName(Ty);
1118 }
1119
1120 case Declarator::DK_Destructor: {
1121 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1122 Ty = Context.getCanonicalType(Ty);
1123 return Context.DeclarationNames.getCXXDestructorName(Ty);
1124 }
1125
1126 case Declarator::DK_Conversion: {
1127 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1128 Ty = Context.getCanonicalType(Ty);
1129 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1130 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001131
1132 case Declarator::DK_Operator:
1133 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1134 return Context.DeclarationNames.getCXXOperatorName(
1135 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001136 }
1137
1138 assert(false && "Unknown name kind");
1139 return DeclarationName();
1140}
1141
Douglas Gregor46cfe452009-02-06 17:46:57 +00001142/// isNearlyMatchingFunction - Determine whether the C++ functions
1143/// Declaration and Definition are "nearly" matching. This heuristic
1144/// is used to improve diagnostics in the case where an out-of-line
1145/// function definition doesn't match any declaration within
1146/// the class or namespace.
1147static bool isNearlyMatchingFunction(ASTContext &Context,
1148 FunctionDecl *Declaration,
1149 FunctionDecl *Definition) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001150 if (Declaration->param_size() != Definition->param_size())
1151 return false;
1152 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1153 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1154 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1155
1156 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1157 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1158 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1159 return false;
1160 }
1161
1162 return true;
1163}
1164
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001165Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001166Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1167 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001168 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001169 DeclarationName Name = GetNameForDeclarator(D);
1170
Chris Lattner4b009652007-07-25 00:24:17 +00001171 // All of these full declarators require an identifier. If it doesn't have
1172 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001173 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001174 if (!D.getInvalidType()) // Reject this if we think it is valid.
1175 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001176 diag::err_declarator_need_ident)
1177 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001178 return 0;
1179 }
1180
Chris Lattnera7549902007-08-26 06:24:45 +00001181 // The scope passed in may not be a decl scope. Zip up the scope tree until
1182 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001183 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregor279272e2009-02-04 19:02:06 +00001184 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001185 S = S->getParent();
1186
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001187 DeclContext *DC;
Douglas Gregor09be81b2009-02-04 17:27:36 +00001188 NamedDecl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001189 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001190 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001191
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001192 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001193 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001194 DC = CurContext;
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001195 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001196 } else { // Something like "int foo::x;"
1197 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001198 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001199
1200 // C++ 7.3.1.2p2:
1201 // Members (including explicit specializations of templates) of a named
1202 // namespace can also be defined outside that namespace by explicit
1203 // qualification of the name being defined, provided that the entity being
1204 // defined was already declared in the namespace and the definition appears
1205 // after the point of declaration in a namespace that encloses the
1206 // declarations namespace.
1207 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001208 // Note that we only check the context at this point. We don't yet
1209 // have enough information to make sure that PrevDecl is actually
1210 // the declaration we want to match. For example, given:
1211 //
Douglas Gregor98341042008-12-12 08:25:50 +00001212 // class X {
1213 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001214 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001215 // };
1216 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001217 // void X::f(int) { } // ill-formed
1218 //
1219 // In this case, PrevDecl will point to the overload set
1220 // containing the two f's declared in X, but neither of them
1221 // matches.
Douglas Gregor46cfe452009-02-06 17:46:57 +00001222
1223 // First check whether we named the global scope.
1224 if (isa<TranslationUnitDecl>(DC)) {
1225 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1226 << Name << D.getCXXScopeSpec().getRange();
1227 } else if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001228 // The qualifying scope doesn't enclose the original declaration.
1229 // Emit diagnostic based on current scope.
1230 SourceLocation L = D.getIdentifierLoc();
1231 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor46cfe452009-02-06 17:46:57 +00001232 if (isa<FunctionDecl>(CurContext))
Chris Lattner254de7d2008-11-23 20:28:15 +00001233 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor46cfe452009-02-06 17:46:57 +00001234 else
Chris Lattner254de7d2008-11-23 20:28:15 +00001235 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor46cfe452009-02-06 17:46:57 +00001236 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001237 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001238 }
1239 }
1240
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001241 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001242 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001243 InvalidDecl = InvalidDecl
1244 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001245 // Just pretend that we didn't see the previous declaration.
1246 PrevDecl = 0;
1247 }
1248
Douglas Gregor1d661552008-04-13 21:07:44 +00001249 // In C++, the previous declaration we find might be a tag type
1250 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001251 // tag type. Note that this does does not apply if we're declaring a
1252 // typedef (C++ [dcl.typedef]p4).
1253 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1254 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001255 PrevDecl = 0;
1256
Chris Lattner82bb4792007-11-14 06:34:38 +00001257 QualType R = GetTypeForDeclarator(D, S);
1258 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001261 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1262 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001263 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001264 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1265 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001266 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001267 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1268 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001269 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001270
1271 if (New == 0)
1272 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001273
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001274 // Set the lexical context. If the declarator has a C++ scope specifier, the
1275 // lexical context will be different from the semantic context.
1276 New->setLexicalDeclContext(CurContext);
1277
Chris Lattner4b009652007-07-25 00:24:17 +00001278 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001279 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001280 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001281 // If any semantic error occurred, mark the decl as invalid.
1282 if (D.getInvalidType() || InvalidDecl)
1283 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001284
1285 return New;
1286}
1287
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001288NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001289Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001290 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001291 Decl* PrevDecl, bool& InvalidDecl) {
1292 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1293 if (D.getCXXScopeSpec().isSet()) {
1294 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1295 << D.getCXXScopeSpec().getRange();
1296 InvalidDecl = true;
1297 // Pretend we didn't see the scope specifier.
1298 DC = 0;
1299 }
1300
1301 // Check that there are no default arguments (C++ only).
1302 if (getLangOptions().CPlusPlus)
1303 CheckExtraCXXDefaultArguments(D);
1304
1305 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1306 if (!NewTD) return 0;
1307
1308 // Handle attributes prior to checking for duplicates in MergeVarDecl
1309 ProcessDeclAttributes(NewTD, D);
1310 // Merge the decl with the existing one if appropriate. If the decl is
1311 // in an outer scope, it isn't the same thing.
1312 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1313 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1314 if (NewTD == 0) return 0;
1315 }
1316
1317 if (S->getFnParent() == 0) {
1318 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1319 // then it shall have block scope.
1320 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1321 if (NewTD->getUnderlyingType()->isVariableArrayType())
1322 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1323 else
1324 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1325
1326 InvalidDecl = true;
1327 }
1328 }
1329 return NewTD;
1330}
1331
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001332NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001333Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001334 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001335 Decl* PrevDecl, bool& InvalidDecl) {
1336 DeclarationName Name = GetNameForDeclarator(D);
1337
1338 // Check that there are no default arguments (C++ only).
1339 if (getLangOptions().CPlusPlus)
1340 CheckExtraCXXDefaultArguments(D);
1341
1342 if (R.getTypePtr()->isObjCInterfaceType()) {
1343 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1344 << D.getIdentifier();
1345 InvalidDecl = true;
1346 }
1347
1348 VarDecl *NewVD;
1349 VarDecl::StorageClass SC;
1350 switch (D.getDeclSpec().getStorageClassSpec()) {
1351 default: assert(0 && "Unknown storage class!");
1352 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1353 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1354 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1355 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1356 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1357 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1358 case DeclSpec::SCS_mutable:
1359 // mutable can only appear on non-static class members, so it's always
1360 // an error here
1361 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1362 InvalidDecl = true;
1363 SC = VarDecl::None;
1364 break;
1365 }
1366
1367 IdentifierInfo *II = Name.getAsIdentifierInfo();
1368 if (!II) {
1369 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1370 << Name.getAsString();
1371 return 0;
1372 }
1373
1374 if (DC->isRecord()) {
1375 // This is a static data member for a C++ class.
1376 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1377 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001378 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001379 } else {
1380 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1381 if (S->getFnParent() == 0) {
1382 // C99 6.9p2: The storage-class specifiers auto and register shall not
1383 // appear in the declaration specifiers in an external declaration.
1384 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1385 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1386 InvalidDecl = true;
1387 }
1388 }
1389 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001390 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001391 // FIXME: Move to DeclGroup...
1392 D.getDeclSpec().getSourceRange().getBegin());
1393 NewVD->setThreadSpecified(ThreadSpecified);
1394 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001395 NewVD->setNextDeclarator(LastDeclarator);
1396
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001397 // Handle attributes prior to checking for duplicates in MergeVarDecl
1398 ProcessDeclAttributes(NewVD, D);
1399
1400 // Handle GNU asm-label extension (encoded as an attribute).
1401 if (Expr *E = (Expr*) D.getAsmLabel()) {
1402 // The parser guarantees this is a string.
1403 StringLiteral *SE = cast<StringLiteral>(E);
1404 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1405 SE->getByteLength())));
1406 }
1407
1408 // Emit an error if an address space was applied to decl with local storage.
1409 // This includes arrays of objects with address space qualifiers, but not
1410 // automatic variables that point to other address spaces.
1411 // ISO/IEC TR 18037 S5.1.2
1412 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1413 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1414 InvalidDecl = true;
1415 }
1416 // Merge the decl with the existing one if appropriate. If the decl is
1417 // in an outer scope, it isn't the same thing.
1418 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1419 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1420 // The user tried to define a non-static data member
1421 // out-of-line (C++ [dcl.meaning]p1).
1422 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1423 << D.getCXXScopeSpec().getRange();
1424 NewVD->Destroy(Context);
1425 return 0;
1426 }
1427
1428 NewVD = MergeVarDecl(NewVD, PrevDecl);
1429 if (NewVD == 0) return 0;
1430
1431 if (D.getCXXScopeSpec().isSet()) {
1432 // No previous declaration in the qualifying scope.
1433 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1434 << Name << D.getCXXScopeSpec().getRange();
1435 InvalidDecl = true;
1436 }
1437 }
1438 return NewVD;
1439}
1440
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001441NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001442Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001443 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001444 Decl* PrevDecl, bool IsFunctionDefinition,
1445 bool& InvalidDecl) {
1446 assert(R.getTypePtr()->isFunctionType());
1447
1448 DeclarationName Name = GetNameForDeclarator(D);
1449 FunctionDecl::StorageClass SC = FunctionDecl::None;
1450 switch (D.getDeclSpec().getStorageClassSpec()) {
1451 default: assert(0 && "Unknown storage class!");
1452 case DeclSpec::SCS_auto:
1453 case DeclSpec::SCS_register:
1454 case DeclSpec::SCS_mutable:
1455 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1456 InvalidDecl = true;
1457 break;
1458 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1459 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1460 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1461 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1462 }
1463
1464 bool isInline = D.getDeclSpec().isInlineSpecified();
1465 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1466 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1467
1468 FunctionDecl *NewFD;
1469 if (D.getKind() == Declarator::DK_Constructor) {
1470 // This is a C++ constructor declaration.
1471 assert(DC->isRecord() &&
1472 "Constructors can only be declared in a member context");
1473
1474 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1475
1476 // Create the new declaration
1477 NewFD = CXXConstructorDecl::Create(Context,
1478 cast<CXXRecordDecl>(DC),
1479 D.getIdentifierLoc(), Name, R,
1480 isExplicit, isInline,
1481 /*isImplicitlyDeclared=*/false);
1482
1483 if (InvalidDecl)
1484 NewFD->setInvalidDecl();
1485 } else if (D.getKind() == Declarator::DK_Destructor) {
1486 // This is a C++ destructor declaration.
1487 if (DC->isRecord()) {
1488 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1489
1490 NewFD = CXXDestructorDecl::Create(Context,
1491 cast<CXXRecordDecl>(DC),
1492 D.getIdentifierLoc(), Name, R,
1493 isInline,
1494 /*isImplicitlyDeclared=*/false);
1495
1496 if (InvalidDecl)
1497 NewFD->setInvalidDecl();
1498 } else {
1499 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1500
1501 // Create a FunctionDecl to satisfy the function definition parsing
1502 // code path.
1503 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001504 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001505 // FIXME: Move to DeclGroup...
1506 D.getDeclSpec().getSourceRange().getBegin());
1507 InvalidDecl = true;
1508 NewFD->setInvalidDecl();
1509 }
1510 } else if (D.getKind() == Declarator::DK_Conversion) {
1511 if (!DC->isRecord()) {
1512 Diag(D.getIdentifierLoc(),
1513 diag::err_conv_function_not_member);
1514 return 0;
1515 } else {
1516 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1517
1518 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1519 D.getIdentifierLoc(), Name, R,
1520 isInline, isExplicit);
1521
1522 if (InvalidDecl)
1523 NewFD->setInvalidDecl();
1524 }
1525 } else if (DC->isRecord()) {
1526 // This is a C++ method declaration.
1527 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1528 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001529 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001530 } else {
1531 NewFD = FunctionDecl::Create(Context, DC,
1532 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001533 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001534 // FIXME: Move to DeclGroup...
1535 D.getDeclSpec().getSourceRange().getBegin());
1536 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001537 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001538
1539 // Set the lexical context. If the declarator has a C++
1540 // scope specifier, the lexical context will be different
1541 // from the semantic context.
1542 NewFD->setLexicalDeclContext(CurContext);
1543
1544 // Handle GNU asm-label extension (encoded as an attribute).
1545 if (Expr *E = (Expr*) D.getAsmLabel()) {
1546 // The parser guarantees this is a string.
1547 StringLiteral *SE = cast<StringLiteral>(E);
1548 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1549 SE->getByteLength())));
1550 }
1551
1552 // Copy the parameter declarations from the declarator D to
1553 // the function declaration NewFD, if they are available.
1554 if (D.getNumTypeObjects() > 0) {
1555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1556
1557 // Create Decl objects for each parameter, adding them to the
1558 // FunctionDecl.
1559 llvm::SmallVector<ParmVarDecl*, 16> Params;
1560
1561 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1562 // function that takes no arguments, not a function that takes a
1563 // single void argument.
1564 // We let through "const void" here because Sema::GetTypeForDeclarator
1565 // already checks for that case.
1566 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1567 FTI.ArgInfo[0].Param &&
1568 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1569 // empty arg list, don't push any params.
1570 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1571
1572 // In C++, the empty parameter-type-list must be spelled "void"; a
1573 // typedef of void is not permitted.
1574 if (getLangOptions().CPlusPlus &&
1575 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1576 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1577 }
1578 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1579 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1580 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1581 }
1582
1583 NewFD->setParams(Context, &Params[0], Params.size());
1584 } else if (R->getAsTypedefType()) {
1585 // When we're declaring a function with a typedef, as in the
1586 // following example, we'll need to synthesize (unnamed)
1587 // parameters for use in the declaration.
1588 //
1589 // @code
1590 // typedef void fn(int);
1591 // fn f;
1592 // @endcode
1593 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1594 if (!FT) {
1595 // This is a typedef of a function with no prototype, so we
1596 // don't need to do anything.
1597 } else if ((FT->getNumArgs() == 0) ||
1598 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1599 FT->getArgType(0)->isVoidType())) {
1600 // This is a zero-argument function. We don't need to do anything.
1601 } else {
1602 // Synthesize a parameter for each argument type.
1603 llvm::SmallVector<ParmVarDecl*, 16> Params;
1604 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1605 ArgType != FT->arg_type_end(); ++ArgType) {
1606 Params.push_back(ParmVarDecl::Create(Context, DC,
1607 SourceLocation(), 0,
1608 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001609 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001610 }
1611
1612 NewFD->setParams(Context, &Params[0], Params.size());
1613 }
1614 }
1615
1616 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1617 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1618 else if (isa<CXXDestructorDecl>(NewFD)) {
1619 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1620 Record->setUserDeclaredDestructor(true);
1621 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1622 // user-defined destructor.
1623 Record->setPOD(false);
1624 } else if (CXXConversionDecl *Conversion =
1625 dyn_cast<CXXConversionDecl>(NewFD))
1626 ActOnConversionDeclarator(Conversion);
1627
1628 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1629 if (NewFD->isOverloadedOperator() &&
1630 CheckOverloadedOperatorDeclaration(NewFD))
1631 NewFD->setInvalidDecl();
1632
1633 // Merge the decl with the existing one if appropriate. Since C functions
1634 // are in a flat namespace, make sure we consider decls in outer scopes.
Douglas Gregor46cfe452009-02-06 17:46:57 +00001635 bool Redeclaration = false;
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001636 if (PrevDecl &&
1637 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001638 // If C++, determine whether NewFD is an overload of PrevDecl or
1639 // a declaration that requires merging. If it's an overload,
1640 // there's no more work to do here; we'll just add the new
1641 // function to the scope.
1642 OverloadedFunctionDecl::function_iterator MatchedDecl;
1643 if (!getLangOptions().CPlusPlus ||
1644 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1645 Decl *OldDecl = PrevDecl;
1646
1647 // If PrevDecl was an overloaded function, extract the
1648 // FunctionDecl that matched.
1649 if (isa<OverloadedFunctionDecl>(PrevDecl))
1650 OldDecl = *MatchedDecl;
1651
1652 // NewFD and PrevDecl represent declarations that need to be
1653 // merged.
1654 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1655
1656 if (NewFD == 0) return 0;
1657 if (Redeclaration) {
1658 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1659
1660 // An out-of-line member function declaration must also be a
1661 // definition (C++ [dcl.meaning]p1).
1662 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1663 !InvalidDecl) {
1664 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1665 << D.getCXXScopeSpec().getRange();
1666 NewFD->setInvalidDecl();
1667 }
1668 }
1669 }
Douglas Gregor46cfe452009-02-06 17:46:57 +00001670 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001671
Douglas Gregor46cfe452009-02-06 17:46:57 +00001672 if (D.getCXXScopeSpec().isSet() &&
1673 (!PrevDecl || !Redeclaration)) {
1674 // The user tried to provide an out-of-line definition for a
1675 // function that is a member of a class or namespace, but there
1676 // was no such member function declared (C++ [class.mfct]p2,
1677 // C++ [namespace.memdef]p2). For example:
1678 //
1679 // class X {
1680 // void f() const;
1681 // };
1682 //
1683 // void X::f() { } // ill-formed
1684 //
1685 // Complain about this problem, and attempt to suggest close
1686 // matches (e.g., those that differ only in cv-qualifiers and
1687 // whether the parameter types are references).
1688 DeclarationName CtxName;
1689 if (DC->isRecord())
1690 CtxName = cast<RecordDecl>(DC)->getDeclName();
1691 else if (DC->isNamespace())
1692 CtxName = cast<NamespaceDecl>(DC)->getDeclName();
1693 // FIXME: global scope
1694 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1695 << CtxName << D.getCXXScopeSpec().getRange();
1696 InvalidDecl = true;
1697
1698 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1699 true);
1700 assert(!Prev.isAmbiguous() &&
1701 "Cannot have an ambiguity in previous-declaration lookup");
1702 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1703 Func != FuncEnd; ++Func) {
1704 if (isa<FunctionDecl>(*Func) &&
1705 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
1706 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001707 }
Douglas Gregor46cfe452009-02-06 17:46:57 +00001708
1709 PrevDecl = 0;
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001710 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001711
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001712 // Handle attributes. We need to have merged decls when handling attributes
1713 // (for example to check for conflicts, etc).
1714 ProcessDeclAttributes(NewFD, D);
1715
1716 if (getLangOptions().CPlusPlus) {
1717 // In C++, check default arguments now that we have merged decls.
1718 CheckCXXDefaultArguments(NewFD);
1719
1720 // An out-of-line member function declaration must also be a
1721 // definition (C++ [dcl.meaning]p1).
1722 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1723 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1724 << D.getCXXScopeSpec().getRange();
1725 InvalidDecl = true;
1726 }
1727 }
1728 return NewFD;
1729}
1730
Steve Narofffc08f5e2008-10-27 11:34:16 +00001731void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001732 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1733 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001734}
1735
Eli Friedman02c22ce2008-05-20 13:48:25 +00001736bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1737 switch (Init->getStmtClass()) {
1738 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001739 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001740 return true;
1741 case Expr::ParenExprClass: {
1742 const ParenExpr* PE = cast<ParenExpr>(Init);
1743 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1744 }
1745 case Expr::CompoundLiteralExprClass:
1746 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001747 case Expr::DeclRefExprClass:
1748 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001749 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001750 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1751 if (VD->hasGlobalStorage())
1752 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001753 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001754 return true;
1755 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001756 if (isa<FunctionDecl>(D))
1757 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001758 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001759 return true;
1760 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001761 case Expr::MemberExprClass: {
1762 const MemberExpr *M = cast<MemberExpr>(Init);
1763 if (M->isArrow())
1764 return CheckAddressConstantExpression(M->getBase());
1765 return CheckAddressConstantExpressionLValue(M->getBase());
1766 }
1767 case Expr::ArraySubscriptExprClass: {
1768 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1769 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1770 return CheckAddressConstantExpression(ASE->getBase()) ||
1771 CheckArithmeticConstantExpression(ASE->getIdx());
1772 }
1773 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001774 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001775 return false;
1776 case Expr::UnaryOperatorClass: {
1777 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1778
1779 // C99 6.6p9
1780 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001781 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001782
Steve Narofffc08f5e2008-10-27 11:34:16 +00001783 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001784 return true;
1785 }
1786 }
1787}
1788
1789bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1790 switch (Init->getStmtClass()) {
1791 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001792 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001793 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001794 case Expr::ParenExprClass:
1795 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001796 case Expr::StringLiteralClass:
1797 case Expr::ObjCStringLiteralClass:
1798 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001799 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001800 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001801 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1802 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1803 Builtin::BI__builtin___CFStringMakeConstantString)
1804 return false;
1805
Steve Narofffc08f5e2008-10-27 11:34:16 +00001806 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001807 return true;
1808
Eli Friedman02c22ce2008-05-20 13:48:25 +00001809 case Expr::UnaryOperatorClass: {
1810 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1811
1812 // C99 6.6p9
1813 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1814 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1815
1816 if (Exp->getOpcode() == UnaryOperator::Extension)
1817 return CheckAddressConstantExpression(Exp->getSubExpr());
1818
Steve Narofffc08f5e2008-10-27 11:34:16 +00001819 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001820 return true;
1821 }
1822 case Expr::BinaryOperatorClass: {
1823 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1824 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1825
1826 Expr *PExp = Exp->getLHS();
1827 Expr *IExp = Exp->getRHS();
1828 if (IExp->getType()->isPointerType())
1829 std::swap(PExp, IExp);
1830
1831 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1832 return CheckAddressConstantExpression(PExp) ||
1833 CheckArithmeticConstantExpression(IExp);
1834 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001835 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001836 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001837 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001838 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1839 // Check for implicit promotion
1840 if (SubExpr->getType()->isFunctionType() ||
1841 SubExpr->getType()->isArrayType())
1842 return CheckAddressConstantExpressionLValue(SubExpr);
1843 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001844
1845 // Check for pointer->pointer cast
1846 if (SubExpr->getType()->isPointerType())
1847 return CheckAddressConstantExpression(SubExpr);
1848
Eli Friedman1fad3c62008-08-25 20:46:57 +00001849 if (SubExpr->getType()->isIntegralType()) {
1850 // Check for the special-case of a pointer->int->pointer cast;
1851 // this isn't standard, but some code requires it. See
1852 // PR2720 for an example.
1853 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1854 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1855 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1856 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1857 if (IntWidth >= PointerWidth) {
1858 return CheckAddressConstantExpression(SubCast->getSubExpr());
1859 }
1860 }
1861 }
1862 }
1863 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001864 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001865 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001866
Steve Narofffc08f5e2008-10-27 11:34:16 +00001867 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001868 return true;
1869 }
1870 case Expr::ConditionalOperatorClass: {
1871 // FIXME: Should we pedwarn here?
1872 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1873 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001874 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001875 return true;
1876 }
1877 if (CheckArithmeticConstantExpression(Exp->getCond()))
1878 return true;
1879 if (Exp->getLHS() &&
1880 CheckAddressConstantExpression(Exp->getLHS()))
1881 return true;
1882 return CheckAddressConstantExpression(Exp->getRHS());
1883 }
1884 case Expr::AddrLabelExprClass:
1885 return false;
1886 }
1887}
1888
Eli Friedman998dffb2008-06-09 05:05:07 +00001889static const Expr* FindExpressionBaseAddress(const Expr* E);
1890
1891static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1892 switch (E->getStmtClass()) {
1893 default:
1894 return E;
1895 case Expr::ParenExprClass: {
1896 const ParenExpr* PE = cast<ParenExpr>(E);
1897 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1898 }
1899 case Expr::MemberExprClass: {
1900 const MemberExpr *M = cast<MemberExpr>(E);
1901 if (M->isArrow())
1902 return FindExpressionBaseAddress(M->getBase());
1903 return FindExpressionBaseAddressLValue(M->getBase());
1904 }
1905 case Expr::ArraySubscriptExprClass: {
1906 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1907 return FindExpressionBaseAddress(ASE->getBase());
1908 }
1909 case Expr::UnaryOperatorClass: {
1910 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1911
1912 if (Exp->getOpcode() == UnaryOperator::Deref)
1913 return FindExpressionBaseAddress(Exp->getSubExpr());
1914
1915 return E;
1916 }
1917 }
1918}
1919
1920static const Expr* FindExpressionBaseAddress(const Expr* E) {
1921 switch (E->getStmtClass()) {
1922 default:
1923 return E;
1924 case Expr::ParenExprClass: {
1925 const ParenExpr* PE = cast<ParenExpr>(E);
1926 return FindExpressionBaseAddress(PE->getSubExpr());
1927 }
1928 case Expr::UnaryOperatorClass: {
1929 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1930
1931 // C99 6.6p9
1932 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1933 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1934
1935 if (Exp->getOpcode() == UnaryOperator::Extension)
1936 return FindExpressionBaseAddress(Exp->getSubExpr());
1937
1938 return E;
1939 }
1940 case Expr::BinaryOperatorClass: {
1941 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1942
1943 Expr *PExp = Exp->getLHS();
1944 Expr *IExp = Exp->getRHS();
1945 if (IExp->getType()->isPointerType())
1946 std::swap(PExp, IExp);
1947
1948 return FindExpressionBaseAddress(PExp);
1949 }
1950 case Expr::ImplicitCastExprClass: {
1951 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1952
1953 // Check for implicit promotion
1954 if (SubExpr->getType()->isFunctionType() ||
1955 SubExpr->getType()->isArrayType())
1956 return FindExpressionBaseAddressLValue(SubExpr);
1957
1958 // Check for pointer->pointer cast
1959 if (SubExpr->getType()->isPointerType())
1960 return FindExpressionBaseAddress(SubExpr);
1961
1962 // We assume that we have an arithmetic expression here;
1963 // if we don't, we'll figure it out later
1964 return 0;
1965 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001966 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001967 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1968
1969 // Check for pointer->pointer cast
1970 if (SubExpr->getType()->isPointerType())
1971 return FindExpressionBaseAddress(SubExpr);
1972
1973 // We assume that we have an arithmetic expression here;
1974 // if we don't, we'll figure it out later
1975 return 0;
1976 }
1977 }
1978}
1979
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001980bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001981 switch (Init->getStmtClass()) {
1982 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001983 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001984 return true;
1985 case Expr::ParenExprClass: {
1986 const ParenExpr* PE = cast<ParenExpr>(Init);
1987 return CheckArithmeticConstantExpression(PE->getSubExpr());
1988 }
1989 case Expr::FloatingLiteralClass:
1990 case Expr::IntegerLiteralClass:
1991 case Expr::CharacterLiteralClass:
1992 case Expr::ImaginaryLiteralClass:
1993 case Expr::TypesCompatibleExprClass:
1994 case Expr::CXXBoolLiteralExprClass:
1995 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001996 case Expr::CallExprClass:
1997 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001998 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001999
2000 // Allow any constant foldable calls to builtins.
2001 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002002 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002003
Steve Narofffc08f5e2008-10-27 11:34:16 +00002004 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002005 return true;
2006 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002007 case Expr::DeclRefExprClass:
2008 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002009 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2010 if (isa<EnumConstantDecl>(D))
2011 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002012 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002013 return true;
2014 }
2015 case Expr::CompoundLiteralExprClass:
2016 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2017 // but vectors are allowed to be magic.
2018 if (Init->getType()->isVectorType())
2019 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002020 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002021 return true;
2022 case Expr::UnaryOperatorClass: {
2023 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2024
2025 switch (Exp->getOpcode()) {
2026 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2027 // See C99 6.6p3.
2028 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002029 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002030 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002031 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002032 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2033 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002034 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002035 return true;
2036 case UnaryOperator::Extension:
2037 case UnaryOperator::LNot:
2038 case UnaryOperator::Plus:
2039 case UnaryOperator::Minus:
2040 case UnaryOperator::Not:
2041 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2042 }
2043 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002044 case Expr::SizeOfAlignOfExprClass: {
2045 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002046 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002047 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002048 return false;
2049 // alignof always evaluates to a constant.
2050 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002051 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002052 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002053 return true;
2054 }
2055 return false;
2056 }
2057 case Expr::BinaryOperatorClass: {
2058 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2059
2060 if (Exp->getLHS()->getType()->isArithmeticType() &&
2061 Exp->getRHS()->getType()->isArithmeticType()) {
2062 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2063 CheckArithmeticConstantExpression(Exp->getRHS());
2064 }
2065
Eli Friedman998dffb2008-06-09 05:05:07 +00002066 if (Exp->getLHS()->getType()->isPointerType() &&
2067 Exp->getRHS()->getType()->isPointerType()) {
2068 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2069 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2070
2071 // Only allow a null (constant integer) base; we could
2072 // allow some additional cases if necessary, but this
2073 // is sufficient to cover offsetof-like constructs.
2074 if (!LHSBase && !RHSBase) {
2075 return CheckAddressConstantExpression(Exp->getLHS()) ||
2076 CheckAddressConstantExpression(Exp->getRHS());
2077 }
2078 }
2079
Steve Narofffc08f5e2008-10-27 11:34:16 +00002080 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002081 return true;
2082 }
2083 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002084 case Expr::CStyleCastExprClass: {
Nuno Lopes7dd54222009-02-02 22:57:15 +00002085 const CastExpr *CE = cast<CastExpr>(Init);
2086 const Expr *SubExpr = CE->getSubExpr();
2087
Eli Friedmand662caa2008-09-01 22:08:17 +00002088 if (SubExpr->getType()->isArithmeticType())
2089 return CheckArithmeticConstantExpression(SubExpr);
2090
Eli Friedman266df142008-09-02 09:37:00 +00002091 if (SubExpr->getType()->isPointerType()) {
2092 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopes7dd54222009-02-02 22:57:15 +00002093 if (Base) {
2094 // the cast is only valid if done to a wide enough type
2095 if (Context.getTypeSize(CE->getType()) >=
2096 Context.getTypeSize(SubExpr->getType()))
2097 return false;
2098 } else {
2099 // If the pointer has a null base, this is an offsetof-like construct
2100 return CheckAddressConstantExpression(SubExpr);
2101 }
Eli Friedman266df142008-09-02 09:37:00 +00002102 }
2103
Steve Narofffc08f5e2008-10-27 11:34:16 +00002104 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002105 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002106 }
2107 case Expr::ConditionalOperatorClass: {
2108 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002109
2110 // If GNU extensions are disabled, we require all operands to be arithmetic
2111 // constant expressions.
2112 if (getLangOptions().NoExtensions) {
2113 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2114 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2115 CheckArithmeticConstantExpression(Exp->getRHS());
2116 }
2117
2118 // Otherwise, we have to emulate some of the behavior of fold here.
2119 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2120 // because it can constant fold things away. To retain compatibility with
2121 // GCC code, we see if we can fold the condition to a constant (which we
2122 // should always be able to do in theory). If so, we only require the
2123 // specified arm of the conditional to be a constant. This is a horrible
2124 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002125 Expr::EvalResult EvalResult;
2126 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2127 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002128 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002129 // won't be able to either. Use it to emit the diagnostic though.
2130 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002131 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002132 return Res;
2133 }
2134
2135 // Verify that the side following the condition is also a constant.
2136 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002137 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002138 std::swap(TrueSide, FalseSide);
2139
2140 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002141 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002142
2143 // Okay, the evaluated side evaluates to a constant, so we accept this.
2144 // Check to see if the other side is obviously not a constant. If so,
2145 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002146 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002147 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002148 diag::ext_typecheck_expression_not_constant_but_accepted)
2149 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002150 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002151 }
2152 }
2153}
2154
2155bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002156 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2157 Init = DIE->getInit();
2158
Nuno Lopese7280452008-07-07 16:46:50 +00002159 Init = Init->IgnoreParens();
2160
Nate Begemand6d2f772009-01-18 03:20:47 +00002161 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002162 return false;
2163
Eli Friedman02c22ce2008-05-20 13:48:25 +00002164 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2165 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2166 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2167
Nuno Lopese7280452008-07-07 16:46:50 +00002168 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2169 return CheckForConstantInitializer(e->getInitializer(), DclT);
2170
Douglas Gregorc9e012a2009-01-29 17:44:32 +00002171 if (isa<ImplicitValueInitExpr>(Init)) {
2172 // FIXME: In C++, check for non-POD types.
2173 return false;
2174 }
2175
Eli Friedman02c22ce2008-05-20 13:48:25 +00002176 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2177 unsigned numInits = Exp->getNumInits();
2178 for (unsigned i = 0; i < numInits; i++) {
2179 // FIXME: Need to get the type of the declaration for C++,
2180 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002181
Eli Friedman02c22ce2008-05-20 13:48:25 +00002182 if (CheckForConstantInitializer(Exp->getInit(i),
2183 Exp->getInit(i)->getType()))
2184 return true;
2185 }
2186 return false;
2187 }
2188
Anders Carlssonf6791c62008-12-05 05:09:56 +00002189 // FIXME: We can probably remove some of this code below, now that
2190 // Expr::Evaluate is doing the heavy lifting for scalars.
2191
Eli Friedman02c22ce2008-05-20 13:48:25 +00002192 if (Init->isNullPointerConstant(Context))
2193 return false;
2194 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002195 QualType InitTy = Context.getCanonicalType(Init->getType())
2196 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002197 if (InitTy == Context.BoolTy) {
2198 // Special handling for pointers implicitly cast to bool;
2199 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2200 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2201 Expr* SubE = ICE->getSubExpr();
2202 if (SubE->getType()->isPointerType() ||
2203 SubE->getType()->isArrayType() ||
2204 SubE->getType()->isFunctionType()) {
2205 return CheckAddressConstantExpression(Init);
2206 }
2207 }
2208 } else if (InitTy->isIntegralType()) {
2209 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002210 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002211 SubE = CE->getSubExpr();
2212 // Special check for pointer cast to int; we allow as an extension
2213 // an address constant cast to an integer if the integer
2214 // is of an appropriate width (this sort of code is apparently used
2215 // in some places).
2216 // FIXME: Add pedwarn?
2217 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2218 if (SubE && (SubE->getType()->isPointerType() ||
2219 SubE->getType()->isArrayType() ||
2220 SubE->getType()->isFunctionType())) {
2221 unsigned IntWidth = Context.getTypeSize(Init->getType());
2222 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2223 if (IntWidth >= PointerWidth)
2224 return CheckAddressConstantExpression(Init);
2225 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002226 }
2227
2228 return CheckArithmeticConstantExpression(Init);
2229 }
2230
2231 if (Init->getType()->isPointerType())
2232 return CheckAddressConstantExpression(Init);
2233
Eli Friedman25086f02008-05-30 18:14:48 +00002234 // An array type at the top level that isn't an init-list must
2235 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002236 if (Init->getType()->isArrayType())
2237 return false;
2238
Nuno Lopes1dc26762008-09-01 18:42:41 +00002239 if (Init->getType()->isFunctionType())
2240 return false;
2241
Steve Naroffdff3fb22008-10-02 17:12:56 +00002242 // Allow block exprs at top level.
2243 if (Init->getType()->isBlockPointerType())
2244 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002245
2246 // GCC cast to union extension
2247 // note: the validity of the cast expr is checked by CheckCastTypes()
2248 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2249 QualType T = C->getType();
2250 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2251 }
2252
Steve Narofffc08f5e2008-10-27 11:34:16 +00002253 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002254 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002255}
2256
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002257void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002258 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2259}
2260
2261/// AddInitializerToDecl - Adds the initializer Init to the
2262/// declaration dcl. If DirectInit is true, this is C++ direct
2263/// initialization rather than copy initialization.
2264void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002265 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002266 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002267 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002268
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002269 // If there is no declaration, there was an error parsing it. Just ignore
2270 // the initializer.
2271 if (RealDecl == 0) {
2272 delete Init;
2273 return;
2274 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002275
Steve Naroff420d0f52007-09-12 20:13:48 +00002276 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2277 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002278 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002279 RealDecl->setInvalidDecl();
2280 return;
2281 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002282 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002283 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002284 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002285 if (VDecl->isBlockVarDecl()) {
2286 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002287 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002288 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002289 VDecl->setInvalidDecl();
2290 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002291 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002292 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002293 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002294
2295 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2296 if (!getLangOptions().CPlusPlus) {
2297 if (SC == VarDecl::Static) // C99 6.7.8p4.
2298 CheckForConstantInitializer(Init, DclT);
2299 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002300 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002301 } else if (VDecl->isFileVarDecl()) {
2302 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002303 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002304 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002305 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002306 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002307 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002308
Anders Carlssonea7140a2008-08-22 05:00:02 +00002309 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2310 if (!getLangOptions().CPlusPlus) {
2311 // C99 6.7.8p4. All file scoped initializers need to be constant.
2312 CheckForConstantInitializer(Init, DclT);
2313 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002314 }
2315 // If the type changed, it means we had an incomplete type that was
2316 // completed by the initializer. For example:
2317 // int ary[] = { 1, 3, 5 };
2318 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002319 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002320 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002321 Init->setType(DclT);
2322 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002323
2324 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002325 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002326 return;
2327}
2328
Douglas Gregor81c29152008-10-29 00:13:59 +00002329void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2330 Decl *RealDecl = static_cast<Decl *>(dcl);
2331
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002332 // If there is no declaration, there was an error parsing it. Just ignore it.
2333 if (RealDecl == 0)
2334 return;
2335
Douglas Gregor81c29152008-10-29 00:13:59 +00002336 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2337 QualType Type = Var->getType();
2338 // C++ [dcl.init.ref]p3:
2339 // The initializer can be omitted for a reference only in a
2340 // parameter declaration (8.3.5), in the declaration of a
2341 // function return type, in the declaration of a class member
2342 // within its class declaration (9.2), and where the extern
2343 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002344 if (Type->isReferenceType() &&
2345 Var->getStorageClass() != VarDecl::Extern &&
2346 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002347 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002348 << Var->getDeclName()
2349 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002350 Var->setInvalidDecl();
2351 return;
2352 }
2353
2354 // C++ [dcl.init]p9:
2355 //
2356 // If no initializer is specified for an object, and the object
2357 // is of (possibly cv-qualified) non-POD class type (or array
2358 // thereof), the object shall be default-initialized; if the
2359 // object is of const-qualified type, the underlying class type
2360 // shall have a user-declared default constructor.
2361 if (getLangOptions().CPlusPlus) {
2362 QualType InitType = Type;
2363 if (const ArrayType *Array = Context.getAsArrayType(Type))
2364 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002365 if (Var->getStorageClass() != VarDecl::Extern &&
2366 Var->getStorageClass() != VarDecl::PrivateExtern &&
2367 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002368 const CXXConstructorDecl *Constructor
2369 = PerformInitializationByConstructor(InitType, 0, 0,
2370 Var->getLocation(),
2371 SourceRange(Var->getLocation(),
2372 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002373 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002374 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002375 if (!Constructor)
2376 Var->setInvalidDecl();
2377 }
2378 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002379
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002380#if 0
2381 // FIXME: Temporarily disabled because we are not properly parsing
2382 // linkage specifications on declarations, e.g.,
2383 //
2384 // extern "C" const CGPoint CGPointerZero;
2385 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002386 // C++ [dcl.init]p9:
2387 //
2388 // If no initializer is specified for an object, and the
2389 // object is of (possibly cv-qualified) non-POD class type (or
2390 // array thereof), the object shall be default-initialized; if
2391 // the object is of const-qualified type, the underlying class
2392 // type shall have a user-declared default
2393 // constructor. Otherwise, if no initializer is specified for
2394 // an object, the object and its subobjects, if any, have an
2395 // indeterminate initial value; if the object or any of its
2396 // subobjects are of const-qualified type, the program is
2397 // ill-formed.
2398 //
2399 // This isn't technically an error in C, so we don't diagnose it.
2400 //
2401 // FIXME: Actually perform the POD/user-defined default
2402 // constructor check.
2403 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002404 Context.getCanonicalType(Type).isConstQualified() &&
2405 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002406 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2407 << Var->getName()
2408 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002409#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002410 }
2411}
2412
Chris Lattner4b009652007-07-25 00:24:17 +00002413/// The declarators are chained together backwards, reverse the list.
2414Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2415 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002416 Decl *GroupDecl = static_cast<Decl*>(group);
2417 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002418 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002419
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002420 Decl *Group = dyn_cast<Decl>(GroupDecl);
2421 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002422 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002423 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002424 else { // reverse the list.
2425 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002426 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002427 Group->setNextDeclarator(NewGroup);
2428 NewGroup = Group;
2429 Group = Next;
2430 }
2431 }
2432 // Perform semantic analysis that depends on having fully processed both
2433 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002434 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002435 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2436 if (!IDecl)
2437 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002438 QualType T = IDecl->getType();
2439
Anders Carlsson68adbd12008-12-07 00:20:55 +00002440 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002441 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002442
2443 // FIXME: This won't give the correct result for
2444 // int a[10][n];
2445 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002446 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002447 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2448 SizeRange;
2449
Eli Friedman8ff07782008-02-15 18:16:39 +00002450 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002451 } else {
2452 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2453 // static storage duration, it shall not have a variable length array.
2454 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002455 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2456 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002457 IDecl->setInvalidDecl();
2458 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002459 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2460 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002461 IDecl->setInvalidDecl();
2462 }
2463 }
2464 } else if (T->isVariablyModifiedType()) {
2465 if (IDecl->isFileVarDecl()) {
2466 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2467 IDecl->setInvalidDecl();
2468 } else {
2469 if (IDecl->getStorageClass() == VarDecl::Extern) {
2470 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2471 IDecl->setInvalidDecl();
2472 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002473 }
2474 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002475
Steve Naroff6a0e2092007-09-12 14:07:44 +00002476 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2477 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002478 if (IDecl->isBlockVarDecl() &&
2479 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002480 if (!IDecl->isInvalidDecl() &&
2481 DiagnoseIncompleteType(IDecl->getLocation(), T,
2482 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002483 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002484 }
2485 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2486 // object that has file scope without an initializer, and without a
2487 // storage-class specifier or with the storage-class specifier "static",
2488 // constitutes a tentative definition. Note: A tentative definition with
2489 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002490 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002491 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002492 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2493 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002494 } else if (!IDecl->isInvalidDecl() &&
2495 DiagnoseIncompleteType(IDecl->getLocation(), T,
2496 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002497 // C99 6.9.2p3: If the declaration of an identifier for an object is
2498 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2499 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002500 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002501 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002502 if (IDecl->isFileVarDecl())
2503 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002504 }
2505 return NewGroup;
2506}
Steve Naroff91b03f72007-08-28 03:03:08 +00002507
Chris Lattner3e254fb2008-04-08 04:40:51 +00002508/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2509/// to introduce parameters into function prototype scope.
2510Sema::DeclTy *
2511Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002512 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002513
Chris Lattner3e254fb2008-04-08 04:40:51 +00002514 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002515 VarDecl::StorageClass StorageClass = VarDecl::None;
2516 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2517 StorageClass = VarDecl::Register;
2518 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002519 Diag(DS.getStorageClassSpecLoc(),
2520 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002521 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002522 }
2523 if (DS.isThreadSpecified()) {
2524 Diag(DS.getThreadSpecLoc(),
2525 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002526 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002527 }
2528
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002529 // Check that there are no default arguments inside the type of this
2530 // parameter (C++ only).
2531 if (getLangOptions().CPlusPlus)
2532 CheckExtraCXXDefaultArguments(D);
2533
Chris Lattner3e254fb2008-04-08 04:40:51 +00002534 // In this context, we *do not* check D.getInvalidType(). If the declarator
2535 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2536 // though it will not reflect the user specified type.
2537 QualType parmDeclType = GetTypeForDeclarator(D, S);
2538
2539 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2540
Chris Lattner4b009652007-07-25 00:24:17 +00002541 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2542 // Can this happen for params? We already checked that they don't conflict
2543 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002544 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002545 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00002546 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002547 if (PrevDecl->isTemplateParameter()) {
2548 // Maybe we will complain about the shadowed template parameter.
2549 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2550 // Just pretend that we didn't see the previous declaration.
2551 PrevDecl = 0;
2552 } else if (S->isDeclScope(PrevDecl)) {
2553 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002554
Chris Lattner310dea32009-01-21 02:38:50 +00002555 // Recover by removing the name
2556 II = 0;
2557 D.SetIdentifier(0, D.getIdentifierLoc());
2558 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002559 }
Chris Lattner4b009652007-07-25 00:24:17 +00002560 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002561
2562 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2563 // Doing the promotion here has a win and a loss. The win is the type for
2564 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2565 // code generator). The loss is the orginal type isn't preserved. For example:
2566 //
2567 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2568 // int blockvardecl[5];
2569 // sizeof(parmvardecl); // size == 4
2570 // sizeof(blockvardecl); // size == 20
2571 // }
2572 //
2573 // For expressions, all implicit conversions are captured using the
2574 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2575 //
2576 // FIXME: If a source translation tool needs to see the original type, then
2577 // we need to consider storing both types (in ParmVarDecl)...
2578 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002579 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002580 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002581 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002582 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002583 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002584
Chris Lattner3e254fb2008-04-08 04:40:51 +00002585 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2586 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002587 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002588 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002589
Chris Lattner3e254fb2008-04-08 04:40:51 +00002590 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002591 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002592
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002593 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2594 if (D.getCXXScopeSpec().isSet()) {
2595 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2596 << D.getCXXScopeSpec().getRange();
2597 New->setInvalidDecl();
2598 }
2599
Douglas Gregor8acb7272008-12-11 16:49:14 +00002600 // Add the parameter declaration into this scope.
2601 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002602 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002603 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002604
Chris Lattner9b384ca2008-06-29 00:02:00 +00002605 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002606 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002607
Chris Lattner4b009652007-07-25 00:24:17 +00002608}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002609
Douglas Gregor65075ec2009-01-23 16:23:13 +00002610void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002611 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2612 "Not a function declarator!");
2613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002614
Chris Lattner4b009652007-07-25 00:24:17 +00002615 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2616 // for a K&R function.
2617 if (!FTI.hasPrototype) {
2618 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002619 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002620 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2621 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002622 // Implicitly declare the argument as type 'int' for lack of a better
2623 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002624 DeclSpec DS;
2625 const char* PrevSpec; // unused
2626 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2627 PrevSpec);
2628 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2629 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002630 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002631 }
2632 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002633 }
2634}
2635
2636Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2637 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2638 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2639 "Not a function declarator!");
2640 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2641
2642 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002643 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002644 }
2645
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002646 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002647
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002648 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002649 ActOnDeclarator(ParentScope, D, 0,
2650 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002651}
2652
2653Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2654 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002655 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002656
2657 // See if this is a redefinition.
2658 const FunctionDecl *Definition;
2659 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002660 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002661 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002662 }
2663
Douglas Gregor8acb7272008-12-11 16:49:14 +00002664 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002665
Chris Lattner3e254fb2008-04-08 04:40:51 +00002666 // Check the validity of our function parameters
2667 CheckParmsForFunctionDef(FD);
2668
2669 // Introduce our parameters into the function scope
2670 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2671 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002672 Param->setOwningFunction(FD);
2673
Chris Lattner3e254fb2008-04-08 04:40:51 +00002674 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002675 if (Param->getIdentifier())
2676 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002677 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002678
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002679 // Checking attributes of current function definition
2680 // dllimport attribute.
2681 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2682 // dllimport attribute cannot be applied to definition.
2683 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2684 Diag(FD->getLocation(),
2685 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2686 << "dllimport";
2687 FD->setInvalidDecl();
2688 return FD;
2689 } else {
2690 // If a symbol previously declared dllimport is later defined, the
2691 // attribute is ignored in subsequent references, and a warning is
2692 // emitted.
2693 Diag(FD->getLocation(),
2694 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2695 << FD->getNameAsCString() << "dllimport";
2696 }
2697 }
Chris Lattner4b009652007-07-25 00:24:17 +00002698 return FD;
2699}
2700
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002701Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002702 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002703 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002704 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002705 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002706 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002707 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002708 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002709 } else
2710 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002711 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002712 // Verify and clean out per-function state.
2713
2714 // Check goto/label use.
2715 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2716 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2717 // Verify that we have no forward references left. If so, there was a goto
2718 // or address of a label taken, but no definition of it. Label fwd
2719 // definitions are indicated with a null substmt.
2720 if (I->second->getSubStmt() == 0) {
2721 LabelStmt *L = I->second;
2722 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002723 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002724
2725 // At this point, we have gotos that use the bogus label. Stitch it into
2726 // the function body so that they aren't leaked and that the AST is well
2727 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002728 if (Body) {
2729 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002730 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002731 } else {
2732 // The whole function wasn't parsed correctly, just delete this.
2733 delete L;
2734 }
Chris Lattner4b009652007-07-25 00:24:17 +00002735 }
2736 }
2737 LabelMap.clear();
2738
Steve Naroff99ee4302007-11-11 23:20:51 +00002739 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002740}
2741
Chris Lattner4b009652007-07-25 00:24:17 +00002742/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2743/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002744NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2745 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002746 // Extension in C99. Legal in C90, but warn about it.
2747 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002748 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002749 else
Chris Lattner65cae292008-11-19 08:23:25 +00002750 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002751
2752 // FIXME: handle stuff like:
2753 // void foo() { extern float X(); }
2754 // void bar() { X(); } <-- implicit decl for X in another scope.
2755
2756 // Set a Declarator for the implicit definition: int foo();
2757 const char *Dummy;
2758 DeclSpec DS;
2759 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2760 Error = Error; // Silence warning.
2761 assert(!Error && "Error setting up implicit decl!");
2762 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002763 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002764 D.SetIdentifier(&II, Loc);
2765
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002766 // Insert this function into translation-unit scope.
2767
2768 DeclContext *PrevDC = CurContext;
2769 CurContext = Context.getTranslationUnitDecl();
2770
Steve Naroff9104f3c2008-04-04 14:32:09 +00002771 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002772 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002773 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002774
2775 CurContext = PrevDC;
2776
Steve Naroff9104f3c2008-04-04 14:32:09 +00002777 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002778}
2779
2780
Chris Lattner82bb4792007-11-14 06:34:38 +00002781TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002782 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002783 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002784 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002785
2786 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002787 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2788 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002789 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002790 T);
2791 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002792 if (D.getInvalidType())
2793 NewTD->setInvalidDecl();
2794 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002795}
2796
Steve Naroff0acc9c92007-09-15 18:49:24 +00002797/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002798/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002799/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002800/// reference/declaration/definition of a tag.
Douglas Gregor279272e2009-02-04 19:02:06 +00002801///
2802/// This creates and returns template declarations if any template parameter
2803/// lists are given.
Douglas Gregor98b27542009-01-17 00:42:38 +00002804Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002805 SourceLocation KWLoc, const CXXScopeSpec &SS,
2806 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002807 AttributeList *Attr,
2808 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002809 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002810 assert((Name != 0 || TK == TK_Definition) &&
2811 "Nameless record must be a definition!");
Douglas Gregor279272e2009-02-04 19:02:06 +00002812 assert((TemplateParameterLists.size() == 0 || TK != TK_Reference) &&
2813 "Can't have a reference to a template");
2814 assert((TemplateParameterLists.size() == 0 ||
2815 TagSpec != DeclSpec::TST_enum) &&
2816 "No such thing as an enum template");
2817
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002818 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002819 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002820 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002821 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2822 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2823 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2824 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002825 }
2826
Douglas Gregorb748fc52009-01-12 22:49:06 +00002827 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002828 DeclContext *DC = CurContext;
Douglas Gregor09be81b2009-02-04 17:27:36 +00002829 NamedDecl *PrevDecl = 0;
Douglas Gregor279272e2009-02-04 19:02:06 +00002830 TemplateDecl *PrevTemplate = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002831
Douglas Gregor98b27542009-01-17 00:42:38 +00002832 bool Invalid = false;
2833
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002834 if (Name && SS.isNotEmpty()) {
2835 // We have a nested-name tag ('struct foo::bar').
2836
2837 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002838 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002839 Name = 0;
2840 goto CreateNewDecl;
2841 }
2842
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002843 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor2d87eb02009-02-03 00:34:39 +00002844 SearchDC = DC;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002845 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002846 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor7a7be652009-02-03 19:21:40 +00002847 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002848
2849 // A tag 'foo::bar' must already exist.
2850 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002851 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002852 Name = 0;
2853 goto CreateNewDecl;
2854 }
Chris Lattner310dea32009-01-21 02:38:50 +00002855 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002856 // If this is a named struct, check to see if there was a previous forward
2857 // declaration or definition.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002858 // FIXME: We're looking into outer scopes here, even when we
2859 // shouldn't be. Doing so can result in ambiguities that we
2860 // shouldn't be diagnosing.
Douglas Gregor362c8952009-02-03 19:26:08 +00002861 LookupResult R = LookupName(S, Name, LookupTagName,
2862 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor7a7be652009-02-03 19:21:40 +00002863 if (R.isAmbiguous()) {
2864 DiagnoseAmbiguousLookup(R, Name, NameLoc);
2865 // FIXME: This is not best way to recover from case like:
2866 //
2867 // struct S s;
2868 //
2869 // causes needless err_ovl_no_viable_function_in_init latter.
2870 Name = 0;
2871 PrevDecl = 0;
2872 Invalid = true;
2873 }
2874 else
Douglas Gregor09be81b2009-02-04 17:27:36 +00002875 PrevDecl = R;
Douglas Gregordb568cf2009-01-08 20:45:30 +00002876
2877 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2878 // FIXME: This makes sure that we ignore the contexts associated
2879 // with C structs, unions, and enums when looking for a matching
2880 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002881 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002882 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2883 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002884 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002885 }
2886
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002887 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002888 // Maybe we will complain about the shadowed template parameter.
2889 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2890 // Just pretend that we didn't see the previous declaration.
2891 PrevDecl = 0;
2892 }
2893
Ted Kremenekd4434152008-09-02 21:26:19 +00002894 if (PrevDecl) {
Douglas Gregor279272e2009-02-04 19:02:06 +00002895 // If we found a template, keep track of the template and its
2896 // underlying declaration.
2897 if ((PrevTemplate = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl)))
2898 PrevDecl = PrevTemplate->getTemplatedDecl();
2899
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002900 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002901 // If this is a use of a previous tag, or if the tag is already declared
2902 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002903 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002904 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002905 // Make sure that this wasn't declared as an enum and now used as a
2906 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002907 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002908 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002909 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002910 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002911 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002912 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002913 Invalid = true;
Douglas Gregor279272e2009-02-04 19:02:06 +00002914 // FIXME: Add template/non-template redecl check
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002915 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002916 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002917
Douglas Gregorae644892008-12-15 16:32:14 +00002918 // FIXME: In the future, return a variant or some other clue
2919 // for the consumer of this Decl to know it doesn't own it.
2920 // For our current ASTs this shouldn't be a problem, but will
2921 // need to be changed with DeclGroups.
2922 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002923 return PrevDecl;
Douglas Gregor279272e2009-02-04 19:02:06 +00002924
Douglas Gregorae644892008-12-15 16:32:14 +00002925 // Diagnose attempts to redefine a tag.
2926 if (TK == TK_Definition) {
2927 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2928 Diag(NameLoc, diag::err_redefinition) << Name;
2929 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002930 // If this is a redefinition, recover by making this
2931 // struct be anonymous, which will make any later
2932 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002933 Name = 0;
2934 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002935 Invalid = true;
2936 } else {
2937 // If the type is currently being defined, complain
2938 // about a nested redefinition.
2939 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2940 if (Tag->isBeingDefined()) {
2941 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2942 Diag(PrevTagDecl->getLocation(),
2943 diag::note_previous_definition);
2944 Name = 0;
2945 PrevDecl = 0;
2946 Invalid = true;
2947 }
Douglas Gregorae644892008-12-15 16:32:14 +00002948 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002949
Douglas Gregorae644892008-12-15 16:32:14 +00002950 // Okay, this is definition of a previously declared or referenced
2951 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002952 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002953 }
Douglas Gregorae644892008-12-15 16:32:14 +00002954 // If we get here we have (another) forward declaration or we
2955 // have a definition. Just create a new decl.
2956 } else {
2957 // If we get here, this is a definition of a new tag type in a nested
2958 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2959 // new decl/type. We set PrevDecl to NULL so that the entities
2960 // have distinct types.
2961 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002962 }
Douglas Gregorae644892008-12-15 16:32:14 +00002963 // If we get here, we're going to create a new Decl. If PrevDecl
2964 // is non-NULL, it's a definition of the tag declared by
2965 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002966 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00002967 // PrevDecl is a namespace, template, or anything else
2968 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002969 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002970 // The tag name clashes with a namespace name, issue an error and
2971 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002972 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002973 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002974 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002975 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002976 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002977 } else {
2978 // The existing declaration isn't relevant to us; we're in a
2979 // new scope, so clear out the previous declaration.
2980 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002981 }
Chris Lattner4b009652007-07-25 00:24:17 +00002982 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002983 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2984 (Kind != TagDecl::TK_enum)) {
2985 // C++ [basic.scope.pdecl]p5:
2986 // -- for an elaborated-type-specifier of the form
2987 //
2988 // class-key identifier
2989 //
2990 // if the elaborated-type-specifier is used in the
2991 // decl-specifier-seq or parameter-declaration-clause of a
2992 // function defined in namespace scope, the identifier is
2993 // declared as a class-name in the namespace that contains
2994 // the declaration; otherwise, except as a friend
2995 // declaration, the identifier is declared in the smallest
2996 // non-class, non-function-prototype scope that contains the
2997 // declaration.
2998 //
2999 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3000 // C structs and unions.
3001
3002 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00003003 // FIXME: We would like to maintain the current DeclContext as the
3004 // lexical context,
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003005 while (SearchDC->isRecord())
3006 SearchDC = SearchDC->getParent();
Douglas Gregorcab994d2009-01-09 22:42:13 +00003007
3008 // Find the scope where we'll be declaring the tag.
3009 while (S->isClassScope() ||
3010 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003011 ((S->getFlags() & Scope::DeclScope) == 0) ||
3012 (S->getEntity() &&
3013 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00003014 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00003015 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00003016
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003017CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00003018
3019 // If there is an identifier, use the location of the identifier as the
3020 // location of the decl, otherwise use the location of the struct/union
3021 // keyword.
3022 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3023
Douglas Gregorae644892008-12-15 16:32:14 +00003024 // Otherwise, create a new declaration. If there is a previous
3025 // declaration of the same entity, the two will be linked via
3026 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003027 TagDecl *New;
Douglas Gregor279272e2009-02-04 19:02:06 +00003028 ClassTemplateDecl *NewTemplate = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +00003029
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003030 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003031 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3032 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003033 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003034 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003035 // If this is an undefined enum, warn.
3036 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003037 } else {
3038 // struct/union/class
3039
Chris Lattner4b009652007-07-25 00:24:17 +00003040 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3041 // struct X { int A; } D; D should chain to X.
Douglas Gregor279272e2009-02-04 19:02:06 +00003042 if (getLangOptions().CPlusPlus) {
Ted Kremenek770b11d2008-09-05 17:39:33 +00003043 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003044 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003045 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregor279272e2009-02-04 19:02:06 +00003046
3047 // If there's are template parameters, then this must be a class
3048 // template. Create the template decl node also.
3049 // FIXME: Do we always create template decls? We may not for forward
3050 // declarations.
3051 // FIXME: What are we actually going to do with the template decl?
3052 if (TemplateParameterLists.size() > 0) {
3053 // FIXME: The allocation of the parameters is probably incorrect.
3054 // FIXME: Does the TemplateDecl have the same name as the class?
3055 TemplateParameterList *Params =
3056 TemplateParameterList::Create(Context,
3057 (Decl **)TemplateParameterLists.get(),
3058 TemplateParameterLists.size());
3059 NewTemplate = ClassTemplateDecl::Create(Context, DC, Loc,
3060 DeclarationName(Name), Params,
3061 New);
3062 }
3063 } else
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003064 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003065 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003066 }
Douglas Gregorae644892008-12-15 16:32:14 +00003067
3068 if (Kind != TagDecl::TK_enum) {
3069 // Handle #pragma pack: if the #pragma pack stack has non-default
3070 // alignment, make up a packed attribute for this decl. These
3071 // attributes are checked when the ASTContext lays out the
3072 // structure.
3073 //
3074 // It is important for implementing the correct semantics that this
3075 // happen here (in act on tag decl). The #pragma pack stack is
3076 // maintained as a result of parser callbacks which can occur at
3077 // many points during the parsing of a struct declaration (because
3078 // the #pragma tokens are effectively skipped over during the
3079 // parsing of the struct).
3080 if (unsigned Alignment = PackContext.getAlignment())
3081 New->addAttr(new PackedAttr(Alignment * 8));
3082 }
3083
Douglas Gregorb31f2942009-01-28 17:15:10 +00003084 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3085 // C++ [dcl.typedef]p3:
3086 // [...] Similarly, in a given scope, a class or enumeration
3087 // shall not be declared with the same name as a typedef-name
3088 // that is declared in that scope and refers to a type other
3089 // than the class or enumeration itself.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003090 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregorb31f2942009-01-28 17:15:10 +00003091 TypedefDecl *PrevTypedef = 0;
3092 if (Lookup.getKind() == LookupResult::Found)
3093 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3094
3095 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3096 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3097 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3098 Diag(Loc, diag::err_tag_definition_of_typedef)
3099 << Context.getTypeDeclType(New)
3100 << PrevTypedef->getUnderlyingType();
3101 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3102 Invalid = true;
3103 }
3104 }
3105
Douglas Gregor98b27542009-01-17 00:42:38 +00003106 if (Invalid)
3107 New->setInvalidDecl();
3108
Douglas Gregorae644892008-12-15 16:32:14 +00003109 if (Attr)
3110 ProcessDeclAttributeList(New, Attr);
3111
Douglas Gregor98b27542009-01-17 00:42:38 +00003112 // If we're declaring or defining a tag in function prototype scope
3113 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003114 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3115 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3116
Douglas Gregorae644892008-12-15 16:32:14 +00003117 // Set the lexical context. If the tag has a C++ scope specifier, the
3118 // lexical context will be different from the semantic context.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003119 New->setLexicalDeclContext(CurContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003120
3121 if (TK == TK_Definition)
3122 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003123
3124 // If this has an identifier, add it to the scope stack.
3125 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003126 S = getNonFieldDeclScope(S);
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003127 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003128 } else {
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003129 CurContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003130 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003131
Chris Lattner4b009652007-07-25 00:24:17 +00003132 return New;
3133}
3134
Douglas Gregordb568cf2009-01-08 20:45:30 +00003135void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003136 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003137 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3138
3139 // Enter the tag context.
3140 PushDeclContext(S, Tag);
3141
3142 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3143 FieldCollector->StartClass();
3144
3145 if (Record->getIdentifier()) {
3146 // C++ [class]p2:
3147 // [...] The class-name is also inserted into the scope of the
3148 // class itself; this is known as the injected-class-name. For
3149 // purposes of access checking, the injected-class-name is treated
3150 // as if it were a public member name.
3151 RecordDecl *InjectedClassName
3152 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3153 CurContext, Record->getLocation(),
3154 Record->getIdentifier(), Record);
3155 InjectedClassName->setImplicit();
3156 PushOnScopeChains(InjectedClassName, S);
3157 }
3158 }
3159}
3160
3161void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003162 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003163 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3164
3165 if (isa<CXXRecordDecl>(Tag))
3166 FieldCollector->FinishClass();
3167
3168 // Exit this scope of this tag's definition.
3169 PopDeclContext();
3170
3171 // Notify the consumer that we've defined a tag.
3172 Consumer.HandleTagDeclDefinition(Tag);
3173}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003174
Chris Lattnera73e2202008-11-12 21:17:48 +00003175/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3176/// types into constant array types in certain situations which would otherwise
3177/// be errors (for GCC compatibility).
3178static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3179 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003180 // This method tries to turn a variable array into a constant
3181 // array even when the size isn't an ICE. This is necessary
3182 // for compatibility with code that depends on gcc's buggy
3183 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003184 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3185 if (!VLATy) return QualType();
3186
Anders Carlsson8c3de802008-12-19 20:58:05 +00003187 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003188 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003189 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003190 return QualType();
3191
Anders Carlsson8c3de802008-12-19 20:58:05 +00003192 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3193 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes5ba3b262009-02-02 22:32:08 +00003194 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3195 return Context.getConstantArrayType(VLATy->getElementType(),
3196 Res, ArrayType::Normal, 0);
3197 return QualType();
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003198}
3199
Anders Carlsson108229a2008-12-06 20:33:04 +00003200bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003201 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003202 // FIXME: 6.7.2.1p4 - verify the field type.
3203
3204 llvm::APSInt Value;
3205 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3206 return true;
3207
Chris Lattner8464c372008-12-12 04:56:04 +00003208 // Zero-width bitfield is ok for anonymous field.
3209 if (Value == 0 && FieldName)
3210 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3211
3212 if (Value.isNegative())
3213 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003214
3215 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3216 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003217 if (TypeSize && Value.getZExtValue() > TypeSize)
3218 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3219 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003220
3221 return false;
3222}
3223
Steve Naroff0acc9c92007-09-15 18:49:24 +00003224/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003225/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003226Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003227 SourceLocation DeclStart,
3228 Declarator &D, ExprTy *BitfieldWidth) {
3229 IdentifierInfo *II = D.getIdentifier();
3230 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003231 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003232 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003233 if (II) Loc = D.getIdentifierLoc();
3234
3235 // FIXME: Unnamed fields can be handled in various different ways, for
3236 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003237
Chris Lattner4b009652007-07-25 00:24:17 +00003238 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003239 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3240 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003241
Chris Lattner4b009652007-07-25 00:24:17 +00003242 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3243 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003244 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003245 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003246 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003247 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003248 T = FixedTy;
3249 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003250 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003251 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003252 InvalidDecl = true;
3253 }
Chris Lattner4b009652007-07-25 00:24:17 +00003254 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003255
3256 if (BitWidth) {
3257 if (VerifyBitField(Loc, II, T, BitWidth))
3258 InvalidDecl = true;
3259 } else {
3260 // Not a bitfield.
3261
3262 // validate II.
3263
3264 }
3265
Chris Lattner4b009652007-07-25 00:24:17 +00003266 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003267 FieldDecl *NewFD;
3268
Douglas Gregor8acb7272008-12-11 16:49:14 +00003269 NewFD = FieldDecl::Create(Context, Record,
3270 Loc, II, T, BitWidth,
3271 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003272 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003273
Douglas Gregordb568cf2009-01-08 20:45:30 +00003274 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003275 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003276 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3277 && !isa<TagDecl>(PrevDecl)) {
3278 Diag(Loc, diag::err_duplicate_member) << II;
3279 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3280 NewFD->setInvalidDecl();
3281 Record->setInvalidDecl();
3282 }
3283 }
3284
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003285 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003286 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003287 if (!T->isPODType())
3288 cast<CXXRecordDecl>(Record)->setPOD(false);
3289 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003290
Chris Lattner9b384ca2008-06-29 00:02:00 +00003291 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003292
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003293 if (D.getInvalidType() || InvalidDecl)
3294 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003295
Douglas Gregordb568cf2009-01-08 20:45:30 +00003296 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003297 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003298 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003299 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003300
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003301 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003302}
3303
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003304/// TranslateIvarVisibility - Translate visibility from a token ID to an
3305/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003306static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003307TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003308 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003309 default: assert(0 && "Unknown visitibility kind");
3310 case tok::objc_private: return ObjCIvarDecl::Private;
3311 case tok::objc_public: return ObjCIvarDecl::Public;
3312 case tok::objc_protected: return ObjCIvarDecl::Protected;
3313 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003314 }
3315}
3316
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003317/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3318/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003319Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003320 SourceLocation DeclStart,
3321 Declarator &D, ExprTy *BitfieldWidth,
3322 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003323
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003324 IdentifierInfo *II = D.getIdentifier();
3325 Expr *BitWidth = (Expr*)BitfieldWidth;
3326 SourceLocation Loc = DeclStart;
3327 if (II) Loc = D.getIdentifierLoc();
3328
3329 // FIXME: Unnamed fields can be handled in various different ways, for
3330 // example, unnamed unions inject all members into the struct namespace!
3331
Anders Carlsson108229a2008-12-06 20:33:04 +00003332 QualType T = GetTypeForDeclarator(D, S);
3333 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3334 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003335
3336 if (BitWidth) {
3337 // TODO: Validate.
3338 //printf("WARNING: BITFIELDS IGNORED!\n");
3339
3340 // 6.7.2.1p3
3341 // 6.7.2.1p4
3342
3343 } else {
3344 // Not a bitfield.
3345
3346 // validate II.
3347
3348 }
3349
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003350 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3351 // than a variably modified type.
3352 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003353 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003354 InvalidDecl = true;
3355 }
3356
Ted Kremenek173dd312008-07-23 18:04:17 +00003357 // Get the visibility (access control) for this ivar.
3358 ObjCIvarDecl::AccessControl ac =
3359 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3360 : ObjCIvarDecl::None;
3361
3362 // Construct the decl.
3363 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003364 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003365
Douglas Gregordb568cf2009-01-08 20:45:30 +00003366 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003367 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003368 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3369 && !isa<TagDecl>(PrevDecl)) {
3370 Diag(Loc, diag::err_duplicate_member) << II;
3371 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3372 NewID->setInvalidDecl();
3373 }
3374 }
3375
Ted Kremenek173dd312008-07-23 18:04:17 +00003376 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003377 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003378
3379 if (D.getInvalidType() || InvalidDecl)
3380 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003381
Douglas Gregordb568cf2009-01-08 20:45:30 +00003382 if (II) {
3383 // FIXME: When interfaces are DeclContexts, we'll need to add
3384 // these to the interface.
3385 S->AddDecl(NewID);
3386 IdResolver.AddDecl(NewID);
3387 }
3388
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003389 return NewID;
3390}
3391
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003392void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003393 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003394 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003395 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003396 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003397 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3398 assert(EnclosingDecl && "missing record or interface decl");
3399 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3400
Chris Lattner4b009652007-07-25 00:24:17 +00003401 // Verify that all the fields are okay.
3402 unsigned NumNamedMembers = 0;
3403 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003404
Chris Lattner4b009652007-07-25 00:24:17 +00003405 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003406 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3407 assert(FD && "missing field decl");
3408
Chris Lattner4b009652007-07-25 00:24:17 +00003409 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003410 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003411
Douglas Gregordb568cf2009-01-08 20:45:30 +00003412 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003413 // Remember all fields written by the user.
3414 RecFields.push_back(FD);
3415 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003416
Chris Lattner4b009652007-07-25 00:24:17 +00003417 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003418 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003419 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003420 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003421 FD->setInvalidDecl();
3422 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003423 continue;
3424 }
Chris Lattner4b009652007-07-25 00:24:17 +00003425 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3426 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003427 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003428 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3429 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003430 FD->setInvalidDecl();
3431 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003432 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003433 }
Chris Lattner4b009652007-07-25 00:24:17 +00003434 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003435 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003436 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003437 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3438 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003439 FD->setInvalidDecl();
3440 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003441 continue;
3442 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003443 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003444 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003445 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003446 FD->setInvalidDecl();
3447 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003448 continue;
3449 }
Chris Lattner4b009652007-07-25 00:24:17 +00003450 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003451 if (Record)
3452 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003453 }
Chris Lattner4b009652007-07-25 00:24:17 +00003454 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3455 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003456 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003457 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3458 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003459 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003460 Record->setHasFlexibleArrayMember(true);
3461 } else {
3462 // If this is a struct/class and this is not the last element, reject
3463 // it. Note that GCC supports variable sized arrays in the middle of
3464 // structures.
3465 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003466 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003467 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003468 FD->setInvalidDecl();
3469 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003470 continue;
3471 }
Chris Lattner4b009652007-07-25 00:24:17 +00003472 // We support flexible arrays at the end of structs in other structs
3473 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003474 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003475 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003476 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003477 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003478 }
3479 }
3480 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003481 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003482 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003483 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003484 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003485 FD->setInvalidDecl();
3486 EnclosingDecl->setInvalidDecl();
3487 continue;
3488 }
Chris Lattner4b009652007-07-25 00:24:17 +00003489 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003490 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003491 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003492 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003493
Chris Lattner4b009652007-07-25 00:24:17 +00003494 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003495 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003496 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003497 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003498 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003499 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003500 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003501 // Must enforce the rule that ivars in the base classes may not be
3502 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003503 if (ID->getSuperClass()) {
3504 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3505 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3506 ObjCIvarDecl* Ivar = (*IVI);
3507 IdentifierInfo *II = Ivar->getIdentifier();
3508 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3509 if (prevIvar) {
3510 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003511 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003512 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003513 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003514 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003515 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003516 else if (ObjCImplementationDecl *IMPDecl =
3517 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003518 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3519 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003520 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003521 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003522 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003523
3524 if (Attr)
3525 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003526}
3527
Steve Naroff0acc9c92007-09-15 18:49:24 +00003528Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003529 DeclTy *lastEnumConst,
3530 SourceLocation IdLoc, IdentifierInfo *Id,
3531 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003532 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003533 EnumConstantDecl *LastEnumConst =
3534 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3535 Expr *Val = static_cast<Expr*>(val);
3536
Chris Lattnera7549902007-08-26 06:24:45 +00003537 // The scope passed in may not be a decl scope. Zip up the scope tree until
3538 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003539 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003540
Chris Lattner4b009652007-07-25 00:24:17 +00003541 // Verify that there isn't already something declared with this name in this
3542 // scope.
Douglas Gregor09be81b2009-02-04 17:27:36 +00003543 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003544 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003545 // Maybe we will complain about the shadowed template parameter.
3546 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3547 // Just pretend that we didn't see the previous declaration.
3548 PrevDecl = 0;
3549 }
3550
3551 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003552 // When in C++, we may get a TagDecl with the same name; in this case the
3553 // enum constant will 'hide' the tag.
3554 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3555 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003556 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003557 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003558 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003559 else
Chris Lattner65cae292008-11-19 08:23:25 +00003560 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003561 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003562 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003563 return 0;
3564 }
3565 }
3566
3567 llvm::APSInt EnumVal(32);
3568 QualType EltTy;
3569 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003570 // Make sure to promote the operand type to int.
3571 UsualUnaryConversions(Val);
3572
Chris Lattner4b009652007-07-25 00:24:17 +00003573 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3574 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003575 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003576 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003577 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003578 } else {
3579 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003580 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003581 }
3582
3583 if (!Val) {
3584 if (LastEnumConst) {
3585 // Assign the last value + 1.
3586 EnumVal = LastEnumConst->getInitVal();
3587 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003588
3589 // Check for overflow on increment.
3590 if (EnumVal < LastEnumConst->getInitVal())
3591 Diag(IdLoc, diag::warn_enum_value_overflow);
3592
Chris Lattnere7f53a42007-08-27 17:37:24 +00003593 EltTy = LastEnumConst->getType();
3594 } else {
3595 // First value, set to zero.
3596 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003597 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003598 }
Chris Lattner4b009652007-07-25 00:24:17 +00003599 }
3600
Chris Lattnere4650482008-03-15 06:12:44 +00003601 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003602 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003603 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003604
3605 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003606 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003607
Chris Lattner4b009652007-07-25 00:24:17 +00003608 return New;
3609}
3610
Steve Naroffb0726b82008-08-07 14:08:16 +00003611// FIXME: For consistency with ActOnFields(), we should have the parser
3612// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003613void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003614 DeclTy **Elements, unsigned NumElements) {
3615 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003616 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003617
Chris Lattner435c3fd2007-08-28 05:10:31 +00003618 // TODO: If the result value doesn't fit in an int, it must be a long or long
3619 // long value. ISO C does not support this, but GCC does as an extension,
3620 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003621 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003622
Chris Lattner206754a2007-08-28 06:15:15 +00003623 // Verify that all the values are okay, compute the size of the values, and
3624 // reverse the list.
3625 unsigned NumNegativeBits = 0;
3626 unsigned NumPositiveBits = 0;
3627
3628 // Keep track of whether all elements have type int.
3629 bool AllElementsInt = true;
3630
Chris Lattner4b009652007-07-25 00:24:17 +00003631 for (unsigned i = 0; i != NumElements; ++i) {
3632 EnumConstantDecl *ECD =
3633 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3634 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003635
3636 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003637 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003638 assert(InitVal.getBitWidth() >= IntWidth &&
3639 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003640 if (InitVal.getBitWidth() > IntWidth) {
3641 llvm::APSInt V(InitVal);
3642 V.trunc(IntWidth);
3643 V.extend(InitVal.getBitWidth());
3644 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003645 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3646 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003647 }
Chris Lattner206754a2007-08-28 06:15:15 +00003648
3649 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003650 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003651 NumPositiveBits = std::max(NumPositiveBits,
3652 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003653 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003654 NumNegativeBits = std::max(NumNegativeBits,
3655 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003656
Chris Lattner206754a2007-08-28 06:15:15 +00003657 // Keep track of whether every enum element has type int (very commmon).
3658 if (AllElementsInt)
3659 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003660 }
3661
Chris Lattner206754a2007-08-28 06:15:15 +00003662 // Figure out the type that should be used for this enum.
3663 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3664 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003665 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003666
3667 if (NumNegativeBits) {
3668 // If there is a negative value, figure out the smallest integer type (of
3669 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003670 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003671 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003672 BestWidth = IntWidth;
3673 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003674 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003675
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003676 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003677 BestType = Context.LongTy;
3678 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003679 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003680
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003681 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003682 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3683 BestType = Context.LongLongTy;
3684 }
3685 }
3686 } else {
3687 // If there is no negative value, figure out which of uint, ulong, ulonglong
3688 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003689 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003690 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003691 BestWidth = IntWidth;
3692 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003693 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003694 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003695 } else {
3696 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003697 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003698 "How could an initializer get larger than ULL?");
3699 BestType = Context.UnsignedLongLongTy;
3700 }
3701 }
3702
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003703 // Loop over all of the enumerator constants, changing their types to match
3704 // the type of the enum if needed.
3705 for (unsigned i = 0; i != NumElements; ++i) {
3706 EnumConstantDecl *ECD =
3707 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3708 if (!ECD) continue; // Already issued a diagnostic.
3709
3710 // Standard C says the enumerators have int type, but we allow, as an
3711 // extension, the enumerators to be larger than int size. If each
3712 // enumerator value fits in an int, type it as an int, otherwise type it the
3713 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3714 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003715 if (ECD->getType() == Context.IntTy) {
3716 // Make sure the init value is signed.
3717 llvm::APSInt IV = ECD->getInitVal();
3718 IV.setIsSigned(true);
3719 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003720
3721 if (getLangOptions().CPlusPlus)
3722 // C++ [dcl.enum]p4: Following the closing brace of an
3723 // enum-specifier, each enumerator has the type of its
3724 // enumeration.
3725 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003726 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003727 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003728
3729 // Determine whether the value fits into an int.
3730 llvm::APSInt InitVal = ECD->getInitVal();
3731 bool FitsInInt;
3732 if (InitVal.isUnsigned() || !InitVal.isNegative())
3733 FitsInInt = InitVal.getActiveBits() < IntWidth;
3734 else
3735 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3736
3737 // If it fits into an integer type, force it. Otherwise force it to match
3738 // the enum decl type.
3739 QualType NewTy;
3740 unsigned NewWidth;
3741 bool NewSign;
3742 if (FitsInInt) {
3743 NewTy = Context.IntTy;
3744 NewWidth = IntWidth;
3745 NewSign = true;
3746 } else if (ECD->getType() == BestType) {
3747 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003748 if (getLangOptions().CPlusPlus)
3749 // C++ [dcl.enum]p4: Following the closing brace of an
3750 // enum-specifier, each enumerator has the type of its
3751 // enumeration.
3752 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003753 continue;
3754 } else {
3755 NewTy = BestType;
3756 NewWidth = BestWidth;
3757 NewSign = BestType->isSignedIntegerType();
3758 }
3759
3760 // Adjust the APSInt value.
3761 InitVal.extOrTrunc(NewWidth);
3762 InitVal.setIsSigned(NewSign);
3763 ECD->setInitVal(InitVal);
3764
3765 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003766 if (ECD->getInitExpr())
3767 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3768 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003769 if (getLangOptions().CPlusPlus)
3770 // C++ [dcl.enum]p4: Following the closing brace of an
3771 // enum-specifier, each enumerator has the type of its
3772 // enumeration.
3773 ECD->setType(EnumType);
3774 else
3775 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003776 }
Chris Lattner206754a2007-08-28 06:15:15 +00003777
Douglas Gregor8acb7272008-12-11 16:49:14 +00003778 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003779}
3780
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003781Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003782 ExprArg expr) {
3783 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3784
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003785 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003786}
3787
Douglas Gregorad17e372008-12-16 22:23:02 +00003788
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003789void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3790 ExprTy *alignment, SourceLocation PragmaLoc,
3791 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3792 Expr *Alignment = static_cast<Expr *>(alignment);
3793
3794 // If specified then alignment must be a "small" power of two.
3795 unsigned AlignmentVal = 0;
3796 if (Alignment) {
3797 llvm::APSInt Val;
3798 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3799 !Val.isPowerOf2() ||
3800 Val.getZExtValue() > 16) {
3801 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3802 delete Alignment;
3803 return; // Ignore
3804 }
3805
3806 AlignmentVal = (unsigned) Val.getZExtValue();
3807 }
3808
3809 switch (Kind) {
3810 case Action::PPK_Default: // pack([n])
3811 PackContext.setAlignment(AlignmentVal);
3812 break;
3813
3814 case Action::PPK_Show: // pack(show)
3815 // Show the current alignment, making sure to show the right value
3816 // for the default.
3817 AlignmentVal = PackContext.getAlignment();
3818 // FIXME: This should come from the target.
3819 if (AlignmentVal == 0)
3820 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003821 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003822 break;
3823
3824 case Action::PPK_Push: // pack(push [, id] [, [n])
3825 PackContext.push(Name);
3826 // Set the new alignment if specified.
3827 if (Alignment)
3828 PackContext.setAlignment(AlignmentVal);
3829 break;
3830
3831 case Action::PPK_Pop: // pack(pop [, id] [, n])
3832 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3833 // "#pragma pack(pop, identifier, n) is undefined"
3834 if (Alignment && Name)
3835 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3836
3837 // Do the pop.
3838 if (!PackContext.pop(Name)) {
3839 // If a name was specified then failure indicates the name
3840 // wasn't found. Otherwise failure indicates the stack was
3841 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003842 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3843 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003844
3845 // FIXME: Warn about popping named records as MSVC does.
3846 } else {
3847 // Pop succeeded, set the new alignment if specified.
3848 if (Alignment)
3849 PackContext.setAlignment(AlignmentVal);
3850 }
3851 break;
3852
3853 default:
3854 assert(0 && "Invalid #pragma pack kind.");
3855 }
3856}
3857
3858bool PragmaPackStack::pop(IdentifierInfo *Name) {
3859 if (Stack.empty())
3860 return false;
3861
3862 // If name is empty just pop top.
3863 if (!Name) {
3864 Alignment = Stack.back().first;
3865 Stack.pop_back();
3866 return true;
3867 }
3868
3869 // Otherwise, find the named record.
3870 for (unsigned i = Stack.size(); i != 0; ) {
3871 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003872 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003873 // Found it, pop up to and including this record.
3874 Alignment = Stack[i].first;
3875 Stack.erase(Stack.begin() + i, Stack.end());
3876 return true;
3877 }
3878 }
3879
3880 return false;
3881}