blob: 3395313f84cd82d7ef50c6e783eb6c8af1a8946e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000022#include "clang/Basic/SourceManager.h"
23// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000024#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000025#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000027#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000028#include <algorithm>
29#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000030
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32
Steve Naroff7b36a1b2009-01-28 19:39:02 +000033Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S,
34 const CXXScopeSpec *SS) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000035 Decl *IIDecl = 0;
Douglas Gregor52ae30c2009-01-30 01:04:22 +000036 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000037 switch (Result.getKind()) {
Steve Naroffa4e04982009-01-29 18:09:31 +000038 case LookupResult::NotFound:
39 case LookupResult::FoundOverloaded:
40 case LookupResult::AmbiguousBaseSubobjectTypes:
41 case LookupResult::AmbiguousBaseSubobjects:
42 // FIXME: In the event of an ambiguous lookup, we could visit all of
43 // the entities found to determine whether they are all types. This
44 // might provide better diagnostics.
45 return 0;
46 case LookupResult::Found:
47 IIDecl = Result.getAsDecl();
48 break;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000049 }
50
Steve Naroffa4e04982009-01-29 18:09:31 +000051 if (IIDecl) {
52 if (isa<TypedefDecl>(IIDecl) ||
53 isa<ObjCInterfaceDecl>(IIDecl) ||
54 isa<TagDecl>(IIDecl) ||
55 isa<TemplateTypeParmDecl>(IIDecl))
56 return IIDecl;
57 }
Steve Naroff81f1bba2007-09-06 21:24:23 +000058 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000059}
60
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000061DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000063 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000064 if (MD->isOutOfLineDefinition())
65 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000066
67 // A C++ inline method is parsed *after* the topmost class it was declared in
68 // is fully parsed (it's "complete").
69 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000070 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000071 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
72 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000073 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000074 DC = RD;
75
76 // Return the declaration context of the topmost class the inline method is
77 // declared in.
78 return DC;
79 }
80
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000081 if (isa<ObjCMethodDecl>(DC))
82 return Context.getTranslationUnitDecl();
83
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000084 if (Decl *D = dyn_cast<Decl>(DC))
85 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000086
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000087 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000088}
89
Douglas Gregor8acb7272008-12-11 16:49:14 +000090void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000091 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000092 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000093 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000094 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000095}
96
Chris Lattnerf3874bc2008-04-06 04:47:34 +000097void Sema::PopDeclContext() {
98 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000099
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000100 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000101}
102
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000103/// Add this decl to the scope shadowed decl chains.
104void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000105 // Move up the scope chain until we find the nearest enclosing
106 // non-transparent context. The declaration will be introduced into this
107 // scope.
108 while (S->getEntity() &&
109 ((DeclContext *)S->getEntity())->isTransparentContext())
110 S = S->getParent();
111
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000112 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000113
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000114 // Add scoped declarations into their context, so that they can be
115 // found later. Declarations without a context won't be inserted
116 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000117 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000118
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000119 // C++ [basic.scope]p4:
120 // -- exactly one declaration shall declare a class name or
121 // enumeration name that is not a typedef name and the other
122 // declarations shall all refer to the same object or
123 // enumerator, or all refer to functions and function templates;
124 // in this case the class name or enumeration name is hidden.
125 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
126 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000127 if (CurContext->getLookupContext()
128 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000129 // We're pushing the tag into the current context, which might
130 // require some reshuffling in the identifier resolver.
131 IdentifierResolver::iterator
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000132 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000133 IEnd = IdResolver.end();
134 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
135 NamedDecl *PrevDecl = *I;
136 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
137 PrevDecl = *I, ++I) {
138 if (TD->declarationReplaces(*I)) {
139 // This is a redeclaration. Remove it from the chain and
140 // break out, so that we'll add in the shadowed
141 // declaration.
142 S->RemoveDecl(*I);
143 if (PrevDecl == *I) {
144 IdResolver.RemoveDecl(*I);
145 IdResolver.AddDecl(TD);
146 return;
147 } else {
148 IdResolver.RemoveDecl(*I);
149 break;
150 }
151 }
152 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000153
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000154 // There is already a declaration with the same name in the same
155 // scope, which is not a tag declaration. It must be found
156 // before we find the new declaration, so insert the new
157 // declaration at the end of the chain.
158 IdResolver.AddShadowedDecl(TD, PrevDecl);
159
160 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000161 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000162 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000163 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000164 // We are pushing the name of a function, which might be an
165 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000166 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000167 IdentifierResolver::iterator Redecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000168 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000169 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000170 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000171 FD));
172 if (Redecl != IdResolver.end()) {
173 // There is already a declaration of a function on our
174 // IdResolver chain. Replace it with this declaration.
175 S->RemoveDecl(*Redecl);
176 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000177 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000178 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000179
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000180 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000181}
182
Steve Naroff9637a9b2007-10-09 22:01:59 +0000183void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000184 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000185 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
186 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000187
Chris Lattner4b009652007-07-25 00:24:17 +0000188 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
189 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000190 Decl *TmpD = static_cast<Decl*>(*I);
191 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000192
Douglas Gregor8acb7272008-12-11 16:49:14 +0000193 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
194 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000195
Douglas Gregor8acb7272008-12-11 16:49:14 +0000196 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000197
Douglas Gregor8acb7272008-12-11 16:49:14 +0000198 // Remove this name from our lexical scope.
199 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000200 }
201}
202
Steve Naroffe57c21a2008-04-01 23:04:06 +0000203/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
204/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000205ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000206 // The third "scope" argument is 0 since we aren't enabling lazy built-in
207 // creation from this context.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000208 Decl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000209
Steve Naroff6384a012008-04-02 14:35:35 +0000210 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000211}
212
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000213/// getNonFieldDeclScope - Retrieves the innermost scope, starting
214/// from S, where a non-field would be declared. This routine copes
215/// with the difference between C and C++ scoping rules in structs and
216/// unions. For example, the following code is well-formed in C but
217/// ill-formed in C++:
218/// @code
219/// struct S6 {
220/// enum { BAR } e;
221/// };
222///
223/// void test_S6() {
224/// struct S6 a;
225/// a.e = BAR;
226/// }
227/// @endcode
228/// For the declaration of BAR, this routine will return a different
229/// scope. The scope S will be the scope of the unnamed enumeration
230/// within S6. In C++, this routine will return the scope associated
231/// with S6, because the enumeration's scope is a transparent
232/// context but structures can contain non-field names. In C, this
233/// routine will return the translation unit scope, since the
234/// enumeration's scope is a transparent context and structures cannot
235/// contain non-field names.
236Scope *Sema::getNonFieldDeclScope(Scope *S) {
237 while (((S->getFlags() & Scope::DeclScope) == 0) ||
238 (S->getEntity() &&
239 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
240 (S->isClassScope() && !getLangOptions().CPlusPlus))
241 S = S->getParent();
242 return S;
243}
244
Chris Lattnera9c87f22008-05-05 22:18:14 +0000245void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000246 if (!Context.getBuiltinVaListType().isNull())
247 return;
248
249 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000250 Decl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000251 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000252 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
253}
254
Chris Lattner4b009652007-07-25 00:24:17 +0000255/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
256/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000257NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
258 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000259 Builtin::ID BID = (Builtin::ID)bid;
260
Chris Lattnerb23469f2008-09-28 05:54:29 +0000261 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000262 InitBuiltinVaListType();
263
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000264 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000265 FunctionDecl *New = FunctionDecl::Create(Context,
266 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000267 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000268 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000269
Chris Lattnera9c87f22008-05-05 22:18:14 +0000270 // Create Decl objects for each parameter, adding them to the
271 // FunctionDecl.
272 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
273 llvm::SmallVector<ParmVarDecl*, 16> Params;
274 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
275 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000276 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000277 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000278 }
279
280
281
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000282 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000283 // FIXME: This is hideous. We need to teach PushOnScopeChains to
284 // relate Scopes to DeclContexts, and probably eliminate CurContext
285 // entirely, but we're not there yet.
286 DeclContext *SavedContext = CurContext;
287 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000288 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000289 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000290 return New;
291}
292
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000293/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
294/// everything from the standard library is defined.
295NamespaceDecl *Sema::GetStdNamespace() {
296 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000297 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000298 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000299 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000300 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
301 }
302 return StdNamespace;
303}
304
Chris Lattner4b009652007-07-25 00:24:17 +0000305/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
306/// and scope as a previous declaration 'Old'. Figure out how to resolve this
307/// situation, merging decls or emitting diagnostics as appropriate.
308///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000309TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000310 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000311 // Allow multiple definitions for ObjC built-in typedefs.
312 // FIXME: Verify the underlying types are equivalent!
313 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000314 const IdentifierInfo *TypeID = New->getIdentifier();
315 switch (TypeID->getLength()) {
316 default: break;
317 case 2:
318 if (!TypeID->isStr("id"))
319 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000320 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000321 objc_types = true;
322 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000323 case 5:
324 if (!TypeID->isStr("Class"))
325 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000326 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000327 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000328 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000329 case 3:
330 if (!TypeID->isStr("SEL"))
331 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000332 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000333 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000334 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000335 case 8:
336 if (!TypeID->isStr("Protocol"))
337 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000338 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000339 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000340 return New;
341 }
342 // Fall through - the typedef name was not a builtin type.
343 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000344 // Verify the old decl was also a type.
345 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000346 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000347 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000348 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000349 if (!objc_types)
350 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000351 return New;
352 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000353
354 // Determine the "old" type we'll use for checking and diagnostics.
355 QualType OldType;
356 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
357 OldType = OldTypedef->getUnderlyingType();
358 else
359 OldType = Context.getTypeDeclType(Old);
360
Chris Lattnerbef8d622008-07-25 18:44:27 +0000361 // If the typedef types are not identical, reject them in all languages and
362 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000363
364 if (OldType != New->getUnderlyingType() &&
365 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000366 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000367 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000368 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000369 if (!objc_types)
370 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000371 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000372 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000373 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000374 if (getLangOptions().Microsoft) return New;
375
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000376 // C++ [dcl.typedef]p2:
377 // In a given non-class scope, a typedef specifier can be used to
378 // redefine the name of any type declared in that scope to refer
379 // to the type to which it already refers.
380 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
381 return New;
382
383 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000384 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
385 // *either* declaration is in a system header. The code below implements
386 // this adhoc compatibility rule. FIXME: The following code will not
387 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000388 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
389 SourceManager &SrcMgr = Context.getSourceManager();
390 if (SrcMgr.isInSystemHeader(Old->getLocation()))
391 return New;
392 if (SrcMgr.isInSystemHeader(New->getLocation()))
393 return New;
394 }
Eli Friedman324d5032008-06-11 06:20:39 +0000395
Chris Lattnerb1753422008-11-23 21:45:46 +0000396 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000397 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000398 return New;
399}
400
Chris Lattner6953a072008-06-26 18:38:35 +0000401/// DeclhasAttr - returns true if decl Declaration already has the target
402/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000403static bool DeclHasAttr(const Decl *decl, const Attr *target) {
404 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
405 if (attr->getKind() == target->getKind())
406 return true;
407
408 return false;
409}
410
411/// MergeAttributes - append attributes from the Old decl to the New one.
412static void MergeAttributes(Decl *New, Decl *Old) {
413 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
414
Chris Lattner402b3372008-03-03 03:28:21 +0000415 while (attr) {
416 tmp = attr;
417 attr = attr->getNext();
418
419 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000420 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000421 New->addAttr(tmp);
422 } else {
423 tmp->setNext(0);
424 delete(tmp);
425 }
426 }
Nuno Lopes77654342008-06-01 22:53:53 +0000427
428 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000429}
430
Chris Lattner3e254fb2008-04-08 04:40:51 +0000431/// MergeFunctionDecl - We just parsed a function 'New' from
432/// declarator D which has the same name and scope as a previous
433/// declaration 'Old'. Figure out how to resolve this situation,
434/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000435/// Redeclaration will be set true if this New is a redeclaration OldD.
436///
437/// In C++, New and Old must be declarations that are not
438/// overloaded. Use IsOverload to determine whether New and Old are
439/// overloaded, and to select the Old declaration that New should be
440/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000441FunctionDecl *
442Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000443 assert(!isa<OverloadedFunctionDecl>(OldD) &&
444 "Cannot merge with an overloaded function declaration");
445
Douglas Gregor42214c52008-04-21 02:02:58 +0000446 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000447 // Verify the old decl was also a function.
448 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
449 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000450 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000451 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000452 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000453 return New;
454 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000455
456 // Determine whether the previous declaration was a definition,
457 // implicit declaration, or a declaration.
458 diag::kind PrevDiag;
459 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000460 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000461 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000462 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000463 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000464 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000465
Chris Lattner42a21742008-04-06 23:10:54 +0000466 QualType OldQType = Context.getCanonicalType(Old->getType());
467 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000468
Douglas Gregord2baafd2008-10-21 16:13:35 +0000469 if (getLangOptions().CPlusPlus) {
470 // (C++98 13.1p2):
471 // Certain function declarations cannot be overloaded:
472 // -- Function declarations that differ only in the return type
473 // cannot be overloaded.
474 QualType OldReturnType
475 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
476 QualType NewReturnType
477 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
478 if (OldReturnType != NewReturnType) {
479 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
480 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000481 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000482 return New;
483 }
484
485 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
486 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
487 if (OldMethod && NewMethod) {
488 // -- Member function declarations with the same name and the
489 // same parameter types cannot be overloaded if any of them
490 // is a static member function declaration.
491 if (OldMethod->isStatic() || NewMethod->isStatic()) {
492 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
493 Diag(Old->getLocation(), PrevDiag);
494 return New;
495 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000496
497 // C++ [class.mem]p1:
498 // [...] A member shall not be declared twice in the
499 // member-specification, except that a nested class or member
500 // class template can be declared and then later defined.
501 if (OldMethod->getLexicalDeclContext() ==
502 NewMethod->getLexicalDeclContext()) {
503 unsigned NewDiag;
504 if (isa<CXXConstructorDecl>(OldMethod))
505 NewDiag = diag::err_constructor_redeclared;
506 else if (isa<CXXDestructorDecl>(NewMethod))
507 NewDiag = diag::err_destructor_redeclared;
508 else if (isa<CXXConversionDecl>(NewMethod))
509 NewDiag = diag::err_conv_function_redeclared;
510 else
511 NewDiag = diag::err_member_redeclared;
512
513 Diag(New->getLocation(), NewDiag);
514 Diag(Old->getLocation(), PrevDiag);
515 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516 }
517
518 // (C++98 8.3.5p3):
519 // All declarations for a function shall agree exactly in both the
520 // return type and the parameter-type-list.
521 if (OldQType == NewQType) {
522 // We have a redeclaration.
523 MergeAttributes(New, Old);
524 Redeclaration = true;
525 return MergeCXXFunctionDecl(New, Old);
526 }
527
528 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000529 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000530
531 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000532 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000533 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000534 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000535 MergeAttributes(New, Old);
536 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000537 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000538 }
Chris Lattner1470b072007-11-06 06:07:26 +0000539
Steve Naroff6c9e7922008-01-16 15:01:34 +0000540 // A function that has already been declared has been redeclared or defined
541 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000542
Chris Lattner4b009652007-07-25 00:24:17 +0000543 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
544 // TODO: This is totally simplistic. It should handle merging functions
545 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000546 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000547 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000548 return New;
549}
550
Steve Naroffb5e78152008-08-08 17:50:35 +0000551/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000552static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000553 if (VD->isFileVarDecl())
554 return (!VD->getInit() &&
555 (VD->getStorageClass() == VarDecl::None ||
556 VD->getStorageClass() == VarDecl::Static));
557 return false;
558}
559
560/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
561/// when dealing with C "tentative" external object definitions (C99 6.9.2).
562void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
563 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000564 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000565
Douglas Gregor3a423132009-01-07 16:34:42 +0000566 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000567 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000568 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
569 E = IdResolver.end();
570 I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000571 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000572 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
573
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000574 // Handle the following case:
575 // int a[10];
576 // int a[]; - the code below makes sure we set the correct type.
577 // int a[11]; - this is an error, size isn't 10.
578 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
579 OldDecl->getType()->isConstantArrayType())
580 VD->setType(OldDecl->getType());
581
Steve Naroffb5e78152008-08-08 17:50:35 +0000582 // Check for "tentative" definitions. We can't accomplish this in
583 // MergeVarDecl since the initializer hasn't been attached.
584 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
585 continue;
586
587 // Handle __private_extern__ just like extern.
588 if (OldDecl->getStorageClass() != VarDecl::Extern &&
589 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
590 VD->getStorageClass() != VarDecl::Extern &&
591 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000592 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000593 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000594 }
595 }
596 }
597}
598
Chris Lattner4b009652007-07-25 00:24:17 +0000599/// MergeVarDecl - We just parsed a variable 'New' which has the same name
600/// and scope as a previous declaration 'Old'. Figure out how to resolve this
601/// situation, merging decls or emitting diagnostics as appropriate.
602///
Steve Naroffb5e78152008-08-08 17:50:35 +0000603/// Tentative definition rules (C99 6.9.2p2) are checked by
604/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
605/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000606///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000607VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000608 // Verify the old decl was also a variable.
609 VarDecl *Old = dyn_cast<VarDecl>(OldD);
610 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000611 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000612 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000613 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000614 return New;
615 }
Chris Lattner402b3372008-03-03 03:28:21 +0000616
617 MergeAttributes(New, Old);
618
Eli Friedman4a480d62009-01-24 23:49:55 +0000619 // Merge the types
620 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
621 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000622 Diag(New->getLocation(), diag::err_redefinition_different_type)
623 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000624 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000625 return New;
626 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000627 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000628 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
629 if (New->getStorageClass() == VarDecl::Static &&
630 (Old->getStorageClass() == VarDecl::None ||
631 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000632 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000633 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000634 return New;
635 }
636 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
637 if (New->getStorageClass() != VarDecl::Static &&
638 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000639 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000640 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000641 return New;
642 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000643 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
644 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000645 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000646 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000647 }
648 return New;
649}
650
Chris Lattner3e254fb2008-04-08 04:40:51 +0000651/// CheckParmsForFunctionDef - Check that the parameters of the given
652/// function are appropriate for the definition of a function. This
653/// takes care of any checks that cannot be performed on the
654/// declaration itself, e.g., that the types of each of the function
655/// parameters are complete.
656bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
657 bool HasInvalidParm = false;
658 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
659 ParmVarDecl *Param = FD->getParamDecl(p);
660
661 // C99 6.7.5.3p4: the parameters in a parameter type list in a
662 // function declarator that is part of a function definition of
663 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000664 if (!Param->isInvalidDecl() &&
665 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
666 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000667 Param->setInvalidDecl();
668 HasInvalidParm = true;
669 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000670
671 // C99 6.9.1p5: If the declarator includes a parameter type list, the
672 // declaration of each parameter shall include an identifier.
673 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
674 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000675 }
676
677 return HasInvalidParm;
678}
679
Chris Lattner4b009652007-07-25 00:24:17 +0000680/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
681/// no declarator (e.g. "struct foo;") is parsed.
682Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000683 TagDecl *Tag
684 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
685 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
686 if (!Record->getDeclName() && Record->isDefinition() &&
687 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
688 return BuildAnonymousStructOrUnion(S, DS, Record);
689
690 // Microsoft allows unnamed struct/union fields. Don't complain
691 // about them.
692 // FIXME: Should we support Microsoft's extensions in this area?
693 if (Record->getDeclName() && getLangOptions().Microsoft)
694 return Tag;
695 }
696
Sebastian Redlb7605e82008-12-28 15:28:59 +0000697 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000698 // Warn about typedefs of enums without names, since this is an
699 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000700 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
701 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000702 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000703 << DS.getSourceRange();
704 return Tag;
705 }
706
Sebastian Redlb7605e82008-12-28 15:28:59 +0000707 // FIXME: This diagnostic is emitted even when various previous
708 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
709 // DeclSpec has no means of communicating this information, and the
710 // responsible parser functions are quite far apart.
711 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
712 << DS.getSourceRange();
713 return 0;
714 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000715
Douglas Gregor723d3332009-01-07 00:43:41 +0000716 return Tag;
717}
718
719/// InjectAnonymousStructOrUnionMembers - Inject the members of the
720/// anonymous struct or union AnonRecord into the owning context Owner
721/// and scope S. This routine will be invoked just after we realize
722/// that an unnamed union or struct is actually an anonymous union or
723/// struct, e.g.,
724///
725/// @code
726/// union {
727/// int i;
728/// float f;
729/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
730/// // f into the surrounding scope.x
731/// @endcode
732///
733/// This routine is recursive, injecting the names of nested anonymous
734/// structs/unions into the owning context and scope as well.
735bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
736 RecordDecl *AnonRecord) {
737 bool Invalid = false;
738 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
739 FEnd = AnonRecord->field_end();
740 F != FEnd; ++F) {
741 if ((*F)->getDeclName()) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000742 Decl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
743 LookupOrdinaryName, true);
Douglas Gregor723d3332009-01-07 00:43:41 +0000744 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
745 // C++ [class.union]p2:
746 // The names of the members of an anonymous union shall be
747 // distinct from the names of any other entity in the
748 // scope in which the anonymous union is declared.
749 unsigned diagKind
750 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
751 : diag::err_anonymous_struct_member_redecl;
752 Diag((*F)->getLocation(), diagKind)
753 << (*F)->getDeclName();
754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
755 Invalid = true;
756 } else {
757 // C++ [class.union]p2:
758 // For the purpose of name lookup, after the anonymous union
759 // definition, the members of the anonymous union are
760 // considered to have been defined in the scope in which the
761 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000762 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000763 S->AddDecl(*F);
764 IdResolver.AddDecl(*F);
765 }
766 } else if (const RecordType *InnerRecordType
767 = (*F)->getType()->getAsRecordType()) {
768 RecordDecl *InnerRecord = InnerRecordType->getDecl();
769 if (InnerRecord->isAnonymousStructOrUnion())
770 Invalid = Invalid ||
771 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
772 }
773 }
774
775 return Invalid;
776}
777
778/// ActOnAnonymousStructOrUnion - Handle the declaration of an
779/// anonymous structure or union. Anonymous unions are a C++ feature
780/// (C++ [class.union]) and a GNU C extension; anonymous structures
781/// are a GNU C and GNU C++ extension.
782Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
783 RecordDecl *Record) {
784 DeclContext *Owner = Record->getDeclContext();
785
786 // Diagnose whether this anonymous struct/union is an extension.
787 if (Record->isUnion() && !getLangOptions().CPlusPlus)
788 Diag(Record->getLocation(), diag::ext_anonymous_union);
789 else if (!Record->isUnion())
790 Diag(Record->getLocation(), diag::ext_anonymous_struct);
791
792 // C and C++ require different kinds of checks for anonymous
793 // structs/unions.
794 bool Invalid = false;
795 if (getLangOptions().CPlusPlus) {
796 const char* PrevSpec = 0;
797 // C++ [class.union]p3:
798 // Anonymous unions declared in a named namespace or in the
799 // global namespace shall be declared static.
800 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
801 (isa<TranslationUnitDecl>(Owner) ||
802 (isa<NamespaceDecl>(Owner) &&
803 cast<NamespaceDecl>(Owner)->getDeclName()))) {
804 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
805 Invalid = true;
806
807 // Recover by adding 'static'.
808 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
809 }
810 // C++ [class.union]p3:
811 // A storage class is not allowed in a declaration of an
812 // anonymous union in a class scope.
813 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
814 isa<RecordDecl>(Owner)) {
815 Diag(DS.getStorageClassSpecLoc(),
816 diag::err_anonymous_union_with_storage_spec);
817 Invalid = true;
818
819 // Recover by removing the storage specifier.
820 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
821 PrevSpec);
822 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000823
824 // C++ [class.union]p2:
825 // The member-specification of an anonymous union shall only
826 // define non-static data members. [Note: nested types and
827 // functions cannot be declared within an anonymous union. ]
828 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
829 MemEnd = Record->decls_end();
830 Mem != MemEnd; ++Mem) {
831 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
832 // C++ [class.union]p3:
833 // An anonymous union shall not have private or protected
834 // members (clause 11).
835 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
836 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
837 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
838 Invalid = true;
839 }
840 } else if ((*Mem)->isImplicit()) {
841 // Any implicit members are fine.
842 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
843 if (!MemRecord->isAnonymousStructOrUnion() &&
844 MemRecord->getDeclName()) {
845 // This is a nested type declaration.
846 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
847 << (int)Record->isUnion();
848 Invalid = true;
849 }
850 } else {
851 // We have something that isn't a non-static data
852 // member. Complain about it.
853 unsigned DK = diag::err_anonymous_record_bad_member;
854 if (isa<TypeDecl>(*Mem))
855 DK = diag::err_anonymous_record_with_type;
856 else if (isa<FunctionDecl>(*Mem))
857 DK = diag::err_anonymous_record_with_function;
858 else if (isa<VarDecl>(*Mem))
859 DK = diag::err_anonymous_record_with_static;
860 Diag((*Mem)->getLocation(), DK)
861 << (int)Record->isUnion();
862 Invalid = true;
863 }
864 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000865 } else {
866 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000867 if (Record->isUnion() && !Owner->isRecord()) {
868 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
869 << (int)getLangOptions().CPlusPlus;
870 Invalid = true;
871 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000872 }
873
874 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000875 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
876 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000877 Invalid = true;
878 }
879
880 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000881 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +0000882 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
883 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
884 /*IdentifierInfo=*/0,
885 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000886 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000887 Anon->setAccess(AS_public);
888 if (getLangOptions().CPlusPlus)
889 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000890 } else {
891 VarDecl::StorageClass SC;
892 switch (DS.getStorageClassSpec()) {
893 default: assert(0 && "Unknown storage class!");
894 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
895 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
896 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
897 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
898 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
899 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
900 case DeclSpec::SCS_mutable:
901 // mutable can only appear on non-static class members, so it's always
902 // an error here
903 Diag(Record->getLocation(), diag::err_mutable_nonmember);
904 Invalid = true;
905 SC = VarDecl::None;
906 break;
907 }
908
909 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
910 /*IdentifierInfo=*/0,
911 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000912 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +0000913 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000914 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000915
916 // Add the anonymous struct/union object to the current
917 // context. We'll be referencing this object when we refer to one of
918 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000919 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000920
921 // Inject the members of the anonymous struct/union into the owning
922 // context and into the identifier resolver chain for name lookup
923 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000924 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
925 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000926
927 // Mark this as an anonymous struct/union type. Note that we do not
928 // do this until after we have already checked and injected the
929 // members of this anonymous struct/union type, because otherwise
930 // the members could be injected twice: once by DeclContext when it
931 // builds its lookup table, and once by
932 // InjectAnonymousStructOrUnionMembers.
933 Record->setAnonymousStructOrUnion(true);
934
935 if (Invalid)
936 Anon->setInvalidDecl();
937
938 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000939}
940
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000941bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
942 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000943 // Get the type before calling CheckSingleAssignmentConstraints(), since
944 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000945 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000946
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000947 if (getLangOptions().CPlusPlus) {
948 // FIXME: I dislike this error message. A lot.
949 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
950 return Diag(Init->getSourceRange().getBegin(),
951 diag::err_typecheck_convert_incompatible)
952 << DeclType << Init->getType() << "initializing"
953 << Init->getSourceRange();
954
955 return false;
956 }
Douglas Gregor6fd35572008-12-19 17:40:08 +0000957
Chris Lattner005ed752008-01-04 18:04:52 +0000958 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
959 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
960 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000961}
962
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000963bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000964 const ArrayType *AT = Context.getAsArrayType(DeclT);
965
966 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000967 // C99 6.7.8p14. We have an array of character type with unknown size
968 // being initialized to a string literal.
969 llvm::APSInt ConstVal(32);
970 ConstVal = strLiteral->getByteLength() + 1;
971 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000972 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000973 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000974 } else {
975 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000976 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000977 // FIXME: Avoid truncation for 64-bit length strings.
978 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000979 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000980 diag::warn_initializer_string_for_char_array_too_long)
981 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000982 }
983 // Set type from "char *" to "constant array of char".
984 strLiteral->setType(DeclT);
985 // For now, we always return false (meaning success).
986 return false;
987}
988
989StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000990 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000991 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +0000992 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +0000993 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000994 return 0;
995}
996
Douglas Gregor6428e762008-11-05 15:29:30 +0000997bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
998 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000999 DeclarationName InitEntity,
1000 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001001 if (DeclType->isDependentType() || Init->isTypeDependent())
1002 return false;
1003
Douglas Gregor81c29152008-10-29 00:13:59 +00001004 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001005 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001006 // (8.3.2), shall be initialized by an object, or function, of
1007 // type T or by an object that can be converted into a T.
1008 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001009 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001010
Steve Naroff8e9337f2008-01-21 23:53:58 +00001011 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1012 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001013 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001014 return Diag(InitLoc, diag::err_variable_object_no_init)
1015 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001016
Steve Naroffcb69fb72007-12-10 22:44:33 +00001017 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1018 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001019 // FIXME: Handle wide strings
1020 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1021 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001022
Douglas Gregor6428e762008-11-05 15:29:30 +00001023 // C++ [dcl.init]p14:
1024 // -- If the destination type is a (possibly cv-qualified) class
1025 // type:
1026 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1027 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1028 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1029
1030 // -- If the initialization is direct-initialization, or if it is
1031 // copy-initialization where the cv-unqualified version of the
1032 // source type is the same class as, or a derived class of, the
1033 // class of the destination, constructors are considered.
1034 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1035 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1036 CXXConstructorDecl *Constructor
1037 = PerformInitializationByConstructor(DeclType, &Init, 1,
1038 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001039 InitEntity,
1040 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001041 return Constructor == 0;
1042 }
1043
1044 // -- Otherwise (i.e., for the remaining copy-initialization
1045 // cases), user-defined conversion sequences that can
1046 // convert from the source type to the destination type or
1047 // (when a conversion function is used) to a derived class
1048 // thereof are enumerated as described in 13.3.1.4, and the
1049 // best one is chosen through overload resolution
1050 // (13.3). If the conversion cannot be done or is
1051 // ambiguous, the initialization is ill-formed. The
1052 // function selected is called with the initializer
1053 // expression as its argument; if the function is a
1054 // constructor, the call initializes a temporary of the
1055 // destination type.
1056 // FIXME: We're pretending to do copy elision here; return to
1057 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001058 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001059 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001060
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001061 if (InitEntity)
1062 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1063 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1064 << Init->getType() << Init->getSourceRange();
1065 else
1066 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1067 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1068 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001069 }
1070
Steve Naroffb2f72412008-09-29 20:07:05 +00001071 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001072 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001073 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1074 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001075
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001076 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor15e04622008-11-05 16:20:31 +00001077 } else if (getLangOptions().CPlusPlus) {
1078 // C++ [dcl.init]p14:
1079 // [...] If the class is an aggregate (8.5.1), and the initializer
1080 // is a brace-enclosed list, see 8.5.1.
1081 //
1082 // Note: 8.5.1 is handled below; here, we diagnose the case where
1083 // we have an initializer list and a destination type that is not
1084 // an aggregate.
1085 // FIXME: In C++0x, this is yet another form of initialization.
Douglas Gregore7ef5002009-01-30 17:31:00 +00001086 // FIXME: Move this checking into CheckInitList!
Douglas Gregor15e04622008-11-05 16:20:31 +00001087 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1088 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1089 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001090 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001091 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001092 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001093 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001094
Douglas Gregor849afc32009-01-29 00:45:39 +00001095 bool hadError = CheckInitList(InitList, DeclType);
1096 Init = InitList;
1097 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +00001098}
1099
Douglas Gregor6704b312008-11-17 22:58:34 +00001100/// GetNameForDeclarator - Determine the full declaration name for the
1101/// given Declarator.
1102DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1103 switch (D.getKind()) {
1104 case Declarator::DK_Abstract:
1105 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1106 return DeclarationName();
1107
1108 case Declarator::DK_Normal:
1109 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1110 return DeclarationName(D.getIdentifier());
1111
1112 case Declarator::DK_Constructor: {
1113 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1114 Ty = Context.getCanonicalType(Ty);
1115 return Context.DeclarationNames.getCXXConstructorName(Ty);
1116 }
1117
1118 case Declarator::DK_Destructor: {
1119 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1120 Ty = Context.getCanonicalType(Ty);
1121 return Context.DeclarationNames.getCXXDestructorName(Ty);
1122 }
1123
1124 case Declarator::DK_Conversion: {
1125 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1126 Ty = Context.getCanonicalType(Ty);
1127 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1128 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001129
1130 case Declarator::DK_Operator:
1131 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1132 return Context.DeclarationNames.getCXXOperatorName(
1133 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001134 }
1135
1136 assert(false && "Unknown name kind");
1137 return DeclarationName();
1138}
1139
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001140/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1141/// functions Declaration and Definition are "nearly" matching. This
1142/// heuristic is used to improve diagnostics in the case where an
1143/// out-of-line member function definition doesn't match any
1144/// declaration within the class.
1145static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1146 FunctionDecl *Declaration,
1147 FunctionDecl *Definition) {
1148 if (Declaration->param_size() != Definition->param_size())
1149 return false;
1150 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1151 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1152 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1153
1154 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1155 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1156 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1157 return false;
1158 }
1159
1160 return true;
1161}
1162
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001163Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001164Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1165 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001166 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001167 DeclarationName Name = GetNameForDeclarator(D);
1168
Chris Lattner4b009652007-07-25 00:24:17 +00001169 // All of these full declarators require an identifier. If it doesn't have
1170 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001171 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001172 if (!D.getInvalidType()) // Reject this if we think it is valid.
1173 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001174 diag::err_declarator_need_ident)
1175 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001176 return 0;
1177 }
1178
Chris Lattnera7549902007-08-26 06:24:45 +00001179 // The scope passed in may not be a decl scope. Zip up the scope tree until
1180 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001181 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1182 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001183 S = S->getParent();
1184
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001185 DeclContext *DC;
1186 Decl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001187 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001188 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001189
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001190 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001191 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001192 DC = CurContext;
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001193 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001194 } else { // Something like "int foo::x;"
1195 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001196 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001197
1198 // C++ 7.3.1.2p2:
1199 // Members (including explicit specializations of templates) of a named
1200 // namespace can also be defined outside that namespace by explicit
1201 // qualification of the name being defined, provided that the entity being
1202 // defined was already declared in the namespace and the definition appears
1203 // after the point of declaration in a namespace that encloses the
1204 // declarations namespace.
1205 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001206 // Note that we only check the context at this point. We don't yet
1207 // have enough information to make sure that PrevDecl is actually
1208 // the declaration we want to match. For example, given:
1209 //
Douglas Gregor98341042008-12-12 08:25:50 +00001210 // class X {
1211 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001212 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001213 // };
1214 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001215 // void X::f(int) { } // ill-formed
1216 //
1217 // In this case, PrevDecl will point to the overload set
1218 // containing the two f's declared in X, but neither of them
1219 // matches.
1220 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001221 // The qualifying scope doesn't enclose the original declaration.
1222 // Emit diagnostic based on current scope.
1223 SourceLocation L = D.getIdentifierLoc();
1224 SourceRange R = D.getCXXScopeSpec().getRange();
1225 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001226 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001227 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001228 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001229 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001230 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001231 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001232 }
1233 }
1234
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001235 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001236 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001237 InvalidDecl = InvalidDecl
1238 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001239 // Just pretend that we didn't see the previous declaration.
1240 PrevDecl = 0;
1241 }
1242
Douglas Gregor1d661552008-04-13 21:07:44 +00001243 // In C++, the previous declaration we find might be a tag type
1244 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001245 // tag type. Note that this does does not apply if we're declaring a
1246 // typedef (C++ [dcl.typedef]p4).
1247 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1248 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001249 PrevDecl = 0;
1250
Chris Lattner82bb4792007-11-14 06:34:38 +00001251 QualType R = GetTypeForDeclarator(D, S);
1252 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001255 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1256 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001257 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001258 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1259 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001260 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001261 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1262 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001263 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001264
1265 if (New == 0)
1266 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001267
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001268 // Set the lexical context. If the declarator has a C++ scope specifier, the
1269 // lexical context will be different from the semantic context.
1270 New->setLexicalDeclContext(CurContext);
1271
Chris Lattner4b009652007-07-25 00:24:17 +00001272 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001273 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001274 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001275 // If any semantic error occurred, mark the decl as invalid.
1276 if (D.getInvalidType() || InvalidDecl)
1277 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001278
1279 return New;
1280}
1281
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001282NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001283Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001284 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001285 Decl* PrevDecl, bool& InvalidDecl) {
1286 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1287 if (D.getCXXScopeSpec().isSet()) {
1288 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1289 << D.getCXXScopeSpec().getRange();
1290 InvalidDecl = true;
1291 // Pretend we didn't see the scope specifier.
1292 DC = 0;
1293 }
1294
1295 // Check that there are no default arguments (C++ only).
1296 if (getLangOptions().CPlusPlus)
1297 CheckExtraCXXDefaultArguments(D);
1298
1299 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1300 if (!NewTD) return 0;
1301
1302 // Handle attributes prior to checking for duplicates in MergeVarDecl
1303 ProcessDeclAttributes(NewTD, D);
1304 // Merge the decl with the existing one if appropriate. If the decl is
1305 // in an outer scope, it isn't the same thing.
1306 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1307 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1308 if (NewTD == 0) return 0;
1309 }
1310
1311 if (S->getFnParent() == 0) {
1312 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1313 // then it shall have block scope.
1314 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1315 if (NewTD->getUnderlyingType()->isVariableArrayType())
1316 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1317 else
1318 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1319
1320 InvalidDecl = true;
1321 }
1322 }
1323 return NewTD;
1324}
1325
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001326NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001327Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001328 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001329 Decl* PrevDecl, bool& InvalidDecl) {
1330 DeclarationName Name = GetNameForDeclarator(D);
1331
1332 // Check that there are no default arguments (C++ only).
1333 if (getLangOptions().CPlusPlus)
1334 CheckExtraCXXDefaultArguments(D);
1335
1336 if (R.getTypePtr()->isObjCInterfaceType()) {
1337 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1338 << D.getIdentifier();
1339 InvalidDecl = true;
1340 }
1341
1342 VarDecl *NewVD;
1343 VarDecl::StorageClass SC;
1344 switch (D.getDeclSpec().getStorageClassSpec()) {
1345 default: assert(0 && "Unknown storage class!");
1346 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1347 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1348 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1349 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1350 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1351 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1352 case DeclSpec::SCS_mutable:
1353 // mutable can only appear on non-static class members, so it's always
1354 // an error here
1355 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1356 InvalidDecl = true;
1357 SC = VarDecl::None;
1358 break;
1359 }
1360
1361 IdentifierInfo *II = Name.getAsIdentifierInfo();
1362 if (!II) {
1363 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1364 << Name.getAsString();
1365 return 0;
1366 }
1367
1368 if (DC->isRecord()) {
1369 // This is a static data member for a C++ class.
1370 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1371 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001372 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001373 } else {
1374 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1375 if (S->getFnParent() == 0) {
1376 // C99 6.9p2: The storage-class specifiers auto and register shall not
1377 // appear in the declaration specifiers in an external declaration.
1378 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1379 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1380 InvalidDecl = true;
1381 }
1382 }
1383 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001384 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001385 // FIXME: Move to DeclGroup...
1386 D.getDeclSpec().getSourceRange().getBegin());
1387 NewVD->setThreadSpecified(ThreadSpecified);
1388 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001389 NewVD->setNextDeclarator(LastDeclarator);
1390
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001391 // Handle attributes prior to checking for duplicates in MergeVarDecl
1392 ProcessDeclAttributes(NewVD, D);
1393
1394 // Handle GNU asm-label extension (encoded as an attribute).
1395 if (Expr *E = (Expr*) D.getAsmLabel()) {
1396 // The parser guarantees this is a string.
1397 StringLiteral *SE = cast<StringLiteral>(E);
1398 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1399 SE->getByteLength())));
1400 }
1401
1402 // Emit an error if an address space was applied to decl with local storage.
1403 // This includes arrays of objects with address space qualifiers, but not
1404 // automatic variables that point to other address spaces.
1405 // ISO/IEC TR 18037 S5.1.2
1406 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1407 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1408 InvalidDecl = true;
1409 }
1410 // Merge the decl with the existing one if appropriate. If the decl is
1411 // in an outer scope, it isn't the same thing.
1412 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1413 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1414 // The user tried to define a non-static data member
1415 // out-of-line (C++ [dcl.meaning]p1).
1416 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1417 << D.getCXXScopeSpec().getRange();
1418 NewVD->Destroy(Context);
1419 return 0;
1420 }
1421
1422 NewVD = MergeVarDecl(NewVD, PrevDecl);
1423 if (NewVD == 0) return 0;
1424
1425 if (D.getCXXScopeSpec().isSet()) {
1426 // No previous declaration in the qualifying scope.
1427 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1428 << Name << D.getCXXScopeSpec().getRange();
1429 InvalidDecl = true;
1430 }
1431 }
1432 return NewVD;
1433}
1434
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001435NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001436Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001437 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001438 Decl* PrevDecl, bool IsFunctionDefinition,
1439 bool& InvalidDecl) {
1440 assert(R.getTypePtr()->isFunctionType());
1441
1442 DeclarationName Name = GetNameForDeclarator(D);
1443 FunctionDecl::StorageClass SC = FunctionDecl::None;
1444 switch (D.getDeclSpec().getStorageClassSpec()) {
1445 default: assert(0 && "Unknown storage class!");
1446 case DeclSpec::SCS_auto:
1447 case DeclSpec::SCS_register:
1448 case DeclSpec::SCS_mutable:
1449 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1450 InvalidDecl = true;
1451 break;
1452 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1453 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1454 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1455 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1456 }
1457
1458 bool isInline = D.getDeclSpec().isInlineSpecified();
1459 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1460 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1461
1462 FunctionDecl *NewFD;
1463 if (D.getKind() == Declarator::DK_Constructor) {
1464 // This is a C++ constructor declaration.
1465 assert(DC->isRecord() &&
1466 "Constructors can only be declared in a member context");
1467
1468 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1469
1470 // Create the new declaration
1471 NewFD = CXXConstructorDecl::Create(Context,
1472 cast<CXXRecordDecl>(DC),
1473 D.getIdentifierLoc(), Name, R,
1474 isExplicit, isInline,
1475 /*isImplicitlyDeclared=*/false);
1476
1477 if (InvalidDecl)
1478 NewFD->setInvalidDecl();
1479 } else if (D.getKind() == Declarator::DK_Destructor) {
1480 // This is a C++ destructor declaration.
1481 if (DC->isRecord()) {
1482 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1483
1484 NewFD = CXXDestructorDecl::Create(Context,
1485 cast<CXXRecordDecl>(DC),
1486 D.getIdentifierLoc(), Name, R,
1487 isInline,
1488 /*isImplicitlyDeclared=*/false);
1489
1490 if (InvalidDecl)
1491 NewFD->setInvalidDecl();
1492 } else {
1493 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1494
1495 // Create a FunctionDecl to satisfy the function definition parsing
1496 // code path.
1497 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001498 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001499 // FIXME: Move to DeclGroup...
1500 D.getDeclSpec().getSourceRange().getBegin());
1501 InvalidDecl = true;
1502 NewFD->setInvalidDecl();
1503 }
1504 } else if (D.getKind() == Declarator::DK_Conversion) {
1505 if (!DC->isRecord()) {
1506 Diag(D.getIdentifierLoc(),
1507 diag::err_conv_function_not_member);
1508 return 0;
1509 } else {
1510 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1511
1512 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1513 D.getIdentifierLoc(), Name, R,
1514 isInline, isExplicit);
1515
1516 if (InvalidDecl)
1517 NewFD->setInvalidDecl();
1518 }
1519 } else if (DC->isRecord()) {
1520 // This is a C++ method declaration.
1521 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1522 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001523 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001524 } else {
1525 NewFD = FunctionDecl::Create(Context, DC,
1526 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001527 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001528 // FIXME: Move to DeclGroup...
1529 D.getDeclSpec().getSourceRange().getBegin());
1530 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001531 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001532
1533 // Set the lexical context. If the declarator has a C++
1534 // scope specifier, the lexical context will be different
1535 // from the semantic context.
1536 NewFD->setLexicalDeclContext(CurContext);
1537
1538 // Handle GNU asm-label extension (encoded as an attribute).
1539 if (Expr *E = (Expr*) D.getAsmLabel()) {
1540 // The parser guarantees this is a string.
1541 StringLiteral *SE = cast<StringLiteral>(E);
1542 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1543 SE->getByteLength())));
1544 }
1545
1546 // Copy the parameter declarations from the declarator D to
1547 // the function declaration NewFD, if they are available.
1548 if (D.getNumTypeObjects() > 0) {
1549 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1550
1551 // Create Decl objects for each parameter, adding them to the
1552 // FunctionDecl.
1553 llvm::SmallVector<ParmVarDecl*, 16> Params;
1554
1555 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1556 // function that takes no arguments, not a function that takes a
1557 // single void argument.
1558 // We let through "const void" here because Sema::GetTypeForDeclarator
1559 // already checks for that case.
1560 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1561 FTI.ArgInfo[0].Param &&
1562 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1563 // empty arg list, don't push any params.
1564 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1565
1566 // In C++, the empty parameter-type-list must be spelled "void"; a
1567 // typedef of void is not permitted.
1568 if (getLangOptions().CPlusPlus &&
1569 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1570 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1571 }
1572 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1573 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1574 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1575 }
1576
1577 NewFD->setParams(Context, &Params[0], Params.size());
1578 } else if (R->getAsTypedefType()) {
1579 // When we're declaring a function with a typedef, as in the
1580 // following example, we'll need to synthesize (unnamed)
1581 // parameters for use in the declaration.
1582 //
1583 // @code
1584 // typedef void fn(int);
1585 // fn f;
1586 // @endcode
1587 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1588 if (!FT) {
1589 // This is a typedef of a function with no prototype, so we
1590 // don't need to do anything.
1591 } else if ((FT->getNumArgs() == 0) ||
1592 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1593 FT->getArgType(0)->isVoidType())) {
1594 // This is a zero-argument function. We don't need to do anything.
1595 } else {
1596 // Synthesize a parameter for each argument type.
1597 llvm::SmallVector<ParmVarDecl*, 16> Params;
1598 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1599 ArgType != FT->arg_type_end(); ++ArgType) {
1600 Params.push_back(ParmVarDecl::Create(Context, DC,
1601 SourceLocation(), 0,
1602 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001603 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001604 }
1605
1606 NewFD->setParams(Context, &Params[0], Params.size());
1607 }
1608 }
1609
1610 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1611 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1612 else if (isa<CXXDestructorDecl>(NewFD)) {
1613 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1614 Record->setUserDeclaredDestructor(true);
1615 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1616 // user-defined destructor.
1617 Record->setPOD(false);
1618 } else if (CXXConversionDecl *Conversion =
1619 dyn_cast<CXXConversionDecl>(NewFD))
1620 ActOnConversionDeclarator(Conversion);
1621
1622 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1623 if (NewFD->isOverloadedOperator() &&
1624 CheckOverloadedOperatorDeclaration(NewFD))
1625 NewFD->setInvalidDecl();
1626
1627 // Merge the decl with the existing one if appropriate. Since C functions
1628 // are in a flat namespace, make sure we consider decls in outer scopes.
1629 if (PrevDecl &&
1630 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1631 bool Redeclaration = false;
1632
1633 // If C++, determine whether NewFD is an overload of PrevDecl or
1634 // a declaration that requires merging. If it's an overload,
1635 // there's no more work to do here; we'll just add the new
1636 // function to the scope.
1637 OverloadedFunctionDecl::function_iterator MatchedDecl;
1638 if (!getLangOptions().CPlusPlus ||
1639 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1640 Decl *OldDecl = PrevDecl;
1641
1642 // If PrevDecl was an overloaded function, extract the
1643 // FunctionDecl that matched.
1644 if (isa<OverloadedFunctionDecl>(PrevDecl))
1645 OldDecl = *MatchedDecl;
1646
1647 // NewFD and PrevDecl represent declarations that need to be
1648 // merged.
1649 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1650
1651 if (NewFD == 0) return 0;
1652 if (Redeclaration) {
1653 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1654
1655 // An out-of-line member function declaration must also be a
1656 // definition (C++ [dcl.meaning]p1).
1657 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1658 !InvalidDecl) {
1659 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1660 << D.getCXXScopeSpec().getRange();
1661 NewFD->setInvalidDecl();
1662 }
1663 }
1664 }
1665
1666 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1667 // The user tried to provide an out-of-line definition for a
1668 // member function, but there was no such member function
1669 // declared (C++ [class.mfct]p2). For example:
1670 //
1671 // class X {
1672 // void f() const;
1673 // };
1674 //
1675 // void X::f() { } // ill-formed
1676 //
1677 // Complain about this problem, and attempt to suggest close
1678 // matches (e.g., those that differ only in cv-qualifiers and
1679 // whether the parameter types are references).
1680 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1681 << cast<CXXRecordDecl>(DC)->getDeclName()
1682 << D.getCXXScopeSpec().getRange();
1683 InvalidDecl = true;
1684
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001685 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001686 if (!PrevDecl) {
1687 // Nothing to suggest.
1688 } else if (OverloadedFunctionDecl *Ovl
1689 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1690 for (OverloadedFunctionDecl::function_iterator
1691 Func = Ovl->function_begin(),
1692 FuncEnd = Ovl->function_end();
1693 Func != FuncEnd; ++Func) {
1694 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1695 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1696
1697 }
1698 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1699 // Suggest this no matter how mismatched it is; it's the only
1700 // thing we have.
1701 unsigned diag;
1702 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1703 diag = diag::note_member_def_close_match;
1704 else if (Method->getBody())
1705 diag = diag::note_previous_definition;
1706 else
1707 diag = diag::note_previous_declaration;
1708 Diag(Method->getLocation(), diag);
1709 }
1710
1711 PrevDecl = 0;
1712 }
1713 }
1714 // Handle attributes. We need to have merged decls when handling attributes
1715 // (for example to check for conflicts, etc).
1716 ProcessDeclAttributes(NewFD, D);
1717
1718 if (getLangOptions().CPlusPlus) {
1719 // In C++, check default arguments now that we have merged decls.
1720 CheckCXXDefaultArguments(NewFD);
1721
1722 // An out-of-line member function declaration must also be a
1723 // definition (C++ [dcl.meaning]p1).
1724 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1725 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1726 << D.getCXXScopeSpec().getRange();
1727 InvalidDecl = true;
1728 }
1729 }
1730 return NewFD;
1731}
1732
Steve Narofffc08f5e2008-10-27 11:34:16 +00001733void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001734 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1735 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001736}
1737
Eli Friedman02c22ce2008-05-20 13:48:25 +00001738bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1739 switch (Init->getStmtClass()) {
1740 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001741 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001742 return true;
1743 case Expr::ParenExprClass: {
1744 const ParenExpr* PE = cast<ParenExpr>(Init);
1745 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1746 }
1747 case Expr::CompoundLiteralExprClass:
1748 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001749 case Expr::DeclRefExprClass:
1750 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001751 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753 if (VD->hasGlobalStorage())
1754 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001755 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001756 return true;
1757 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001758 if (isa<FunctionDecl>(D))
1759 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001760 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001761 return true;
1762 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001763 case Expr::MemberExprClass: {
1764 const MemberExpr *M = cast<MemberExpr>(Init);
1765 if (M->isArrow())
1766 return CheckAddressConstantExpression(M->getBase());
1767 return CheckAddressConstantExpressionLValue(M->getBase());
1768 }
1769 case Expr::ArraySubscriptExprClass: {
1770 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1771 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1772 return CheckAddressConstantExpression(ASE->getBase()) ||
1773 CheckArithmeticConstantExpression(ASE->getIdx());
1774 }
1775 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001776 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001777 return false;
1778 case Expr::UnaryOperatorClass: {
1779 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1780
1781 // C99 6.6p9
1782 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001783 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001784
Steve Narofffc08f5e2008-10-27 11:34:16 +00001785 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001786 return true;
1787 }
1788 }
1789}
1790
1791bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1792 switch (Init->getStmtClass()) {
1793 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001794 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001795 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001796 case Expr::ParenExprClass:
1797 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001798 case Expr::StringLiteralClass:
1799 case Expr::ObjCStringLiteralClass:
1800 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001801 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001802 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001803 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1804 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1805 Builtin::BI__builtin___CFStringMakeConstantString)
1806 return false;
1807
Steve Narofffc08f5e2008-10-27 11:34:16 +00001808 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001809 return true;
1810
Eli Friedman02c22ce2008-05-20 13:48:25 +00001811 case Expr::UnaryOperatorClass: {
1812 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1813
1814 // C99 6.6p9
1815 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1816 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1817
1818 if (Exp->getOpcode() == UnaryOperator::Extension)
1819 return CheckAddressConstantExpression(Exp->getSubExpr());
1820
Steve Narofffc08f5e2008-10-27 11:34:16 +00001821 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001822 return true;
1823 }
1824 case Expr::BinaryOperatorClass: {
1825 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1826 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1827
1828 Expr *PExp = Exp->getLHS();
1829 Expr *IExp = Exp->getRHS();
1830 if (IExp->getType()->isPointerType())
1831 std::swap(PExp, IExp);
1832
1833 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1834 return CheckAddressConstantExpression(PExp) ||
1835 CheckArithmeticConstantExpression(IExp);
1836 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001837 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001838 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001839 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001840 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1841 // Check for implicit promotion
1842 if (SubExpr->getType()->isFunctionType() ||
1843 SubExpr->getType()->isArrayType())
1844 return CheckAddressConstantExpressionLValue(SubExpr);
1845 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001846
1847 // Check for pointer->pointer cast
1848 if (SubExpr->getType()->isPointerType())
1849 return CheckAddressConstantExpression(SubExpr);
1850
Eli Friedman1fad3c62008-08-25 20:46:57 +00001851 if (SubExpr->getType()->isIntegralType()) {
1852 // Check for the special-case of a pointer->int->pointer cast;
1853 // this isn't standard, but some code requires it. See
1854 // PR2720 for an example.
1855 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1856 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1857 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1858 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1859 if (IntWidth >= PointerWidth) {
1860 return CheckAddressConstantExpression(SubCast->getSubExpr());
1861 }
1862 }
1863 }
1864 }
1865 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001866 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001867 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001868
Steve Narofffc08f5e2008-10-27 11:34:16 +00001869 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001870 return true;
1871 }
1872 case Expr::ConditionalOperatorClass: {
1873 // FIXME: Should we pedwarn here?
1874 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1875 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001876 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001877 return true;
1878 }
1879 if (CheckArithmeticConstantExpression(Exp->getCond()))
1880 return true;
1881 if (Exp->getLHS() &&
1882 CheckAddressConstantExpression(Exp->getLHS()))
1883 return true;
1884 return CheckAddressConstantExpression(Exp->getRHS());
1885 }
1886 case Expr::AddrLabelExprClass:
1887 return false;
1888 }
1889}
1890
Eli Friedman998dffb2008-06-09 05:05:07 +00001891static const Expr* FindExpressionBaseAddress(const Expr* E);
1892
1893static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1894 switch (E->getStmtClass()) {
1895 default:
1896 return E;
1897 case Expr::ParenExprClass: {
1898 const ParenExpr* PE = cast<ParenExpr>(E);
1899 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1900 }
1901 case Expr::MemberExprClass: {
1902 const MemberExpr *M = cast<MemberExpr>(E);
1903 if (M->isArrow())
1904 return FindExpressionBaseAddress(M->getBase());
1905 return FindExpressionBaseAddressLValue(M->getBase());
1906 }
1907 case Expr::ArraySubscriptExprClass: {
1908 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1909 return FindExpressionBaseAddress(ASE->getBase());
1910 }
1911 case Expr::UnaryOperatorClass: {
1912 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1913
1914 if (Exp->getOpcode() == UnaryOperator::Deref)
1915 return FindExpressionBaseAddress(Exp->getSubExpr());
1916
1917 return E;
1918 }
1919 }
1920}
1921
1922static const Expr* FindExpressionBaseAddress(const Expr* E) {
1923 switch (E->getStmtClass()) {
1924 default:
1925 return E;
1926 case Expr::ParenExprClass: {
1927 const ParenExpr* PE = cast<ParenExpr>(E);
1928 return FindExpressionBaseAddress(PE->getSubExpr());
1929 }
1930 case Expr::UnaryOperatorClass: {
1931 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1932
1933 // C99 6.6p9
1934 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1935 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1936
1937 if (Exp->getOpcode() == UnaryOperator::Extension)
1938 return FindExpressionBaseAddress(Exp->getSubExpr());
1939
1940 return E;
1941 }
1942 case Expr::BinaryOperatorClass: {
1943 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1944
1945 Expr *PExp = Exp->getLHS();
1946 Expr *IExp = Exp->getRHS();
1947 if (IExp->getType()->isPointerType())
1948 std::swap(PExp, IExp);
1949
1950 return FindExpressionBaseAddress(PExp);
1951 }
1952 case Expr::ImplicitCastExprClass: {
1953 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1954
1955 // Check for implicit promotion
1956 if (SubExpr->getType()->isFunctionType() ||
1957 SubExpr->getType()->isArrayType())
1958 return FindExpressionBaseAddressLValue(SubExpr);
1959
1960 // Check for pointer->pointer cast
1961 if (SubExpr->getType()->isPointerType())
1962 return FindExpressionBaseAddress(SubExpr);
1963
1964 // We assume that we have an arithmetic expression here;
1965 // if we don't, we'll figure it out later
1966 return 0;
1967 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001968 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001969 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1970
1971 // Check for pointer->pointer cast
1972 if (SubExpr->getType()->isPointerType())
1973 return FindExpressionBaseAddress(SubExpr);
1974
1975 // We assume that we have an arithmetic expression here;
1976 // if we don't, we'll figure it out later
1977 return 0;
1978 }
1979 }
1980}
1981
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001982bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001983 switch (Init->getStmtClass()) {
1984 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001985 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001986 return true;
1987 case Expr::ParenExprClass: {
1988 const ParenExpr* PE = cast<ParenExpr>(Init);
1989 return CheckArithmeticConstantExpression(PE->getSubExpr());
1990 }
1991 case Expr::FloatingLiteralClass:
1992 case Expr::IntegerLiteralClass:
1993 case Expr::CharacterLiteralClass:
1994 case Expr::ImaginaryLiteralClass:
1995 case Expr::TypesCompatibleExprClass:
1996 case Expr::CXXBoolLiteralExprClass:
1997 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001998 case Expr::CallExprClass:
1999 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002000 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002001
2002 // Allow any constant foldable calls to builtins.
2003 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002004 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002005
Steve Narofffc08f5e2008-10-27 11:34:16 +00002006 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002007 return true;
2008 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002009 case Expr::DeclRefExprClass:
2010 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002011 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2012 if (isa<EnumConstantDecl>(D))
2013 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002014 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002015 return true;
2016 }
2017 case Expr::CompoundLiteralExprClass:
2018 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2019 // but vectors are allowed to be magic.
2020 if (Init->getType()->isVectorType())
2021 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002022 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002023 return true;
2024 case Expr::UnaryOperatorClass: {
2025 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2026
2027 switch (Exp->getOpcode()) {
2028 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2029 // See C99 6.6p3.
2030 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002031 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002032 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002033 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002034 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2035 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002036 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002037 return true;
2038 case UnaryOperator::Extension:
2039 case UnaryOperator::LNot:
2040 case UnaryOperator::Plus:
2041 case UnaryOperator::Minus:
2042 case UnaryOperator::Not:
2043 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2044 }
2045 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002046 case Expr::SizeOfAlignOfExprClass: {
2047 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002048 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002049 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002050 return false;
2051 // alignof always evaluates to a constant.
2052 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002053 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002054 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002055 return true;
2056 }
2057 return false;
2058 }
2059 case Expr::BinaryOperatorClass: {
2060 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2061
2062 if (Exp->getLHS()->getType()->isArithmeticType() &&
2063 Exp->getRHS()->getType()->isArithmeticType()) {
2064 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2065 CheckArithmeticConstantExpression(Exp->getRHS());
2066 }
2067
Eli Friedman998dffb2008-06-09 05:05:07 +00002068 if (Exp->getLHS()->getType()->isPointerType() &&
2069 Exp->getRHS()->getType()->isPointerType()) {
2070 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2071 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2072
2073 // Only allow a null (constant integer) base; we could
2074 // allow some additional cases if necessary, but this
2075 // is sufficient to cover offsetof-like constructs.
2076 if (!LHSBase && !RHSBase) {
2077 return CheckAddressConstantExpression(Exp->getLHS()) ||
2078 CheckAddressConstantExpression(Exp->getRHS());
2079 }
2080 }
2081
Steve Narofffc08f5e2008-10-27 11:34:16 +00002082 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002083 return true;
2084 }
2085 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002086 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002087 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
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);
2093 // If the pointer has a null base, this is an offsetof-like construct
2094 if (!Base)
2095 return CheckAddressConstantExpression(SubExpr);
2096 }
2097
Steve Narofffc08f5e2008-10-27 11:34:16 +00002098 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002099 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002100 }
2101 case Expr::ConditionalOperatorClass: {
2102 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002103
2104 // If GNU extensions are disabled, we require all operands to be arithmetic
2105 // constant expressions.
2106 if (getLangOptions().NoExtensions) {
2107 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2108 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2109 CheckArithmeticConstantExpression(Exp->getRHS());
2110 }
2111
2112 // Otherwise, we have to emulate some of the behavior of fold here.
2113 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2114 // because it can constant fold things away. To retain compatibility with
2115 // GCC code, we see if we can fold the condition to a constant (which we
2116 // should always be able to do in theory). If so, we only require the
2117 // specified arm of the conditional to be a constant. This is a horrible
2118 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002119 Expr::EvalResult EvalResult;
2120 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2121 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002122 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002123 // won't be able to either. Use it to emit the diagnostic though.
2124 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002125 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002126 return Res;
2127 }
2128
2129 // Verify that the side following the condition is also a constant.
2130 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002131 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002132 std::swap(TrueSide, FalseSide);
2133
2134 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002135 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002136
2137 // Okay, the evaluated side evaluates to a constant, so we accept this.
2138 // Check to see if the other side is obviously not a constant. If so,
2139 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002140 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002141 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002142 diag::ext_typecheck_expression_not_constant_but_accepted)
2143 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002144 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002145 }
2146 }
2147}
2148
2149bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002150 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2151 Init = DIE->getInit();
2152
Nuno Lopese7280452008-07-07 16:46:50 +00002153 Init = Init->IgnoreParens();
2154
Nate Begemand6d2f772009-01-18 03:20:47 +00002155 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002156 return false;
2157
Eli Friedman02c22ce2008-05-20 13:48:25 +00002158 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2159 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2160 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2161
Nuno Lopese7280452008-07-07 16:46:50 +00002162 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2163 return CheckForConstantInitializer(e->getInitializer(), DclT);
2164
Douglas Gregorc9e012a2009-01-29 17:44:32 +00002165 if (isa<ImplicitValueInitExpr>(Init)) {
2166 // FIXME: In C++, check for non-POD types.
2167 return false;
2168 }
2169
Eli Friedman02c22ce2008-05-20 13:48:25 +00002170 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2171 unsigned numInits = Exp->getNumInits();
2172 for (unsigned i = 0; i < numInits; i++) {
2173 // FIXME: Need to get the type of the declaration for C++,
2174 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002175
Eli Friedman02c22ce2008-05-20 13:48:25 +00002176 if (CheckForConstantInitializer(Exp->getInit(i),
2177 Exp->getInit(i)->getType()))
2178 return true;
2179 }
2180 return false;
2181 }
2182
Anders Carlssonf6791c62008-12-05 05:09:56 +00002183 // FIXME: We can probably remove some of this code below, now that
2184 // Expr::Evaluate is doing the heavy lifting for scalars.
2185
Eli Friedman02c22ce2008-05-20 13:48:25 +00002186 if (Init->isNullPointerConstant(Context))
2187 return false;
2188 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002189 QualType InitTy = Context.getCanonicalType(Init->getType())
2190 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002191 if (InitTy == Context.BoolTy) {
2192 // Special handling for pointers implicitly cast to bool;
2193 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2194 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2195 Expr* SubE = ICE->getSubExpr();
2196 if (SubE->getType()->isPointerType() ||
2197 SubE->getType()->isArrayType() ||
2198 SubE->getType()->isFunctionType()) {
2199 return CheckAddressConstantExpression(Init);
2200 }
2201 }
2202 } else if (InitTy->isIntegralType()) {
2203 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002204 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002205 SubE = CE->getSubExpr();
2206 // Special check for pointer cast to int; we allow as an extension
2207 // an address constant cast to an integer if the integer
2208 // is of an appropriate width (this sort of code is apparently used
2209 // in some places).
2210 // FIXME: Add pedwarn?
2211 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2212 if (SubE && (SubE->getType()->isPointerType() ||
2213 SubE->getType()->isArrayType() ||
2214 SubE->getType()->isFunctionType())) {
2215 unsigned IntWidth = Context.getTypeSize(Init->getType());
2216 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2217 if (IntWidth >= PointerWidth)
2218 return CheckAddressConstantExpression(Init);
2219 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002220 }
2221
2222 return CheckArithmeticConstantExpression(Init);
2223 }
2224
2225 if (Init->getType()->isPointerType())
2226 return CheckAddressConstantExpression(Init);
2227
Eli Friedman25086f02008-05-30 18:14:48 +00002228 // An array type at the top level that isn't an init-list must
2229 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002230 if (Init->getType()->isArrayType())
2231 return false;
2232
Nuno Lopes1dc26762008-09-01 18:42:41 +00002233 if (Init->getType()->isFunctionType())
2234 return false;
2235
Steve Naroffdff3fb22008-10-02 17:12:56 +00002236 // Allow block exprs at top level.
2237 if (Init->getType()->isBlockPointerType())
2238 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002239
2240 // GCC cast to union extension
2241 // note: the validity of the cast expr is checked by CheckCastTypes()
2242 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2243 QualType T = C->getType();
2244 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2245 }
2246
Steve Narofffc08f5e2008-10-27 11:34:16 +00002247 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002248 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002249}
2250
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002251void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002252 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2253}
2254
2255/// AddInitializerToDecl - Adds the initializer Init to the
2256/// declaration dcl. If DirectInit is true, this is C++ direct
2257/// initialization rather than copy initialization.
2258void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002259 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002260 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002261 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002262
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002263 // If there is no declaration, there was an error parsing it. Just ignore
2264 // the initializer.
2265 if (RealDecl == 0) {
2266 delete Init;
2267 return;
2268 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002269
Steve Naroff420d0f52007-09-12 20:13:48 +00002270 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2271 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002272 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002273 RealDecl->setInvalidDecl();
2274 return;
2275 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002276 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002277 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002278 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002279 if (VDecl->isBlockVarDecl()) {
2280 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002281 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002282 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002283 VDecl->setInvalidDecl();
2284 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002285 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002286 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002287 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002288
2289 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2290 if (!getLangOptions().CPlusPlus) {
2291 if (SC == VarDecl::Static) // C99 6.7.8p4.
2292 CheckForConstantInitializer(Init, DclT);
2293 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002294 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002295 } else if (VDecl->isFileVarDecl()) {
2296 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002297 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002298 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002299 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002300 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002301 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002302
Anders Carlssonea7140a2008-08-22 05:00:02 +00002303 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2304 if (!getLangOptions().CPlusPlus) {
2305 // C99 6.7.8p4. All file scoped initializers need to be constant.
2306 CheckForConstantInitializer(Init, DclT);
2307 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002308 }
2309 // If the type changed, it means we had an incomplete type that was
2310 // completed by the initializer. For example:
2311 // int ary[] = { 1, 3, 5 };
2312 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002313 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002314 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002315 Init->setType(DclT);
2316 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002317
2318 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002319 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002320 return;
2321}
2322
Douglas Gregor81c29152008-10-29 00:13:59 +00002323void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2324 Decl *RealDecl = static_cast<Decl *>(dcl);
2325
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002326 // If there is no declaration, there was an error parsing it. Just ignore it.
2327 if (RealDecl == 0)
2328 return;
2329
Douglas Gregor81c29152008-10-29 00:13:59 +00002330 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2331 QualType Type = Var->getType();
2332 // C++ [dcl.init.ref]p3:
2333 // The initializer can be omitted for a reference only in a
2334 // parameter declaration (8.3.5), in the declaration of a
2335 // function return type, in the declaration of a class member
2336 // within its class declaration (9.2), and where the extern
2337 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002338 if (Type->isReferenceType() &&
2339 Var->getStorageClass() != VarDecl::Extern &&
2340 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002341 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002342 << Var->getDeclName()
2343 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002344 Var->setInvalidDecl();
2345 return;
2346 }
2347
2348 // C++ [dcl.init]p9:
2349 //
2350 // If no initializer is specified for an object, and the object
2351 // is of (possibly cv-qualified) non-POD class type (or array
2352 // thereof), the object shall be default-initialized; if the
2353 // object is of const-qualified type, the underlying class type
2354 // shall have a user-declared default constructor.
2355 if (getLangOptions().CPlusPlus) {
2356 QualType InitType = Type;
2357 if (const ArrayType *Array = Context.getAsArrayType(Type))
2358 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002359 if (Var->getStorageClass() != VarDecl::Extern &&
2360 Var->getStorageClass() != VarDecl::PrivateExtern &&
2361 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002362 const CXXConstructorDecl *Constructor
2363 = PerformInitializationByConstructor(InitType, 0, 0,
2364 Var->getLocation(),
2365 SourceRange(Var->getLocation(),
2366 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002367 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002368 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002369 if (!Constructor)
2370 Var->setInvalidDecl();
2371 }
2372 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002373
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002374#if 0
2375 // FIXME: Temporarily disabled because we are not properly parsing
2376 // linkage specifications on declarations, e.g.,
2377 //
2378 // extern "C" const CGPoint CGPointerZero;
2379 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002380 // C++ [dcl.init]p9:
2381 //
2382 // If no initializer is specified for an object, and the
2383 // object is of (possibly cv-qualified) non-POD class type (or
2384 // array thereof), the object shall be default-initialized; if
2385 // the object is of const-qualified type, the underlying class
2386 // type shall have a user-declared default
2387 // constructor. Otherwise, if no initializer is specified for
2388 // an object, the object and its subobjects, if any, have an
2389 // indeterminate initial value; if the object or any of its
2390 // subobjects are of const-qualified type, the program is
2391 // ill-formed.
2392 //
2393 // This isn't technically an error in C, so we don't diagnose it.
2394 //
2395 // FIXME: Actually perform the POD/user-defined default
2396 // constructor check.
2397 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002398 Context.getCanonicalType(Type).isConstQualified() &&
2399 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002400 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2401 << Var->getName()
2402 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002403#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002404 }
2405}
2406
Chris Lattner4b009652007-07-25 00:24:17 +00002407/// The declarators are chained together backwards, reverse the list.
2408Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2409 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002410 Decl *GroupDecl = static_cast<Decl*>(group);
2411 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002412 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002413
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002414 Decl *Group = dyn_cast<Decl>(GroupDecl);
2415 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002416 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002417 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002418 else { // reverse the list.
2419 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002420 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002421 Group->setNextDeclarator(NewGroup);
2422 NewGroup = Group;
2423 Group = Next;
2424 }
2425 }
2426 // Perform semantic analysis that depends on having fully processed both
2427 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002428 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002429 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2430 if (!IDecl)
2431 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002432 QualType T = IDecl->getType();
2433
Anders Carlsson68adbd12008-12-07 00:20:55 +00002434 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002435 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002436
2437 // FIXME: This won't give the correct result for
2438 // int a[10][n];
2439 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002440 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002441 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2442 SizeRange;
2443
Eli Friedman8ff07782008-02-15 18:16:39 +00002444 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002445 } else {
2446 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2447 // static storage duration, it shall not have a variable length array.
2448 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002449 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2450 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002451 IDecl->setInvalidDecl();
2452 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002453 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2454 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002455 IDecl->setInvalidDecl();
2456 }
2457 }
2458 } else if (T->isVariablyModifiedType()) {
2459 if (IDecl->isFileVarDecl()) {
2460 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2461 IDecl->setInvalidDecl();
2462 } else {
2463 if (IDecl->getStorageClass() == VarDecl::Extern) {
2464 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2465 IDecl->setInvalidDecl();
2466 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002467 }
2468 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002469
Steve Naroff6a0e2092007-09-12 14:07:44 +00002470 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2471 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002472 if (IDecl->isBlockVarDecl() &&
2473 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002474 if (!IDecl->isInvalidDecl() &&
2475 DiagnoseIncompleteType(IDecl->getLocation(), T,
2476 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002477 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002478 }
2479 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2480 // object that has file scope without an initializer, and without a
2481 // storage-class specifier or with the storage-class specifier "static",
2482 // constitutes a tentative definition. Note: A tentative definition with
2483 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002484 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002485 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002486 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2487 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002488 } else if (!IDecl->isInvalidDecl() &&
2489 DiagnoseIncompleteType(IDecl->getLocation(), T,
2490 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002491 // C99 6.9.2p3: If the declaration of an identifier for an object is
2492 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2493 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002494 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002495 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002496 if (IDecl->isFileVarDecl())
2497 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002498 }
2499 return NewGroup;
2500}
Steve Naroff91b03f72007-08-28 03:03:08 +00002501
Chris Lattner3e254fb2008-04-08 04:40:51 +00002502/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2503/// to introduce parameters into function prototype scope.
2504Sema::DeclTy *
2505Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002506 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002507
Chris Lattner3e254fb2008-04-08 04:40:51 +00002508 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002509 VarDecl::StorageClass StorageClass = VarDecl::None;
2510 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2511 StorageClass = VarDecl::Register;
2512 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002513 Diag(DS.getStorageClassSpecLoc(),
2514 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002515 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002516 }
2517 if (DS.isThreadSpecified()) {
2518 Diag(DS.getThreadSpecLoc(),
2519 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002520 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002521 }
2522
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002523 // Check that there are no default arguments inside the type of this
2524 // parameter (C++ only).
2525 if (getLangOptions().CPlusPlus)
2526 CheckExtraCXXDefaultArguments(D);
2527
Chris Lattner3e254fb2008-04-08 04:40:51 +00002528 // In this context, we *do not* check D.getInvalidType(). If the declarator
2529 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2530 // though it will not reflect the user specified type.
2531 QualType parmDeclType = GetTypeForDeclarator(D, S);
2532
2533 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2534
Chris Lattner4b009652007-07-25 00:24:17 +00002535 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2536 // Can this happen for params? We already checked that they don't conflict
2537 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002538 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002539 if (II) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002540 if (Decl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002541 if (PrevDecl->isTemplateParameter()) {
2542 // Maybe we will complain about the shadowed template parameter.
2543 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2544 // Just pretend that we didn't see the previous declaration.
2545 PrevDecl = 0;
2546 } else if (S->isDeclScope(PrevDecl)) {
2547 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002548
Chris Lattner310dea32009-01-21 02:38:50 +00002549 // Recover by removing the name
2550 II = 0;
2551 D.SetIdentifier(0, D.getIdentifierLoc());
2552 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002553 }
Chris Lattner4b009652007-07-25 00:24:17 +00002554 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002555
2556 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2557 // Doing the promotion here has a win and a loss. The win is the type for
2558 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2559 // code generator). The loss is the orginal type isn't preserved. For example:
2560 //
2561 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2562 // int blockvardecl[5];
2563 // sizeof(parmvardecl); // size == 4
2564 // sizeof(blockvardecl); // size == 20
2565 // }
2566 //
2567 // For expressions, all implicit conversions are captured using the
2568 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2569 //
2570 // FIXME: If a source translation tool needs to see the original type, then
2571 // we need to consider storing both types (in ParmVarDecl)...
2572 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002573 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002574 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002575 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002576 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002577 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002578
Chris Lattner3e254fb2008-04-08 04:40:51 +00002579 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2580 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002581 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002582 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002583
Chris Lattner3e254fb2008-04-08 04:40:51 +00002584 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002585 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002586
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002587 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2588 if (D.getCXXScopeSpec().isSet()) {
2589 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2590 << D.getCXXScopeSpec().getRange();
2591 New->setInvalidDecl();
2592 }
2593
Douglas Gregor8acb7272008-12-11 16:49:14 +00002594 // Add the parameter declaration into this scope.
2595 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002596 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002597 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002598
Chris Lattner9b384ca2008-06-29 00:02:00 +00002599 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002600 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002601
Chris Lattner4b009652007-07-25 00:24:17 +00002602}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002603
Douglas Gregor65075ec2009-01-23 16:23:13 +00002604void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002605 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2606 "Not a function declarator!");
2607 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002608
Chris Lattner4b009652007-07-25 00:24:17 +00002609 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2610 // for a K&R function.
2611 if (!FTI.hasPrototype) {
2612 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002613 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002614 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2615 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002616 // Implicitly declare the argument as type 'int' for lack of a better
2617 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002618 DeclSpec DS;
2619 const char* PrevSpec; // unused
2620 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2621 PrevSpec);
2622 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2623 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002624 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002625 }
2626 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002627 }
2628}
2629
2630Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2631 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2632 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2633 "Not a function declarator!");
2634 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2635
2636 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002637 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002638 }
2639
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002640 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002641
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002642 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002643 ActOnDeclarator(ParentScope, D, 0,
2644 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002645}
2646
2647Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2648 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002649 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002650
2651 // See if this is a redefinition.
2652 const FunctionDecl *Definition;
2653 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002654 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002655 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002656 }
2657
Douglas Gregor8acb7272008-12-11 16:49:14 +00002658 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002659
Chris Lattner3e254fb2008-04-08 04:40:51 +00002660 // Check the validity of our function parameters
2661 CheckParmsForFunctionDef(FD);
2662
2663 // Introduce our parameters into the function scope
2664 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2665 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002666 Param->setOwningFunction(FD);
2667
Chris Lattner3e254fb2008-04-08 04:40:51 +00002668 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002669 if (Param->getIdentifier())
2670 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002671 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002672
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002673 // Checking attributes of current function definition
2674 // dllimport attribute.
2675 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2676 // dllimport attribute cannot be applied to definition.
2677 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2678 Diag(FD->getLocation(),
2679 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2680 << "dllimport";
2681 FD->setInvalidDecl();
2682 return FD;
2683 } else {
2684 // If a symbol previously declared dllimport is later defined, the
2685 // attribute is ignored in subsequent references, and a warning is
2686 // emitted.
2687 Diag(FD->getLocation(),
2688 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2689 << FD->getNameAsCString() << "dllimport";
2690 }
2691 }
Chris Lattner4b009652007-07-25 00:24:17 +00002692 return FD;
2693}
2694
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002695Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002696 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002697 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002698 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002699 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002700 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002701 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002702 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002703 } else
2704 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002705 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002706 // Verify and clean out per-function state.
2707
2708 // Check goto/label use.
2709 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2710 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2711 // Verify that we have no forward references left. If so, there was a goto
2712 // or address of a label taken, but no definition of it. Label fwd
2713 // definitions are indicated with a null substmt.
2714 if (I->second->getSubStmt() == 0) {
2715 LabelStmt *L = I->second;
2716 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002717 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002718
2719 // At this point, we have gotos that use the bogus label. Stitch it into
2720 // the function body so that they aren't leaked and that the AST is well
2721 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002722 if (Body) {
2723 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002724 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002725 } else {
2726 // The whole function wasn't parsed correctly, just delete this.
2727 delete L;
2728 }
Chris Lattner4b009652007-07-25 00:24:17 +00002729 }
2730 }
2731 LabelMap.clear();
2732
Steve Naroff99ee4302007-11-11 23:20:51 +00002733 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002734}
2735
Chris Lattner4b009652007-07-25 00:24:17 +00002736/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2737/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002738NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2739 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002740 // Extension in C99. Legal in C90, but warn about it.
2741 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002742 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002743 else
Chris Lattner65cae292008-11-19 08:23:25 +00002744 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002745
2746 // FIXME: handle stuff like:
2747 // void foo() { extern float X(); }
2748 // void bar() { X(); } <-- implicit decl for X in another scope.
2749
2750 // Set a Declarator for the implicit definition: int foo();
2751 const char *Dummy;
2752 DeclSpec DS;
2753 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2754 Error = Error; // Silence warning.
2755 assert(!Error && "Error setting up implicit decl!");
2756 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002757 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002758 D.SetIdentifier(&II, Loc);
2759
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002760 // Insert this function into translation-unit scope.
2761
2762 DeclContext *PrevDC = CurContext;
2763 CurContext = Context.getTranslationUnitDecl();
2764
Steve Naroff9104f3c2008-04-04 14:32:09 +00002765 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002766 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002767 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002768
2769 CurContext = PrevDC;
2770
Steve Naroff9104f3c2008-04-04 14:32:09 +00002771 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002772}
2773
2774
Chris Lattner82bb4792007-11-14 06:34:38 +00002775TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002776 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002777 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002778 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002779
2780 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002781 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2782 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002783 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002784 T);
2785 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002786 if (D.getInvalidType())
2787 NewTD->setInvalidDecl();
2788 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002789}
2790
Steve Naroff0acc9c92007-09-15 18:49:24 +00002791/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002792/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002793/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002794/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002795Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002796 SourceLocation KWLoc, const CXXScopeSpec &SS,
2797 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002798 AttributeList *Attr,
2799 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002800 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002801 assert((Name != 0 || TK == TK_Definition) &&
2802 "Nameless record must be a definition!");
2803
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002804 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002805 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002806 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002807 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2808 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2809 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2810 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002811 }
2812
Douglas Gregorb748fc52009-01-12 22:49:06 +00002813 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002814 DeclContext *DC = CurContext;
Douglas Gregorcab994d2009-01-09 22:42:13 +00002815 DeclContext *LexicalContext = CurContext;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002816 Decl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002817
Douglas Gregor98b27542009-01-17 00:42:38 +00002818 bool Invalid = false;
2819
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002820 if (Name && SS.isNotEmpty()) {
2821 // We have a nested-name tag ('struct foo::bar').
2822
2823 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002824 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002825 Name = 0;
2826 goto CreateNewDecl;
2827 }
2828
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002829 DC = static_cast<DeclContext*>(SS.getScopeRep());
2830 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002831 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002832 LookupQualifiedName(DC, Name, LookupTagName).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002833
2834 // A tag 'foo::bar' must already exist.
2835 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002836 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002837 Name = 0;
2838 goto CreateNewDecl;
2839 }
Chris Lattner310dea32009-01-21 02:38:50 +00002840 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002841 // If this is a named struct, check to see if there was a previous forward
2842 // declaration or definition.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002843 Decl *D = LookupName(S, Name, LookupTagName);
Steve Naroffa4e04982009-01-29 18:09:31 +00002844 PrevDecl = dyn_cast_or_null<NamedDecl>(D);
Douglas Gregordb568cf2009-01-08 20:45:30 +00002845
2846 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2847 // FIXME: This makes sure that we ignore the contexts associated
2848 // with C structs, unions, and enums when looking for a matching
2849 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002850 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002851 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2852 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002853 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002854 }
2855
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002856 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002857 // Maybe we will complain about the shadowed template parameter.
2858 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2859 // Just pretend that we didn't see the previous declaration.
2860 PrevDecl = 0;
2861 }
2862
Ted Kremenekd4434152008-09-02 21:26:19 +00002863 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002864 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002865 // If this is a use of a previous tag, or if the tag is already declared
2866 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002867 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002868 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002869 // Make sure that this wasn't declared as an enum and now used as a
2870 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002871 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002872 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002873 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002874 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002875 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002876 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002877 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002878 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002879 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002880
Douglas Gregorae644892008-12-15 16:32:14 +00002881 // FIXME: In the future, return a variant or some other clue
2882 // for the consumer of this Decl to know it doesn't own it.
2883 // For our current ASTs this shouldn't be a problem, but will
2884 // need to be changed with DeclGroups.
2885 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002886 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002887
2888 // Diagnose attempts to redefine a tag.
2889 if (TK == TK_Definition) {
2890 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2891 Diag(NameLoc, diag::err_redefinition) << Name;
2892 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002893 // If this is a redefinition, recover by making this
2894 // struct be anonymous, which will make any later
2895 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002896 Name = 0;
2897 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002898 Invalid = true;
2899 } else {
2900 // If the type is currently being defined, complain
2901 // about a nested redefinition.
2902 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2903 if (Tag->isBeingDefined()) {
2904 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2905 Diag(PrevTagDecl->getLocation(),
2906 diag::note_previous_definition);
2907 Name = 0;
2908 PrevDecl = 0;
2909 Invalid = true;
2910 }
Douglas Gregorae644892008-12-15 16:32:14 +00002911 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002912
Douglas Gregorae644892008-12-15 16:32:14 +00002913 // Okay, this is definition of a previously declared or referenced
2914 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002915 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002916 }
Douglas Gregorae644892008-12-15 16:32:14 +00002917 // If we get here we have (another) forward declaration or we
2918 // have a definition. Just create a new decl.
2919 } else {
2920 // If we get here, this is a definition of a new tag type in a nested
2921 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2922 // new decl/type. We set PrevDecl to NULL so that the entities
2923 // have distinct types.
2924 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002925 }
Douglas Gregorae644892008-12-15 16:32:14 +00002926 // If we get here, we're going to create a new Decl. If PrevDecl
2927 // is non-NULL, it's a definition of the tag declared by
2928 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002929 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00002930 // PrevDecl is a namespace, template, or anything else
2931 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002932 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002933 // The tag name clashes with a namespace name, issue an error and
2934 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002935 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002936 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002937 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002938 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002939 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002940 } else {
2941 // The existing declaration isn't relevant to us; we're in a
2942 // new scope, so clear out the previous declaration.
2943 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002944 }
Chris Lattner4b009652007-07-25 00:24:17 +00002945 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002946 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2947 (Kind != TagDecl::TK_enum)) {
2948 // C++ [basic.scope.pdecl]p5:
2949 // -- for an elaborated-type-specifier of the form
2950 //
2951 // class-key identifier
2952 //
2953 // if the elaborated-type-specifier is used in the
2954 // decl-specifier-seq or parameter-declaration-clause of a
2955 // function defined in namespace scope, the identifier is
2956 // declared as a class-name in the namespace that contains
2957 // the declaration; otherwise, except as a friend
2958 // declaration, the identifier is declared in the smallest
2959 // non-class, non-function-prototype scope that contains the
2960 // declaration.
2961 //
2962 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2963 // C structs and unions.
2964
2965 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002966 // FIXME: We would like to maintain the current DeclContext as the
2967 // lexical context,
Douglas Gregorcab994d2009-01-09 22:42:13 +00002968 while (DC->isRecord())
2969 DC = DC->getParent();
2970 LexicalContext = DC;
2971
2972 // Find the scope where we'll be declaring the tag.
2973 while (S->isClassScope() ||
2974 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00002975 ((S->getFlags() & Scope::DeclScope) == 0) ||
2976 (S->getEntity() &&
2977 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00002978 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00002979 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002980
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002981CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002982
2983 // If there is an identifier, use the location of the identifier as the
2984 // location of the decl, otherwise use the location of the struct/union
2985 // keyword.
2986 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2987
Douglas Gregorae644892008-12-15 16:32:14 +00002988 // Otherwise, create a new declaration. If there is a previous
2989 // declaration of the same entity, the two will be linked via
2990 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00002991 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00002992
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002993 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002994 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2995 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00002996 New = EnumDecl::Create(Context, DC, Loc, Name,
2997 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002998 // If this is an undefined enum, warn.
2999 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003000 } else {
3001 // struct/union/class
3002
Chris Lattner4b009652007-07-25 00:24:17 +00003003 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3004 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003005 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003006 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00003007 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3008 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003009 else
Douglas Gregorae644892008-12-15 16:32:14 +00003010 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3011 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003012 }
Douglas Gregorae644892008-12-15 16:32:14 +00003013
3014 if (Kind != TagDecl::TK_enum) {
3015 // Handle #pragma pack: if the #pragma pack stack has non-default
3016 // alignment, make up a packed attribute for this decl. These
3017 // attributes are checked when the ASTContext lays out the
3018 // structure.
3019 //
3020 // It is important for implementing the correct semantics that this
3021 // happen here (in act on tag decl). The #pragma pack stack is
3022 // maintained as a result of parser callbacks which can occur at
3023 // many points during the parsing of a struct declaration (because
3024 // the #pragma tokens are effectively skipped over during the
3025 // parsing of the struct).
3026 if (unsigned Alignment = PackContext.getAlignment())
3027 New->addAttr(new PackedAttr(Alignment * 8));
3028 }
3029
Douglas Gregorb31f2942009-01-28 17:15:10 +00003030 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3031 // C++ [dcl.typedef]p3:
3032 // [...] Similarly, in a given scope, a class or enumeration
3033 // shall not be declared with the same name as a typedef-name
3034 // that is declared in that scope and refers to a type other
3035 // than the class or enumeration itself.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003036 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregorb31f2942009-01-28 17:15:10 +00003037 TypedefDecl *PrevTypedef = 0;
3038 if (Lookup.getKind() == LookupResult::Found)
3039 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3040
3041 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3042 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3043 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3044 Diag(Loc, diag::err_tag_definition_of_typedef)
3045 << Context.getTypeDeclType(New)
3046 << PrevTypedef->getUnderlyingType();
3047 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3048 Invalid = true;
3049 }
3050 }
3051
Douglas Gregor98b27542009-01-17 00:42:38 +00003052 if (Invalid)
3053 New->setInvalidDecl();
3054
Douglas Gregorae644892008-12-15 16:32:14 +00003055 if (Attr)
3056 ProcessDeclAttributeList(New, Attr);
3057
Douglas Gregor98b27542009-01-17 00:42:38 +00003058 // If we're declaring or defining a tag in function prototype scope
3059 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003060 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3061 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3062
Douglas Gregorae644892008-12-15 16:32:14 +00003063 // Set the lexical context. If the tag has a C++ scope specifier, the
3064 // lexical context will be different from the semantic context.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003065 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003066
3067 if (TK == TK_Definition)
3068 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003069
3070 // If this has an identifier, add it to the scope stack.
3071 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003072 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003073
3074 // Add it to the decl chain.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003075 if (LexicalContext != CurContext) {
3076 // FIXME: PushOnScopeChains should not rely on CurContext!
3077 DeclContext *OldContext = CurContext;
3078 CurContext = LexicalContext;
3079 PushOnScopeChains(New, S);
3080 CurContext = OldContext;
3081 } else
3082 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003083 } else {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003084 LexicalContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003085 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003086
Chris Lattner4b009652007-07-25 00:24:17 +00003087 return New;
3088}
3089
Douglas Gregordb568cf2009-01-08 20:45:30 +00003090void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3091 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3092
3093 // Enter the tag context.
3094 PushDeclContext(S, Tag);
3095
3096 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3097 FieldCollector->StartClass();
3098
3099 if (Record->getIdentifier()) {
3100 // C++ [class]p2:
3101 // [...] The class-name is also inserted into the scope of the
3102 // class itself; this is known as the injected-class-name. For
3103 // purposes of access checking, the injected-class-name is treated
3104 // as if it were a public member name.
3105 RecordDecl *InjectedClassName
3106 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3107 CurContext, Record->getLocation(),
3108 Record->getIdentifier(), Record);
3109 InjectedClassName->setImplicit();
3110 PushOnScopeChains(InjectedClassName, S);
3111 }
3112 }
3113}
3114
3115void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3116 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3117
3118 if (isa<CXXRecordDecl>(Tag))
3119 FieldCollector->FinishClass();
3120
3121 // Exit this scope of this tag's definition.
3122 PopDeclContext();
3123
3124 // Notify the consumer that we've defined a tag.
3125 Consumer.HandleTagDeclDefinition(Tag);
3126}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003127
Chris Lattnera73e2202008-11-12 21:17:48 +00003128/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3129/// types into constant array types in certain situations which would otherwise
3130/// be errors (for GCC compatibility).
3131static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3132 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003133 // This method tries to turn a variable array into a constant
3134 // array even when the size isn't an ICE. This is necessary
3135 // for compatibility with code that depends on gcc's buggy
3136 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003137 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3138 if (!VLATy) return QualType();
3139
Anders Carlsson8c3de802008-12-19 20:58:05 +00003140 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003141 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003142 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003143 return QualType();
3144
Anders Carlsson8c3de802008-12-19 20:58:05 +00003145 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3146 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003147 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3148 return Context.getConstantArrayType(VLATy->getElementType(),
3149 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003150 return QualType();
3151}
3152
Anders Carlsson108229a2008-12-06 20:33:04 +00003153bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003154 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003155 // FIXME: 6.7.2.1p4 - verify the field type.
3156
3157 llvm::APSInt Value;
3158 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3159 return true;
3160
Chris Lattner8464c372008-12-12 04:56:04 +00003161 // Zero-width bitfield is ok for anonymous field.
3162 if (Value == 0 && FieldName)
3163 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3164
3165 if (Value.isNegative())
3166 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003167
3168 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3169 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003170 if (TypeSize && Value.getZExtValue() > TypeSize)
3171 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3172 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003173
3174 return false;
3175}
3176
Steve Naroff0acc9c92007-09-15 18:49:24 +00003177/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003178/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003179Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003180 SourceLocation DeclStart,
3181 Declarator &D, ExprTy *BitfieldWidth) {
3182 IdentifierInfo *II = D.getIdentifier();
3183 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003184 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003185 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003186 if (II) Loc = D.getIdentifierLoc();
3187
3188 // FIXME: Unnamed fields can be handled in various different ways, for
3189 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003190
Chris Lattner4b009652007-07-25 00:24:17 +00003191 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003192 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3193 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003194
Chris Lattner4b009652007-07-25 00:24:17 +00003195 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3196 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003197 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003198 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003199 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003200 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003201 T = FixedTy;
3202 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003203 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003204 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003205 InvalidDecl = true;
3206 }
Chris Lattner4b009652007-07-25 00:24:17 +00003207 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003208
3209 if (BitWidth) {
3210 if (VerifyBitField(Loc, II, T, BitWidth))
3211 InvalidDecl = true;
3212 } else {
3213 // Not a bitfield.
3214
3215 // validate II.
3216
3217 }
3218
Chris Lattner4b009652007-07-25 00:24:17 +00003219 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003220 FieldDecl *NewFD;
3221
Douglas Gregor8acb7272008-12-11 16:49:14 +00003222 NewFD = FieldDecl::Create(Context, Record,
3223 Loc, II, T, BitWidth,
3224 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003225 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003226
Douglas Gregordb568cf2009-01-08 20:45:30 +00003227 if (II) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003228 Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003229 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3230 && !isa<TagDecl>(PrevDecl)) {
3231 Diag(Loc, diag::err_duplicate_member) << II;
3232 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3233 NewFD->setInvalidDecl();
3234 Record->setInvalidDecl();
3235 }
3236 }
3237
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003238 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003239 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003240 if (!T->isPODType())
3241 cast<CXXRecordDecl>(Record)->setPOD(false);
3242 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003243
Chris Lattner9b384ca2008-06-29 00:02:00 +00003244 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003245
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003246 if (D.getInvalidType() || InvalidDecl)
3247 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003248
Douglas Gregordb568cf2009-01-08 20:45:30 +00003249 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003250 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003251 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003252 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003253
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003254 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003255}
3256
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003257/// TranslateIvarVisibility - Translate visibility from a token ID to an
3258/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003259static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003260TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003261 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003262 default: assert(0 && "Unknown visitibility kind");
3263 case tok::objc_private: return ObjCIvarDecl::Private;
3264 case tok::objc_public: return ObjCIvarDecl::Public;
3265 case tok::objc_protected: return ObjCIvarDecl::Protected;
3266 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003267 }
3268}
3269
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003270/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3271/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003272Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003273 SourceLocation DeclStart,
3274 Declarator &D, ExprTy *BitfieldWidth,
3275 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003276
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003277 IdentifierInfo *II = D.getIdentifier();
3278 Expr *BitWidth = (Expr*)BitfieldWidth;
3279 SourceLocation Loc = DeclStart;
3280 if (II) Loc = D.getIdentifierLoc();
3281
3282 // FIXME: Unnamed fields can be handled in various different ways, for
3283 // example, unnamed unions inject all members into the struct namespace!
3284
Anders Carlsson108229a2008-12-06 20:33:04 +00003285 QualType T = GetTypeForDeclarator(D, S);
3286 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3287 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003288
3289 if (BitWidth) {
3290 // TODO: Validate.
3291 //printf("WARNING: BITFIELDS IGNORED!\n");
3292
3293 // 6.7.2.1p3
3294 // 6.7.2.1p4
3295
3296 } else {
3297 // Not a bitfield.
3298
3299 // validate II.
3300
3301 }
3302
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003303 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3304 // than a variably modified type.
3305 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003306 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003307 InvalidDecl = true;
3308 }
3309
Ted Kremenek173dd312008-07-23 18:04:17 +00003310 // Get the visibility (access control) for this ivar.
3311 ObjCIvarDecl::AccessControl ac =
3312 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3313 : ObjCIvarDecl::None;
3314
3315 // Construct the decl.
3316 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003317 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003318
Douglas Gregordb568cf2009-01-08 20:45:30 +00003319 if (II) {
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003320 Decl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003321 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3322 && !isa<TagDecl>(PrevDecl)) {
3323 Diag(Loc, diag::err_duplicate_member) << II;
3324 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3325 NewID->setInvalidDecl();
3326 }
3327 }
3328
Ted Kremenek173dd312008-07-23 18:04:17 +00003329 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003330 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003331
3332 if (D.getInvalidType() || InvalidDecl)
3333 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003334
Douglas Gregordb568cf2009-01-08 20:45:30 +00003335 if (II) {
3336 // FIXME: When interfaces are DeclContexts, we'll need to add
3337 // these to the interface.
3338 S->AddDecl(NewID);
3339 IdResolver.AddDecl(NewID);
3340 }
3341
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003342 return NewID;
3343}
3344
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003345void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003346 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003347 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003348 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003349 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003350 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3351 assert(EnclosingDecl && "missing record or interface decl");
3352 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3353
Chris Lattner4b009652007-07-25 00:24:17 +00003354 // Verify that all the fields are okay.
3355 unsigned NumNamedMembers = 0;
3356 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003357
Chris Lattner4b009652007-07-25 00:24:17 +00003358 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003359 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3360 assert(FD && "missing field decl");
3361
Chris Lattner4b009652007-07-25 00:24:17 +00003362 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003363 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003364
Douglas Gregordb568cf2009-01-08 20:45:30 +00003365 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003366 // Remember all fields written by the user.
3367 RecFields.push_back(FD);
3368 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003369
Chris Lattner4b009652007-07-25 00:24:17 +00003370 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003371 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003372 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003373 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003374 FD->setInvalidDecl();
3375 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003376 continue;
3377 }
Chris Lattner4b009652007-07-25 00:24:17 +00003378 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3379 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003380 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003381 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3382 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003383 FD->setInvalidDecl();
3384 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003385 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003386 }
Chris Lattner4b009652007-07-25 00:24:17 +00003387 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003388 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003389 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003390 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3391 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003392 FD->setInvalidDecl();
3393 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003394 continue;
3395 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003396 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003397 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003398 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003399 FD->setInvalidDecl();
3400 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003401 continue;
3402 }
Chris Lattner4b009652007-07-25 00:24:17 +00003403 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003404 if (Record)
3405 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003406 }
Chris Lattner4b009652007-07-25 00:24:17 +00003407 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3408 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003409 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003410 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3411 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003412 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003413 Record->setHasFlexibleArrayMember(true);
3414 } else {
3415 // If this is a struct/class and this is not the last element, reject
3416 // it. Note that GCC supports variable sized arrays in the middle of
3417 // structures.
3418 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003419 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
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 // We support flexible arrays at the end of structs in other structs
3426 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003427 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003428 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003429 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003430 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003431 }
3432 }
3433 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003434 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003435 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003436 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003437 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003438 FD->setInvalidDecl();
3439 EnclosingDecl->setInvalidDecl();
3440 continue;
3441 }
Chris Lattner4b009652007-07-25 00:24:17 +00003442 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003443 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003444 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003445 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003446
Chris Lattner4b009652007-07-25 00:24:17 +00003447 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003448 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003449 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003450 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003451 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003452 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003453 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003454 // Must enforce the rule that ivars in the base classes may not be
3455 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003456 if (ID->getSuperClass()) {
3457 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3458 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3459 ObjCIvarDecl* Ivar = (*IVI);
3460 IdentifierInfo *II = Ivar->getIdentifier();
3461 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3462 if (prevIvar) {
3463 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003464 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003465 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003466 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003467 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003468 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003469 else if (ObjCImplementationDecl *IMPDecl =
3470 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003471 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3472 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003473 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003474 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003475 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003476
3477 if (Attr)
3478 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003479}
3480
Steve Naroff0acc9c92007-09-15 18:49:24 +00003481Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003482 DeclTy *lastEnumConst,
3483 SourceLocation IdLoc, IdentifierInfo *Id,
3484 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003485 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003486 EnumConstantDecl *LastEnumConst =
3487 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3488 Expr *Val = static_cast<Expr*>(val);
3489
Chris Lattnera7549902007-08-26 06:24:45 +00003490 // The scope passed in may not be a decl scope. Zip up the scope tree until
3491 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003492 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003493
Chris Lattner4b009652007-07-25 00:24:17 +00003494 // Verify that there isn't already something declared with this name in this
3495 // scope.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003496 Decl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003497 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003498 // Maybe we will complain about the shadowed template parameter.
3499 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3500 // Just pretend that we didn't see the previous declaration.
3501 PrevDecl = 0;
3502 }
3503
3504 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003505 // When in C++, we may get a TagDecl with the same name; in this case the
3506 // enum constant will 'hide' the tag.
3507 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3508 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003509 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003510 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003511 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003512 else
Chris Lattner65cae292008-11-19 08:23:25 +00003513 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003514 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003515 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003516 return 0;
3517 }
3518 }
3519
3520 llvm::APSInt EnumVal(32);
3521 QualType EltTy;
3522 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003523 // Make sure to promote the operand type to int.
3524 UsualUnaryConversions(Val);
3525
Chris Lattner4b009652007-07-25 00:24:17 +00003526 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3527 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003528 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003529 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003530 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003531 } else {
3532 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003533 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003534 }
3535
3536 if (!Val) {
3537 if (LastEnumConst) {
3538 // Assign the last value + 1.
3539 EnumVal = LastEnumConst->getInitVal();
3540 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003541
3542 // Check for overflow on increment.
3543 if (EnumVal < LastEnumConst->getInitVal())
3544 Diag(IdLoc, diag::warn_enum_value_overflow);
3545
Chris Lattnere7f53a42007-08-27 17:37:24 +00003546 EltTy = LastEnumConst->getType();
3547 } else {
3548 // First value, set to zero.
3549 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003550 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003551 }
Chris Lattner4b009652007-07-25 00:24:17 +00003552 }
3553
Chris Lattnere4650482008-03-15 06:12:44 +00003554 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003555 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003556 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003557
3558 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003559 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003560
Chris Lattner4b009652007-07-25 00:24:17 +00003561 return New;
3562}
3563
Steve Naroffb0726b82008-08-07 14:08:16 +00003564// FIXME: For consistency with ActOnFields(), we should have the parser
3565// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003566void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003567 DeclTy **Elements, unsigned NumElements) {
3568 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003569 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003570
Chris Lattner435c3fd2007-08-28 05:10:31 +00003571 // TODO: If the result value doesn't fit in an int, it must be a long or long
3572 // long value. ISO C does not support this, but GCC does as an extension,
3573 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003574 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003575
Chris Lattner206754a2007-08-28 06:15:15 +00003576 // Verify that all the values are okay, compute the size of the values, and
3577 // reverse the list.
3578 unsigned NumNegativeBits = 0;
3579 unsigned NumPositiveBits = 0;
3580
3581 // Keep track of whether all elements have type int.
3582 bool AllElementsInt = true;
3583
Chris Lattner4b009652007-07-25 00:24:17 +00003584 for (unsigned i = 0; i != NumElements; ++i) {
3585 EnumConstantDecl *ECD =
3586 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3587 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003588
3589 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003590 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003591 assert(InitVal.getBitWidth() >= IntWidth &&
3592 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003593 if (InitVal.getBitWidth() > IntWidth) {
3594 llvm::APSInt V(InitVal);
3595 V.trunc(IntWidth);
3596 V.extend(InitVal.getBitWidth());
3597 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003598 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3599 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003600 }
Chris Lattner206754a2007-08-28 06:15:15 +00003601
3602 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003603 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003604 NumPositiveBits = std::max(NumPositiveBits,
3605 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003606 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003607 NumNegativeBits = std::max(NumNegativeBits,
3608 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003609
Chris Lattner206754a2007-08-28 06:15:15 +00003610 // Keep track of whether every enum element has type int (very commmon).
3611 if (AllElementsInt)
3612 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003613 }
3614
Chris Lattner206754a2007-08-28 06:15:15 +00003615 // Figure out the type that should be used for this enum.
3616 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3617 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003618 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003619
3620 if (NumNegativeBits) {
3621 // If there is a negative value, figure out the smallest integer type (of
3622 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003623 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003624 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003625 BestWidth = IntWidth;
3626 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003627 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003628
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003629 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003630 BestType = Context.LongTy;
3631 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003632 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003633
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003634 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003635 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3636 BestType = Context.LongLongTy;
3637 }
3638 }
3639 } else {
3640 // If there is no negative value, figure out which of uint, ulong, ulonglong
3641 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003642 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003643 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003644 BestWidth = IntWidth;
3645 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003646 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003647 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003648 } else {
3649 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003650 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003651 "How could an initializer get larger than ULL?");
3652 BestType = Context.UnsignedLongLongTy;
3653 }
3654 }
3655
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003656 // Loop over all of the enumerator constants, changing their types to match
3657 // the type of the enum if needed.
3658 for (unsigned i = 0; i != NumElements; ++i) {
3659 EnumConstantDecl *ECD =
3660 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3661 if (!ECD) continue; // Already issued a diagnostic.
3662
3663 // Standard C says the enumerators have int type, but we allow, as an
3664 // extension, the enumerators to be larger than int size. If each
3665 // enumerator value fits in an int, type it as an int, otherwise type it the
3666 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3667 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003668 if (ECD->getType() == Context.IntTy) {
3669 // Make sure the init value is signed.
3670 llvm::APSInt IV = ECD->getInitVal();
3671 IV.setIsSigned(true);
3672 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003673
3674 if (getLangOptions().CPlusPlus)
3675 // C++ [dcl.enum]p4: Following the closing brace of an
3676 // enum-specifier, each enumerator has the type of its
3677 // enumeration.
3678 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003679 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003680 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003681
3682 // Determine whether the value fits into an int.
3683 llvm::APSInt InitVal = ECD->getInitVal();
3684 bool FitsInInt;
3685 if (InitVal.isUnsigned() || !InitVal.isNegative())
3686 FitsInInt = InitVal.getActiveBits() < IntWidth;
3687 else
3688 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3689
3690 // If it fits into an integer type, force it. Otherwise force it to match
3691 // the enum decl type.
3692 QualType NewTy;
3693 unsigned NewWidth;
3694 bool NewSign;
3695 if (FitsInInt) {
3696 NewTy = Context.IntTy;
3697 NewWidth = IntWidth;
3698 NewSign = true;
3699 } else if (ECD->getType() == BestType) {
3700 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003701 if (getLangOptions().CPlusPlus)
3702 // C++ [dcl.enum]p4: Following the closing brace of an
3703 // enum-specifier, each enumerator has the type of its
3704 // enumeration.
3705 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003706 continue;
3707 } else {
3708 NewTy = BestType;
3709 NewWidth = BestWidth;
3710 NewSign = BestType->isSignedIntegerType();
3711 }
3712
3713 // Adjust the APSInt value.
3714 InitVal.extOrTrunc(NewWidth);
3715 InitVal.setIsSigned(NewSign);
3716 ECD->setInitVal(InitVal);
3717
3718 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003719 if (ECD->getInitExpr())
3720 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3721 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003722 if (getLangOptions().CPlusPlus)
3723 // C++ [dcl.enum]p4: Following the closing brace of an
3724 // enum-specifier, each enumerator has the type of its
3725 // enumeration.
3726 ECD->setType(EnumType);
3727 else
3728 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003729 }
Chris Lattner206754a2007-08-28 06:15:15 +00003730
Douglas Gregor8acb7272008-12-11 16:49:14 +00003731 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003732}
3733
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003734Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003735 ExprArg expr) {
3736 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3737
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003738 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003739}
3740
Douglas Gregorad17e372008-12-16 22:23:02 +00003741
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003742void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3743 ExprTy *alignment, SourceLocation PragmaLoc,
3744 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3745 Expr *Alignment = static_cast<Expr *>(alignment);
3746
3747 // If specified then alignment must be a "small" power of two.
3748 unsigned AlignmentVal = 0;
3749 if (Alignment) {
3750 llvm::APSInt Val;
3751 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3752 !Val.isPowerOf2() ||
3753 Val.getZExtValue() > 16) {
3754 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3755 delete Alignment;
3756 return; // Ignore
3757 }
3758
3759 AlignmentVal = (unsigned) Val.getZExtValue();
3760 }
3761
3762 switch (Kind) {
3763 case Action::PPK_Default: // pack([n])
3764 PackContext.setAlignment(AlignmentVal);
3765 break;
3766
3767 case Action::PPK_Show: // pack(show)
3768 // Show the current alignment, making sure to show the right value
3769 // for the default.
3770 AlignmentVal = PackContext.getAlignment();
3771 // FIXME: This should come from the target.
3772 if (AlignmentVal == 0)
3773 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003774 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003775 break;
3776
3777 case Action::PPK_Push: // pack(push [, id] [, [n])
3778 PackContext.push(Name);
3779 // Set the new alignment if specified.
3780 if (Alignment)
3781 PackContext.setAlignment(AlignmentVal);
3782 break;
3783
3784 case Action::PPK_Pop: // pack(pop [, id] [, n])
3785 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3786 // "#pragma pack(pop, identifier, n) is undefined"
3787 if (Alignment && Name)
3788 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3789
3790 // Do the pop.
3791 if (!PackContext.pop(Name)) {
3792 // If a name was specified then failure indicates the name
3793 // wasn't found. Otherwise failure indicates the stack was
3794 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003795 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3796 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003797
3798 // FIXME: Warn about popping named records as MSVC does.
3799 } else {
3800 // Pop succeeded, set the new alignment if specified.
3801 if (Alignment)
3802 PackContext.setAlignment(AlignmentVal);
3803 }
3804 break;
3805
3806 default:
3807 assert(0 && "Invalid #pragma pack kind.");
3808 }
3809}
3810
3811bool PragmaPackStack::pop(IdentifierInfo *Name) {
3812 if (Stack.empty())
3813 return false;
3814
3815 // If name is empty just pop top.
3816 if (!Name) {
3817 Alignment = Stack.back().first;
3818 Stack.pop_back();
3819 return true;
3820 }
3821
3822 // Otherwise, find the named record.
3823 for (unsigned i = Stack.size(); i != 0; ) {
3824 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003825 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003826 // Found it, pop up to and including this record.
3827 Alignment = Stack[i].first;
3828 Stack.erase(Stack.begin() + i, Stack.end());
3829 return true;
3830 }
3831 }
3832
3833 return false;
3834}