blob: 7ccc13c97d15e50083df85f922309f2cb3ddeb34 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner6953a072008-06-26 18:38:35 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000031
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Douglas Gregorf2dbdca2009-02-04 19:16:12 +000034/// \brief If the identifier refers to a type name within this scope,
35/// return the declaration of that type.
36///
37/// This routine performs ordinary name lookup of the identifier II
38/// within the given scope, with optional C++ scope specifier SS, to
39/// determine whether the name refers to a type. If so, returns the
40/// declaration corresponding to that type. Otherwise, returns NULL.
41///
42/// If name lookup results in an ambiguity, this routine will complain
43/// and then return NULL.
44Sema::DeclTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor1075a162009-02-04 17:00:24 +000045 Scope *S, const CXXScopeSpec *SS) {
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000046 Decl *IIDecl = 0;
Douglas Gregor52ae30c2009-01-30 01:04:22 +000047 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000048 switch (Result.getKind()) {
Steve Naroffa4e04982009-01-29 18:09:31 +000049 case LookupResult::NotFound:
50 case LookupResult::FoundOverloaded:
Douglas Gregor1075a162009-02-04 17:00:24 +000051 return 0;
52
Steve Naroffa4e04982009-01-29 18:09:31 +000053 case LookupResult::AmbiguousBaseSubobjectTypes:
54 case LookupResult::AmbiguousBaseSubobjects:
Douglas Gregor7a7be652009-02-03 19:21:40 +000055 case LookupResult::AmbiguousReference:
Douglas Gregor1075a162009-02-04 17:00:24 +000056 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
Steve Naroffa4e04982009-01-29 18:09:31 +000057 return 0;
Douglas Gregor1075a162009-02-04 17:00:24 +000058
Steve Naroffa4e04982009-01-29 18:09:31 +000059 case LookupResult::Found:
60 IIDecl = Result.getAsDecl();
61 break;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000062 }
63
Steve Naroffa4e04982009-01-29 18:09:31 +000064 if (IIDecl) {
65 if (isa<TypedefDecl>(IIDecl) ||
66 isa<ObjCInterfaceDecl>(IIDecl) ||
67 isa<TagDecl>(IIDecl) ||
68 isa<TemplateTypeParmDecl>(IIDecl))
69 return IIDecl;
70 }
Steve Naroff81f1bba2007-09-06 21:24:23 +000071 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000072}
73
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000074DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000075 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000076 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000077 if (MD->isOutOfLineDefinition())
78 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000079
80 // A C++ inline method is parsed *after* the topmost class it was declared in
81 // is fully parsed (it's "complete").
82 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000083 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000084 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
85 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000086 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000087 DC = RD;
88
89 // Return the declaration context of the topmost class the inline method is
90 // declared in.
91 return DC;
92 }
93
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000094 if (isa<ObjCMethodDecl>(DC))
95 return Context.getTranslationUnitDecl();
96
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000097 if (Decl *D = dyn_cast<Decl>(DC))
98 return D->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000099
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +0000100 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000101}
102
Douglas Gregor8acb7272008-12-11 16:49:14 +0000103void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000104 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +0000105 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000106 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000107 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000108}
109
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000110void Sema::PopDeclContext() {
111 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000112
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000113 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000114}
115
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000116/// Add this decl to the scope shadowed decl chains.
117void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000118 // Move up the scope chain until we find the nearest enclosing
119 // non-transparent context. The declaration will be introduced into this
120 // scope.
121 while (S->getEntity() &&
122 ((DeclContext *)S->getEntity())->isTransparentContext())
123 S = S->getParent();
124
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000125 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000126
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000127 // Add scoped declarations into their context, so that they can be
128 // found later. Declarations without a context won't be inserted
129 // into any context.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000130 CurContext->addDecl(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000131
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000132 // C++ [basic.scope]p4:
133 // -- exactly one declaration shall declare a class name or
134 // enumeration name that is not a typedef name and the other
135 // declarations shall all refer to the same object or
136 // enumerator, or all refer to functions and function templates;
137 // in this case the class name or enumeration name is hidden.
138 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
139 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000140 if (CurContext->getLookupContext()
141 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000142 // We're pushing the tag into the current context, which might
143 // require some reshuffling in the identifier resolver.
144 IdentifierResolver::iterator
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000145 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000146 IEnd = IdResolver.end();
147 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
148 NamedDecl *PrevDecl = *I;
149 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
150 PrevDecl = *I, ++I) {
151 if (TD->declarationReplaces(*I)) {
152 // This is a redeclaration. Remove it from the chain and
153 // break out, so that we'll add in the shadowed
154 // declaration.
155 S->RemoveDecl(*I);
156 if (PrevDecl == *I) {
157 IdResolver.RemoveDecl(*I);
158 IdResolver.AddDecl(TD);
159 return;
160 } else {
161 IdResolver.RemoveDecl(*I);
162 break;
163 }
164 }
165 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000166
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000167 // There is already a declaration with the same name in the same
168 // scope, which is not a tag declaration. It must be found
169 // before we find the new declaration, so insert the new
170 // declaration at the end of the chain.
171 IdResolver.AddShadowedDecl(TD, PrevDecl);
172
173 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000174 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000175 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000176 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000177 // We are pushing the name of a function, which might be an
178 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000179 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000180 IdentifierResolver::iterator Redecl
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000181 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000182 IdResolver.end(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000192
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000194}
195
Steve Naroff9637a9b2007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000200
Chris Lattner4b009652007-07-25 00:24:17 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000205
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000210
Douglas Gregor8acb7272008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000213 }
214}
215
Steve Naroffe57c21a2008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Douglas Gregor09be81b2009-02-04 17:27:36 +0000221 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222
Steve Naroff6384a012008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000224}
225
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Chris Lattnera9c87f22008-05-05 22:18:14 +0000258void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000259 if (!Context.getBuiltinVaListType().isNull())
260 return;
261
262 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor09be81b2009-02-04 17:27:36 +0000263 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000264 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000265 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
266}
267
Chris Lattner4b009652007-07-25 00:24:17 +0000268/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
269/// lazily create a decl for it.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000270NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
271 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000272 Builtin::ID BID = (Builtin::ID)bid;
273
Chris Lattnerb23469f2008-09-28 05:54:29 +0000274 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000275 InitBuiltinVaListType();
276
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000277 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000278 FunctionDecl *New = FunctionDecl::Create(Context,
279 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000280 SourceLocation(), II, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000281 FunctionDecl::Extern, false);
Chris Lattner4b009652007-07-25 00:24:17 +0000282
Chris Lattnera9c87f22008-05-05 22:18:14 +0000283 // Create Decl objects for each parameter, adding them to the
284 // FunctionDecl.
285 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
286 llvm::SmallVector<ParmVarDecl*, 16> Params;
287 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
288 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000289 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000290 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000291 }
292
293
294
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000295 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000296 // FIXME: This is hideous. We need to teach PushOnScopeChains to
297 // relate Scopes to DeclContexts, and probably eliminate CurContext
298 // entirely, but we're not there yet.
299 DeclContext *SavedContext = CurContext;
300 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000301 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000302 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000303 return New;
304}
305
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000306/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
307/// everything from the standard library is defined.
308NamespaceDecl *Sema::GetStdNamespace() {
309 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000310 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000311 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000312 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000313 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
314 }
315 return StdNamespace;
316}
317
Chris Lattner4b009652007-07-25 00:24:17 +0000318/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
319/// and scope as a previous declaration 'Old'. Figure out how to resolve this
320/// situation, merging decls or emitting diagnostics as appropriate.
321///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000322TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000323 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000324 // Allow multiple definitions for ObjC built-in typedefs.
325 // FIXME: Verify the underlying types are equivalent!
326 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000327 const IdentifierInfo *TypeID = New->getIdentifier();
328 switch (TypeID->getLength()) {
329 default: break;
330 case 2:
331 if (!TypeID->isStr("id"))
332 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000333 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000334 objc_types = true;
335 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000336 case 5:
337 if (!TypeID->isStr("Class"))
338 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000339 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000340 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000341 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000342 case 3:
343 if (!TypeID->isStr("SEL"))
344 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000345 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000346 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000347 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000348 case 8:
349 if (!TypeID->isStr("Protocol"))
350 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000351 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000352 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000353 return New;
354 }
355 // Fall through - the typedef name was not a builtin type.
356 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000357 // Verify the old decl was also a type.
358 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattner4b009652007-07-25 00:24:17 +0000359 if (!Old) {
Douglas Gregorb31f2942009-01-28 17:15:10 +0000360 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000361 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000362 if (!objc_types)
363 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000364 return New;
365 }
Douglas Gregorb31f2942009-01-28 17:15:10 +0000366
367 // Determine the "old" type we'll use for checking and diagnostics.
368 QualType OldType;
369 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
370 OldType = OldTypedef->getUnderlyingType();
371 else
372 OldType = Context.getTypeDeclType(Old);
373
Chris Lattnerbef8d622008-07-25 18:44:27 +0000374 // If the typedef types are not identical, reject them in all languages and
375 // with any extensions enabled.
Douglas Gregorb31f2942009-01-28 17:15:10 +0000376
377 if (OldType != New->getUnderlyingType() &&
378 Context.getCanonicalType(OldType) !=
Chris Lattnerbef8d622008-07-25 18:44:27 +0000379 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000380 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorb31f2942009-01-28 17:15:10 +0000381 << New->getUnderlyingType() << OldType;
Fariborz Jahaniande939672009-01-16 19:58:32 +0000382 if (!objc_types)
383 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000384 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000385 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000386 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000387 if (getLangOptions().Microsoft) return New;
388
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000389 // C++ [dcl.typedef]p2:
390 // In a given non-class scope, a typedef specifier can be used to
391 // redefine the name of any type declared in that scope to refer
392 // to the type to which it already refers.
393 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
394 return New;
395
396 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000397 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
398 // *either* declaration is in a system header. The code below implements
399 // this adhoc compatibility rule. FIXME: The following code will not
400 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000401 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
402 SourceManager &SrcMgr = Context.getSourceManager();
403 if (SrcMgr.isInSystemHeader(Old->getLocation()))
404 return New;
405 if (SrcMgr.isInSystemHeader(New->getLocation()))
406 return New;
407 }
Eli Friedman324d5032008-06-11 06:20:39 +0000408
Chris Lattnerb1753422008-11-23 21:45:46 +0000409 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000410 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000411 return New;
412}
413
Chris Lattner6953a072008-06-26 18:38:35 +0000414/// DeclhasAttr - returns true if decl Declaration already has the target
415/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000416static bool DeclHasAttr(const Decl *decl, const Attr *target) {
417 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
418 if (attr->getKind() == target->getKind())
419 return true;
420
421 return false;
422}
423
424/// MergeAttributes - append attributes from the Old decl to the New one.
425static void MergeAttributes(Decl *New, Decl *Old) {
426 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
427
Chris Lattner402b3372008-03-03 03:28:21 +0000428 while (attr) {
429 tmp = attr;
430 attr = attr->getNext();
431
432 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000433 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000434 New->addAttr(tmp);
435 } else {
436 tmp->setNext(0);
437 delete(tmp);
438 }
439 }
Nuno Lopes77654342008-06-01 22:53:53 +0000440
441 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000442}
443
Chris Lattner3e254fb2008-04-08 04:40:51 +0000444/// MergeFunctionDecl - We just parsed a function 'New' from
445/// declarator D which has the same name and scope as a previous
446/// declaration 'Old'. Figure out how to resolve this situation,
447/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000448/// Redeclaration will be set true if this New is a redeclaration OldD.
449///
450/// In C++, New and Old must be declarations that are not
451/// overloaded. Use IsOverload to determine whether New and Old are
452/// overloaded, and to select the Old declaration that New should be
453/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000454FunctionDecl *
455Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000456 assert(!isa<OverloadedFunctionDecl>(OldD) &&
457 "Cannot merge with an overloaded function declaration");
458
Douglas Gregor42214c52008-04-21 02:02:58 +0000459 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000460 // Verify the old decl was also a function.
461 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
462 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000463 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000464 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000465 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000466 return New;
467 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000468
469 // Determine whether the previous declaration was a definition,
470 // implicit declaration, or a declaration.
471 diag::kind PrevDiag;
472 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000473 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000474 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000475 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000476 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000477 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000478
Chris Lattner42a21742008-04-06 23:10:54 +0000479 QualType OldQType = Context.getCanonicalType(Old->getType());
480 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000481
Douglas Gregord2baafd2008-10-21 16:13:35 +0000482 if (getLangOptions().CPlusPlus) {
483 // (C++98 13.1p2):
484 // Certain function declarations cannot be overloaded:
485 // -- Function declarations that differ only in the return type
486 // cannot be overloaded.
487 QualType OldReturnType
488 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
489 QualType NewReturnType
490 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
491 if (OldReturnType != NewReturnType) {
492 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
493 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000494 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000495 return New;
496 }
497
498 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
499 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
500 if (OldMethod && NewMethod) {
501 // -- Member function declarations with the same name and the
502 // same parameter types cannot be overloaded if any of them
503 // is a static member function declaration.
504 if (OldMethod->isStatic() || NewMethod->isStatic()) {
505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
506 Diag(Old->getLocation(), PrevDiag);
507 return New;
508 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000509
510 // C++ [class.mem]p1:
511 // [...] A member shall not be declared twice in the
512 // member-specification, except that a nested class or member
513 // class template can be declared and then later defined.
514 if (OldMethod->getLexicalDeclContext() ==
515 NewMethod->getLexicalDeclContext()) {
516 unsigned NewDiag;
517 if (isa<CXXConstructorDecl>(OldMethod))
518 NewDiag = diag::err_constructor_redeclared;
519 else if (isa<CXXDestructorDecl>(NewMethod))
520 NewDiag = diag::err_destructor_redeclared;
521 else if (isa<CXXConversionDecl>(NewMethod))
522 NewDiag = diag::err_conv_function_redeclared;
523 else
524 NewDiag = diag::err_member_redeclared;
525
526 Diag(New->getLocation(), NewDiag);
527 Diag(Old->getLocation(), PrevDiag);
528 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000529 }
530
531 // (C++98 8.3.5p3):
532 // All declarations for a function shall agree exactly in both the
533 // return type and the parameter-type-list.
534 if (OldQType == NewQType) {
535 // We have a redeclaration.
536 MergeAttributes(New, Old);
537 Redeclaration = true;
538 return MergeCXXFunctionDecl(New, Old);
539 }
540
541 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000542 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000543
544 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000545 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000546 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000547 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000548 MergeAttributes(New, Old);
549 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000550 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000551 }
Chris Lattner1470b072007-11-06 06:07:26 +0000552
Steve Naroff6c9e7922008-01-16 15:01:34 +0000553 // A function that has already been declared has been redeclared or defined
554 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000555
Chris Lattner4b009652007-07-25 00:24:17 +0000556 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
557 // TODO: This is totally simplistic. It should handle merging functions
558 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000559 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000560 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000561 return New;
562}
563
Steve Naroffb5e78152008-08-08 17:50:35 +0000564/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000565static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000566 if (VD->isFileVarDecl())
567 return (!VD->getInit() &&
568 (VD->getStorageClass() == VarDecl::None ||
569 VD->getStorageClass() == VarDecl::Static));
570 return false;
571}
572
573/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
574/// when dealing with C "tentative" external object definitions (C99 6.9.2).
575void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
576 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000577 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000578
Douglas Gregor3a423132009-01-07 16:34:42 +0000579 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000580 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000581 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
582 E = IdResolver.end();
583 I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000584 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000585 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
586
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000587 // Handle the following case:
588 // int a[10];
589 // int a[]; - the code below makes sure we set the correct type.
590 // int a[11]; - this is an error, size isn't 10.
591 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
592 OldDecl->getType()->isConstantArrayType())
593 VD->setType(OldDecl->getType());
594
Steve Naroffb5e78152008-08-08 17:50:35 +0000595 // Check for "tentative" definitions. We can't accomplish this in
596 // MergeVarDecl since the initializer hasn't been attached.
597 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
598 continue;
599
600 // Handle __private_extern__ just like extern.
601 if (OldDecl->getStorageClass() != VarDecl::Extern &&
602 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
603 VD->getStorageClass() != VarDecl::Extern &&
604 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000605 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000606 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000607 }
608 }
609 }
610}
611
Chris Lattner4b009652007-07-25 00:24:17 +0000612/// MergeVarDecl - We just parsed a variable 'New' which has the same name
613/// and scope as a previous declaration 'Old'. Figure out how to resolve this
614/// situation, merging decls or emitting diagnostics as appropriate.
615///
Steve Naroffb5e78152008-08-08 17:50:35 +0000616/// Tentative definition rules (C99 6.9.2p2) are checked by
617/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
618/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000619///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000620VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000621 // Verify the old decl was also a variable.
622 VarDecl *Old = dyn_cast<VarDecl>(OldD);
623 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000624 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000625 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000626 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000627 return New;
628 }
Chris Lattner402b3372008-03-03 03:28:21 +0000629
630 MergeAttributes(New, Old);
631
Eli Friedman4a480d62009-01-24 23:49:55 +0000632 // Merge the types
633 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
634 if (MergedT.isNull()) {
Douglas Gregord1675382009-01-09 19:42:16 +0000635 Diag(New->getLocation(), diag::err_redefinition_different_type)
636 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000637 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000638 return New;
639 }
Eli Friedman4a480d62009-01-24 23:49:55 +0000640 New->setType(MergedT);
Steve Naroffb00247f2008-01-30 00:44:01 +0000641 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
642 if (New->getStorageClass() == VarDecl::Static &&
643 (Old->getStorageClass() == VarDecl::None ||
644 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000645 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000646 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000647 return New;
648 }
649 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
650 if (New->getStorageClass() != VarDecl::Static &&
651 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000652 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000653 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000654 return New;
655 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000656 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
657 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000658 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000659 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000660 }
661 return New;
662}
663
Chris Lattner3e254fb2008-04-08 04:40:51 +0000664/// CheckParmsForFunctionDef - Check that the parameters of the given
665/// function are appropriate for the definition of a function. This
666/// takes care of any checks that cannot be performed on the
667/// declaration itself, e.g., that the types of each of the function
668/// parameters are complete.
669bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
670 bool HasInvalidParm = false;
671 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
672 ParmVarDecl *Param = FD->getParamDecl(p);
673
674 // C99 6.7.5.3p4: the parameters in a parameter type list in a
675 // function declarator that is part of a function definition of
676 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000677 if (!Param->isInvalidDecl() &&
678 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
679 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000680 Param->setInvalidDecl();
681 HasInvalidParm = true;
682 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000683
684 // C99 6.9.1p5: If the declarator includes a parameter type list, the
685 // declaration of each parameter shall include an identifier.
686 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
687 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000688 }
689
690 return HasInvalidParm;
691}
692
Chris Lattner4b009652007-07-25 00:24:17 +0000693/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
694/// no declarator (e.g. "struct foo;") is parsed.
695Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000696 TagDecl *Tag
697 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
698 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
699 if (!Record->getDeclName() && Record->isDefinition() &&
700 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
701 return BuildAnonymousStructOrUnion(S, DS, Record);
702
703 // Microsoft allows unnamed struct/union fields. Don't complain
704 // about them.
705 // FIXME: Should we support Microsoft's extensions in this area?
706 if (Record->getDeclName() && getLangOptions().Microsoft)
707 return Tag;
708 }
709
Douglas Gregord406b032009-02-06 22:42:48 +0000710 if (!DS.isMissingDeclaratorOk() &&
711 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000712 // Warn about typedefs of enums without names, since this is an
713 // extension in both Microsoft an GNU.
Douglas Gregor72de8492009-01-17 02:55:50 +0000714 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
715 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregoredd94e92009-01-22 16:23:54 +0000716 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000717 << DS.getSourceRange();
718 return Tag;
719 }
720
Sebastian Redlb7605e82008-12-28 15:28:59 +0000721 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
722 << DS.getSourceRange();
723 return 0;
724 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000725
Douglas Gregor723d3332009-01-07 00:43:41 +0000726 return Tag;
727}
728
729/// InjectAnonymousStructOrUnionMembers - Inject the members of the
730/// anonymous struct or union AnonRecord into the owning context Owner
731/// and scope S. This routine will be invoked just after we realize
732/// that an unnamed union or struct is actually an anonymous union or
733/// struct, e.g.,
734///
735/// @code
736/// union {
737/// int i;
738/// float f;
739/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
740/// // f into the surrounding scope.x
741/// @endcode
742///
743/// This routine is recursive, injecting the names of nested anonymous
744/// structs/unions into the owning context and scope as well.
745bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
746 RecordDecl *AnonRecord) {
747 bool Invalid = false;
748 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
749 FEnd = AnonRecord->field_end();
750 F != FEnd; ++F) {
751 if ((*F)->getDeclName()) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000752 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
753 LookupOrdinaryName, true);
Douglas Gregor723d3332009-01-07 00:43:41 +0000754 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
755 // C++ [class.union]p2:
756 // The names of the members of an anonymous union shall be
757 // distinct from the names of any other entity in the
758 // scope in which the anonymous union is declared.
759 unsigned diagKind
760 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
761 : diag::err_anonymous_struct_member_redecl;
762 Diag((*F)->getLocation(), diagKind)
763 << (*F)->getDeclName();
764 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
765 Invalid = true;
766 } else {
767 // C++ [class.union]p2:
768 // For the purpose of name lookup, after the anonymous union
769 // definition, the members of the anonymous union are
770 // considered to have been defined in the scope in which the
771 // anonymous union is declared.
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000772 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000773 S->AddDecl(*F);
774 IdResolver.AddDecl(*F);
775 }
776 } else if (const RecordType *InnerRecordType
777 = (*F)->getType()->getAsRecordType()) {
778 RecordDecl *InnerRecord = InnerRecordType->getDecl();
779 if (InnerRecord->isAnonymousStructOrUnion())
780 Invalid = Invalid ||
781 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
782 }
783 }
784
785 return Invalid;
786}
787
788/// ActOnAnonymousStructOrUnion - Handle the declaration of an
789/// anonymous structure or union. Anonymous unions are a C++ feature
790/// (C++ [class.union]) and a GNU C extension; anonymous structures
791/// are a GNU C and GNU C++ extension.
792Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
793 RecordDecl *Record) {
794 DeclContext *Owner = Record->getDeclContext();
795
796 // Diagnose whether this anonymous struct/union is an extension.
797 if (Record->isUnion() && !getLangOptions().CPlusPlus)
798 Diag(Record->getLocation(), diag::ext_anonymous_union);
799 else if (!Record->isUnion())
800 Diag(Record->getLocation(), diag::ext_anonymous_struct);
801
802 // C and C++ require different kinds of checks for anonymous
803 // structs/unions.
804 bool Invalid = false;
805 if (getLangOptions().CPlusPlus) {
806 const char* PrevSpec = 0;
807 // C++ [class.union]p3:
808 // Anonymous unions declared in a named namespace or in the
809 // global namespace shall be declared static.
810 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
811 (isa<TranslationUnitDecl>(Owner) ||
812 (isa<NamespaceDecl>(Owner) &&
813 cast<NamespaceDecl>(Owner)->getDeclName()))) {
814 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
815 Invalid = true;
816
817 // Recover by adding 'static'.
818 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
819 }
820 // C++ [class.union]p3:
821 // A storage class is not allowed in a declaration of an
822 // anonymous union in a class scope.
823 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
824 isa<RecordDecl>(Owner)) {
825 Diag(DS.getStorageClassSpecLoc(),
826 diag::err_anonymous_union_with_storage_spec);
827 Invalid = true;
828
829 // Recover by removing the storage specifier.
830 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
831 PrevSpec);
832 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000833
834 // C++ [class.union]p2:
835 // The member-specification of an anonymous union shall only
836 // define non-static data members. [Note: nested types and
837 // functions cannot be declared within an anonymous union. ]
838 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
839 MemEnd = Record->decls_end();
840 Mem != MemEnd; ++Mem) {
841 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
842 // C++ [class.union]p3:
843 // An anonymous union shall not have private or protected
844 // members (clause 11).
845 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
846 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
847 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
848 Invalid = true;
849 }
850 } else if ((*Mem)->isImplicit()) {
851 // Any implicit members are fine.
Douglas Gregor2d87eb02009-02-03 00:34:39 +0000852 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
853 // This is a type that showed up in an
854 // elaborated-type-specifier inside the anonymous struct or
855 // union, but which actually declares a type outside of the
856 // anonymous struct or union. It's okay.
Douglas Gregorc7f01612009-01-07 19:46:03 +0000857 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
858 if (!MemRecord->isAnonymousStructOrUnion() &&
859 MemRecord->getDeclName()) {
860 // This is a nested type declaration.
861 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
862 << (int)Record->isUnion();
863 Invalid = true;
864 }
865 } else {
866 // We have something that isn't a non-static data
867 // member. Complain about it.
868 unsigned DK = diag::err_anonymous_record_bad_member;
869 if (isa<TypeDecl>(*Mem))
870 DK = diag::err_anonymous_record_with_type;
871 else if (isa<FunctionDecl>(*Mem))
872 DK = diag::err_anonymous_record_with_function;
873 else if (isa<VarDecl>(*Mem))
874 DK = diag::err_anonymous_record_with_static;
875 Diag((*Mem)->getLocation(), DK)
876 << (int)Record->isUnion();
877 Invalid = true;
878 }
879 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000880 } else {
881 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000882 if (Record->isUnion() && !Owner->isRecord()) {
883 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
884 << (int)getLangOptions().CPlusPlus;
885 Invalid = true;
886 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000887 }
888
889 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000890 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
891 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000892 Invalid = true;
893 }
894
895 // Create a declaration for this anonymous struct/union.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000896 NamedDecl *Anon = 0;
Douglas Gregor723d3332009-01-07 00:43:41 +0000897 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
898 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
899 /*IdentifierInfo=*/0,
900 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000901 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000902 Anon->setAccess(AS_public);
903 if (getLangOptions().CPlusPlus)
904 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000905 } else {
906 VarDecl::StorageClass SC;
907 switch (DS.getStorageClassSpec()) {
908 default: assert(0 && "Unknown storage class!");
909 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
910 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
911 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
912 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
913 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
914 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
915 case DeclSpec::SCS_mutable:
916 // mutable can only appear on non-static class members, so it's always
917 // an error here
918 Diag(Record->getLocation(), diag::err_mutable_nonmember);
919 Invalid = true;
920 SC = VarDecl::None;
921 break;
922 }
923
924 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
925 /*IdentifierInfo=*/0,
926 Context.getTypeDeclType(Record),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000927 SC, DS.getSourceRange().getBegin());
Douglas Gregor723d3332009-01-07 00:43:41 +0000928 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000929 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000930
931 // Add the anonymous struct/union object to the current
932 // context. We'll be referencing this object when we refer to one of
933 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000934 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000935
936 // Inject the members of the anonymous struct/union into the owning
937 // context and into the identifier resolver chain for name lookup
938 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000939 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
940 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000941
942 // Mark this as an anonymous struct/union type. Note that we do not
943 // do this until after we have already checked and injected the
944 // members of this anonymous struct/union type, because otherwise
945 // the members could be injected twice: once by DeclContext when it
946 // builds its lookup table, and once by
947 // InjectAnonymousStructOrUnionMembers.
948 Record->setAnonymousStructOrUnion(true);
949
950 if (Invalid)
951 Anon->setInvalidDecl();
952
953 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000954}
955
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000956bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
957 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000958 // Get the type before calling CheckSingleAssignmentConstraints(), since
959 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000960 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000961
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000962 if (getLangOptions().CPlusPlus) {
963 // FIXME: I dislike this error message. A lot.
964 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
965 return Diag(Init->getSourceRange().getBegin(),
966 diag::err_typecheck_convert_incompatible)
967 << DeclType << Init->getType() << "initializing"
968 << Init->getSourceRange();
969
970 return false;
971 }
Douglas Gregor6fd35572008-12-19 17:40:08 +0000972
Chris Lattner005ed752008-01-04 18:04:52 +0000973 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
974 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
975 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000976}
977
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000978bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000979 const ArrayType *AT = Context.getAsArrayType(DeclT);
980
981 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000982 // C99 6.7.8p14. We have an array of character type with unknown size
983 // being initialized to a string literal.
984 llvm::APSInt ConstVal(32);
985 ConstVal = strLiteral->getByteLength() + 1;
986 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000987 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000988 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000989 } else {
990 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000991 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000992 // FIXME: Avoid truncation for 64-bit length strings.
993 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000994 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000995 diag::warn_initializer_string_for_char_array_too_long)
996 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000997 }
998 // Set type from "char *" to "constant array of char".
999 strLiteral->setType(DeclT);
1000 // For now, we always return false (meaning success).
1001 return false;
1002}
1003
1004StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001005 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001006 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson37704be2009-01-24 17:47:50 +00001007 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Narofff3cb5142008-01-25 00:51:06 +00001008 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001009 return 0;
1010}
1011
Douglas Gregor6428e762008-11-05 15:29:30 +00001012bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1013 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001014 DeclarationName InitEntity,
1015 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001016 if (DeclType->isDependentType() || Init->isTypeDependent())
1017 return false;
1018
Douglas Gregor81c29152008-10-29 00:13:59 +00001019 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001020 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001021 // (8.3.2), shall be initialized by an object, or function, of
1022 // type T or by an object that can be converted into a T.
1023 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001024 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001025
Steve Naroff8e9337f2008-01-21 23:53:58 +00001026 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1027 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001028 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001029 return Diag(InitLoc, diag::err_variable_object_no_init)
1030 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001031
Steve Naroffcb69fb72007-12-10 22:44:33 +00001032 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1033 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001034 // FIXME: Handle wide strings
1035 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1036 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001037
Douglas Gregor6428e762008-11-05 15:29:30 +00001038 // C++ [dcl.init]p14:
1039 // -- If the destination type is a (possibly cv-qualified) class
1040 // type:
1041 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1042 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1043 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1044
1045 // -- If the initialization is direct-initialization, or if it is
1046 // copy-initialization where the cv-unqualified version of the
1047 // source type is the same class as, or a derived class of, the
1048 // class of the destination, constructors are considered.
1049 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1050 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1051 CXXConstructorDecl *Constructor
1052 = PerformInitializationByConstructor(DeclType, &Init, 1,
1053 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001054 InitEntity,
1055 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001056 return Constructor == 0;
1057 }
1058
1059 // -- Otherwise (i.e., for the remaining copy-initialization
1060 // cases), user-defined conversion sequences that can
1061 // convert from the source type to the destination type or
1062 // (when a conversion function is used) to a derived class
1063 // thereof are enumerated as described in 13.3.1.4, and the
1064 // best one is chosen through overload resolution
1065 // (13.3). If the conversion cannot be done or is
1066 // ambiguous, the initialization is ill-formed. The
1067 // function selected is called with the initializer
1068 // expression as its argument; if the function is a
1069 // constructor, the call initializes a temporary of the
1070 // destination type.
1071 // FIXME: We're pretending to do copy elision here; return to
1072 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001073 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001074 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001075
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001076 if (InitEntity)
1077 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1078 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1079 << Init->getType() << Init->getSourceRange();
1080 else
1081 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1082 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1083 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001084 }
1085
Steve Naroffb2f72412008-09-29 20:07:05 +00001086 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001087 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001088 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1089 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001090
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001091 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregord45210d2009-01-30 22:09:00 +00001092 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001093
Douglas Gregor849afc32009-01-29 00:45:39 +00001094 bool hadError = CheckInitList(InitList, DeclType);
1095 Init = InitList;
1096 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +00001097}
1098
Douglas Gregor6704b312008-11-17 22:58:34 +00001099/// GetNameForDeclarator - Determine the full declaration name for the
1100/// given Declarator.
1101DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1102 switch (D.getKind()) {
1103 case Declarator::DK_Abstract:
1104 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1105 return DeclarationName();
1106
1107 case Declarator::DK_Normal:
1108 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1109 return DeclarationName(D.getIdentifier());
1110
1111 case Declarator::DK_Constructor: {
1112 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1113 Ty = Context.getCanonicalType(Ty);
1114 return Context.DeclarationNames.getCXXConstructorName(Ty);
1115 }
1116
1117 case Declarator::DK_Destructor: {
1118 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1119 Ty = Context.getCanonicalType(Ty);
1120 return Context.DeclarationNames.getCXXDestructorName(Ty);
1121 }
1122
1123 case Declarator::DK_Conversion: {
1124 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1125 Ty = Context.getCanonicalType(Ty);
1126 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1127 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001128
1129 case Declarator::DK_Operator:
1130 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1131 return Context.DeclarationNames.getCXXOperatorName(
1132 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001133 }
1134
1135 assert(false && "Unknown name kind");
1136 return DeclarationName();
1137}
1138
Douglas Gregor46cfe452009-02-06 17:46:57 +00001139/// isNearlyMatchingFunction - Determine whether the C++ functions
1140/// Declaration and Definition are "nearly" matching. This heuristic
1141/// is used to improve diagnostics in the case where an out-of-line
1142/// function definition doesn't match any declaration within
1143/// the class or namespace.
1144static bool isNearlyMatchingFunction(ASTContext &Context,
1145 FunctionDecl *Declaration,
1146 FunctionDecl *Definition) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001147 if (Declaration->param_size() != Definition->param_size())
1148 return false;
1149 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1150 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1151 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1152
1153 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1154 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1155 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1156 return false;
1157 }
1158
1159 return true;
1160}
1161
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001162Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001163Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1164 bool IsFunctionDefinition) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001165 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001166 DeclarationName Name = GetNameForDeclarator(D);
1167
Chris Lattner4b009652007-07-25 00:24:17 +00001168 // All of these full declarators require an identifier. If it doesn't have
1169 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001170 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001171 if (!D.getInvalidType()) // Reject this if we think it is valid.
1172 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001173 diag::err_declarator_need_ident)
1174 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001175 return 0;
1176 }
1177
Chris Lattnera7549902007-08-26 06:24:45 +00001178 // The scope passed in may not be a decl scope. Zip up the scope tree until
1179 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001180 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregor279272e2009-02-04 19:02:06 +00001181 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001182 S = S->getParent();
1183
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001184 DeclContext *DC;
Douglas Gregor09be81b2009-02-04 17:27:36 +00001185 NamedDecl *PrevDecl;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001186 NamedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001187 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001188
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001189 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001190 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001191 DC = CurContext;
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001192 PrevDecl = LookupName(S, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001193 } else { // Something like "int foo::x;"
1194 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001195 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001196
1197 // C++ 7.3.1.2p2:
1198 // Members (including explicit specializations of templates) of a named
1199 // namespace can also be defined outside that namespace by explicit
1200 // qualification of the name being defined, provided that the entity being
1201 // defined was already declared in the namespace and the definition appears
1202 // after the point of declaration in a namespace that encloses the
1203 // declarations namespace.
1204 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001205 // Note that we only check the context at this point. We don't yet
1206 // have enough information to make sure that PrevDecl is actually
1207 // the declaration we want to match. For example, given:
1208 //
Douglas Gregor98341042008-12-12 08:25:50 +00001209 // class X {
1210 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001211 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001212 // };
1213 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001214 // void X::f(int) { } // ill-formed
1215 //
1216 // In this case, PrevDecl will point to the overload set
1217 // containing the two f's declared in X, but neither of them
1218 // matches.
Douglas Gregor46cfe452009-02-06 17:46:57 +00001219
1220 // First check whether we named the global scope.
1221 if (isa<TranslationUnitDecl>(DC)) {
1222 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1223 << Name << D.getCXXScopeSpec().getRange();
1224 } else if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001225 // The qualifying scope doesn't enclose the original declaration.
1226 // Emit diagnostic based on current scope.
1227 SourceLocation L = D.getIdentifierLoc();
1228 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor46cfe452009-02-06 17:46:57 +00001229 if (isa<FunctionDecl>(CurContext))
Chris Lattner254de7d2008-11-23 20:28:15 +00001230 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor46cfe452009-02-06 17:46:57 +00001231 else
Chris Lattner254de7d2008-11-23 20:28:15 +00001232 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor46cfe452009-02-06 17:46:57 +00001233 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001234 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001235 }
1236 }
1237
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001238 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001239 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001240 InvalidDecl = InvalidDecl
1241 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001242 // Just pretend that we didn't see the previous declaration.
1243 PrevDecl = 0;
1244 }
1245
Douglas Gregor1d661552008-04-13 21:07:44 +00001246 // In C++, the previous declaration we find might be a tag type
1247 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorb31f2942009-01-28 17:15:10 +00001248 // tag type. Note that this does does not apply if we're declaring a
1249 // typedef (C++ [dcl.typedef]p4).
1250 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1251 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor1d661552008-04-13 21:07:44 +00001252 PrevDecl = 0;
1253
Chris Lattner82bb4792007-11-14 06:34:38 +00001254 QualType R = GetTypeForDeclarator(D, S);
1255 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1256
Chris Lattner4b009652007-07-25 00:24:17 +00001257 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001258 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1259 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001260 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001261 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1262 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001263 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001264 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1265 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001266 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001267
1268 if (New == 0)
1269 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001270
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001271 // Set the lexical context. If the declarator has a C++ scope specifier, the
1272 // lexical context will be different from the semantic context.
1273 New->setLexicalDeclContext(CurContext);
1274
Chris Lattner4b009652007-07-25 00:24:17 +00001275 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001276 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001277 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001278 // If any semantic error occurred, mark the decl as invalid.
1279 if (D.getInvalidType() || InvalidDecl)
1280 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001281
1282 return New;
1283}
1284
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001285NamedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001286Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001287 QualType R, Decl* LastDeclarator,
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001288 Decl* PrevDecl, bool& InvalidDecl) {
1289 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1290 if (D.getCXXScopeSpec().isSet()) {
1291 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1292 << D.getCXXScopeSpec().getRange();
1293 InvalidDecl = true;
1294 // Pretend we didn't see the scope specifier.
1295 DC = 0;
1296 }
1297
1298 // Check that there are no default arguments (C++ only).
1299 if (getLangOptions().CPlusPlus)
1300 CheckExtraCXXDefaultArguments(D);
1301
1302 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1303 if (!NewTD) return 0;
1304
1305 // Handle attributes prior to checking for duplicates in MergeVarDecl
1306 ProcessDeclAttributes(NewTD, D);
1307 // Merge the decl with the existing one if appropriate. If the decl is
1308 // in an outer scope, it isn't the same thing.
1309 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1310 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1311 if (NewTD == 0) return 0;
1312 }
1313
1314 if (S->getFnParent() == 0) {
1315 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1316 // then it shall have block scope.
1317 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1318 if (NewTD->getUnderlyingType()->isVariableArrayType())
1319 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1320 else
1321 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1322
1323 InvalidDecl = true;
1324 }
1325 }
1326 return NewTD;
1327}
1328
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001329NamedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001330Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001331 QualType R, Decl* LastDeclarator,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001332 Decl* PrevDecl, bool& InvalidDecl) {
1333 DeclarationName Name = GetNameForDeclarator(D);
1334
1335 // Check that there are no default arguments (C++ only).
1336 if (getLangOptions().CPlusPlus)
1337 CheckExtraCXXDefaultArguments(D);
1338
1339 if (R.getTypePtr()->isObjCInterfaceType()) {
1340 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1341 << D.getIdentifier();
1342 InvalidDecl = true;
1343 }
1344
1345 VarDecl *NewVD;
1346 VarDecl::StorageClass SC;
1347 switch (D.getDeclSpec().getStorageClassSpec()) {
1348 default: assert(0 && "Unknown storage class!");
1349 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1350 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1351 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1352 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1353 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1354 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1355 case DeclSpec::SCS_mutable:
1356 // mutable can only appear on non-static class members, so it's always
1357 // an error here
1358 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1359 InvalidDecl = true;
1360 SC = VarDecl::None;
1361 break;
1362 }
1363
1364 IdentifierInfo *II = Name.getAsIdentifierInfo();
1365 if (!II) {
1366 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1367 << Name.getAsString();
1368 return 0;
1369 }
1370
1371 if (DC->isRecord()) {
1372 // This is a static data member for a C++ class.
1373 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1374 D.getIdentifierLoc(), II,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001375 R);
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001376 } else {
1377 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1378 if (S->getFnParent() == 0) {
1379 // C99 6.9p2: The storage-class specifiers auto and register shall not
1380 // appear in the declaration specifiers in an external declaration.
1381 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1382 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1383 InvalidDecl = true;
1384 }
1385 }
1386 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001387 II, R, SC,
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001388 // FIXME: Move to DeclGroup...
1389 D.getDeclSpec().getSourceRange().getBegin());
1390 NewVD->setThreadSpecified(ThreadSpecified);
1391 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001392 NewVD->setNextDeclarator(LastDeclarator);
1393
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001394 // Handle attributes prior to checking for duplicates in MergeVarDecl
1395 ProcessDeclAttributes(NewVD, D);
1396
1397 // Handle GNU asm-label extension (encoded as an attribute).
1398 if (Expr *E = (Expr*) D.getAsmLabel()) {
1399 // The parser guarantees this is a string.
1400 StringLiteral *SE = cast<StringLiteral>(E);
1401 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1402 SE->getByteLength())));
1403 }
1404
1405 // Emit an error if an address space was applied to decl with local storage.
1406 // This includes arrays of objects with address space qualifiers, but not
1407 // automatic variables that point to other address spaces.
1408 // ISO/IEC TR 18037 S5.1.2
1409 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1410 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1411 InvalidDecl = true;
1412 }
1413 // Merge the decl with the existing one if appropriate. If the decl is
1414 // in an outer scope, it isn't the same thing.
1415 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1416 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1417 // The user tried to define a non-static data member
1418 // out-of-line (C++ [dcl.meaning]p1).
1419 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1420 << D.getCXXScopeSpec().getRange();
1421 NewVD->Destroy(Context);
1422 return 0;
1423 }
1424
1425 NewVD = MergeVarDecl(NewVD, PrevDecl);
1426 if (NewVD == 0) return 0;
1427
1428 if (D.getCXXScopeSpec().isSet()) {
1429 // No previous declaration in the qualifying scope.
1430 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1431 << Name << D.getCXXScopeSpec().getRange();
1432 InvalidDecl = true;
1433 }
1434 }
1435 return NewVD;
1436}
1437
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001438NamedDecl*
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001439Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001440 QualType R, Decl *LastDeclarator,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001441 Decl* PrevDecl, bool IsFunctionDefinition,
1442 bool& InvalidDecl) {
1443 assert(R.getTypePtr()->isFunctionType());
1444
1445 DeclarationName Name = GetNameForDeclarator(D);
1446 FunctionDecl::StorageClass SC = FunctionDecl::None;
1447 switch (D.getDeclSpec().getStorageClassSpec()) {
1448 default: assert(0 && "Unknown storage class!");
1449 case DeclSpec::SCS_auto:
1450 case DeclSpec::SCS_register:
1451 case DeclSpec::SCS_mutable:
1452 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1453 InvalidDecl = true;
1454 break;
1455 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1456 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1457 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1458 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1459 }
1460
1461 bool isInline = D.getDeclSpec().isInlineSpecified();
1462 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1463 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1464
1465 FunctionDecl *NewFD;
1466 if (D.getKind() == Declarator::DK_Constructor) {
1467 // This is a C++ constructor declaration.
1468 assert(DC->isRecord() &&
1469 "Constructors can only be declared in a member context");
1470
1471 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1472
1473 // Create the new declaration
1474 NewFD = CXXConstructorDecl::Create(Context,
1475 cast<CXXRecordDecl>(DC),
1476 D.getIdentifierLoc(), Name, R,
1477 isExplicit, isInline,
1478 /*isImplicitlyDeclared=*/false);
1479
1480 if (InvalidDecl)
1481 NewFD->setInvalidDecl();
1482 } else if (D.getKind() == Declarator::DK_Destructor) {
1483 // This is a C++ destructor declaration.
1484 if (DC->isRecord()) {
1485 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1486
1487 NewFD = CXXDestructorDecl::Create(Context,
1488 cast<CXXRecordDecl>(DC),
1489 D.getIdentifierLoc(), Name, R,
1490 isInline,
1491 /*isImplicitlyDeclared=*/false);
1492
1493 if (InvalidDecl)
1494 NewFD->setInvalidDecl();
1495 } else {
1496 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1497
1498 // Create a FunctionDecl to satisfy the function definition parsing
1499 // code path.
1500 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001501 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001502 // FIXME: Move to DeclGroup...
1503 D.getDeclSpec().getSourceRange().getBegin());
1504 InvalidDecl = true;
1505 NewFD->setInvalidDecl();
1506 }
1507 } else if (D.getKind() == Declarator::DK_Conversion) {
1508 if (!DC->isRecord()) {
1509 Diag(D.getIdentifierLoc(),
1510 diag::err_conv_function_not_member);
1511 return 0;
1512 } else {
1513 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1514
1515 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1516 D.getIdentifierLoc(), Name, R,
1517 isInline, isExplicit);
1518
1519 if (InvalidDecl)
1520 NewFD->setInvalidDecl();
1521 }
1522 } else if (DC->isRecord()) {
1523 // This is a C++ method declaration.
1524 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1525 D.getIdentifierLoc(), Name, R,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001526 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001527 } else {
1528 NewFD = FunctionDecl::Create(Context, DC,
1529 D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001530 Name, R, SC, isInline,
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001531 // FIXME: Move to DeclGroup...
1532 D.getDeclSpec().getSourceRange().getBegin());
1533 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001534 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001535
1536 // Set the lexical context. If the declarator has a C++
1537 // scope specifier, the lexical context will be different
1538 // from the semantic context.
1539 NewFD->setLexicalDeclContext(CurContext);
1540
1541 // Handle GNU asm-label extension (encoded as an attribute).
1542 if (Expr *E = (Expr*) D.getAsmLabel()) {
1543 // The parser guarantees this is a string.
1544 StringLiteral *SE = cast<StringLiteral>(E);
1545 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1546 SE->getByteLength())));
1547 }
1548
1549 // Copy the parameter declarations from the declarator D to
1550 // the function declaration NewFD, if they are available.
1551 if (D.getNumTypeObjects() > 0) {
1552 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1553
1554 // Create Decl objects for each parameter, adding them to the
1555 // FunctionDecl.
1556 llvm::SmallVector<ParmVarDecl*, 16> Params;
1557
1558 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1559 // function that takes no arguments, not a function that takes a
1560 // single void argument.
1561 // We let through "const void" here because Sema::GetTypeForDeclarator
1562 // already checks for that case.
1563 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1564 FTI.ArgInfo[0].Param &&
1565 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1566 // empty arg list, don't push any params.
1567 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1568
1569 // In C++, the empty parameter-type-list must be spelled "void"; a
1570 // typedef of void is not permitted.
1571 if (getLangOptions().CPlusPlus &&
1572 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1573 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1574 }
1575 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1576 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1577 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1578 }
1579
1580 NewFD->setParams(Context, &Params[0], Params.size());
1581 } else if (R->getAsTypedefType()) {
1582 // When we're declaring a function with a typedef, as in the
1583 // following example, we'll need to synthesize (unnamed)
1584 // parameters for use in the declaration.
1585 //
1586 // @code
1587 // typedef void fn(int);
1588 // fn f;
1589 // @endcode
1590 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1591 if (!FT) {
1592 // This is a typedef of a function with no prototype, so we
1593 // don't need to do anything.
1594 } else if ((FT->getNumArgs() == 0) ||
1595 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1596 FT->getArgType(0)->isVoidType())) {
1597 // This is a zero-argument function. We don't need to do anything.
1598 } else {
1599 // Synthesize a parameter for each argument type.
1600 llvm::SmallVector<ParmVarDecl*, 16> Params;
1601 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1602 ArgType != FT->arg_type_end(); ++ArgType) {
1603 Params.push_back(ParmVarDecl::Create(Context, DC,
1604 SourceLocation(), 0,
1605 *ArgType, VarDecl::None,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001606 0));
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001607 }
1608
1609 NewFD->setParams(Context, &Params[0], Params.size());
1610 }
1611 }
1612
1613 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1614 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1615 else if (isa<CXXDestructorDecl>(NewFD)) {
1616 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1617 Record->setUserDeclaredDestructor(true);
1618 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1619 // user-defined destructor.
1620 Record->setPOD(false);
1621 } else if (CXXConversionDecl *Conversion =
1622 dyn_cast<CXXConversionDecl>(NewFD))
1623 ActOnConversionDeclarator(Conversion);
1624
1625 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1626 if (NewFD->isOverloadedOperator() &&
1627 CheckOverloadedOperatorDeclaration(NewFD))
1628 NewFD->setInvalidDecl();
1629
1630 // Merge the decl with the existing one if appropriate. Since C functions
1631 // are in a flat namespace, make sure we consider decls in outer scopes.
Douglas Gregor46cfe452009-02-06 17:46:57 +00001632 bool Redeclaration = false;
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001633 if (PrevDecl &&
1634 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001635 // If C++, determine whether NewFD is an overload of PrevDecl or
1636 // a declaration that requires merging. If it's an overload,
1637 // there's no more work to do here; we'll just add the new
1638 // function to the scope.
1639 OverloadedFunctionDecl::function_iterator MatchedDecl;
1640 if (!getLangOptions().CPlusPlus ||
1641 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1642 Decl *OldDecl = PrevDecl;
1643
1644 // If PrevDecl was an overloaded function, extract the
1645 // FunctionDecl that matched.
1646 if (isa<OverloadedFunctionDecl>(PrevDecl))
1647 OldDecl = *MatchedDecl;
1648
1649 // NewFD and PrevDecl represent declarations that need to be
1650 // merged.
1651 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1652
1653 if (NewFD == 0) return 0;
1654 if (Redeclaration) {
1655 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1656
1657 // An out-of-line member function declaration must also be a
1658 // definition (C++ [dcl.meaning]p1).
1659 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1660 !InvalidDecl) {
1661 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1662 << D.getCXXScopeSpec().getRange();
1663 NewFD->setInvalidDecl();
1664 }
1665 }
1666 }
Douglas Gregor46cfe452009-02-06 17:46:57 +00001667 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001668
Douglas Gregor46cfe452009-02-06 17:46:57 +00001669 if (D.getCXXScopeSpec().isSet() &&
1670 (!PrevDecl || !Redeclaration)) {
1671 // The user tried to provide an out-of-line definition for a
1672 // function that is a member of a class or namespace, but there
1673 // was no such member function declared (C++ [class.mfct]p2,
1674 // C++ [namespace.memdef]p2). For example:
1675 //
1676 // class X {
1677 // void f() const;
1678 // };
1679 //
1680 // void X::f() { } // ill-formed
1681 //
1682 // Complain about this problem, and attempt to suggest close
1683 // matches (e.g., those that differ only in cv-qualifiers and
1684 // whether the parameter types are references).
1685 DeclarationName CtxName;
1686 if (DC->isRecord())
1687 CtxName = cast<RecordDecl>(DC)->getDeclName();
1688 else if (DC->isNamespace())
1689 CtxName = cast<NamespaceDecl>(DC)->getDeclName();
1690 // FIXME: global scope
1691 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1692 << CtxName << D.getCXXScopeSpec().getRange();
1693 InvalidDecl = true;
1694
1695 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1696 true);
1697 assert(!Prev.isAmbiguous() &&
1698 "Cannot have an ambiguity in previous-declaration lookup");
1699 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1700 Func != FuncEnd; ++Func) {
1701 if (isa<FunctionDecl>(*Func) &&
1702 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
1703 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001704 }
Douglas Gregor46cfe452009-02-06 17:46:57 +00001705
1706 PrevDecl = 0;
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001707 }
Douglas Gregorbd4b0852009-02-02 21:35:47 +00001708
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001709 // Handle attributes. We need to have merged decls when handling attributes
1710 // (for example to check for conflicts, etc).
1711 ProcessDeclAttributes(NewFD, D);
1712
1713 if (getLangOptions().CPlusPlus) {
1714 // In C++, check default arguments now that we have merged decls.
1715 CheckCXXDefaultArguments(NewFD);
1716
1717 // An out-of-line member function declaration must also be a
1718 // definition (C++ [dcl.meaning]p1).
1719 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1720 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1721 << D.getCXXScopeSpec().getRange();
1722 InvalidDecl = true;
1723 }
1724 }
1725 return NewFD;
1726}
1727
Steve Narofffc08f5e2008-10-27 11:34:16 +00001728void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001729 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1730 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001731}
1732
Eli Friedman02c22ce2008-05-20 13:48:25 +00001733bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1734 switch (Init->getStmtClass()) {
1735 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001736 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001737 return true;
1738 case Expr::ParenExprClass: {
1739 const ParenExpr* PE = cast<ParenExpr>(Init);
1740 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1741 }
1742 case Expr::CompoundLiteralExprClass:
1743 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001744 case Expr::DeclRefExprClass:
1745 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001746 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001747 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1748 if (VD->hasGlobalStorage())
1749 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001750 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001751 return true;
1752 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001753 if (isa<FunctionDecl>(D))
1754 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001755 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001756 return true;
1757 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001758 case Expr::MemberExprClass: {
1759 const MemberExpr *M = cast<MemberExpr>(Init);
1760 if (M->isArrow())
1761 return CheckAddressConstantExpression(M->getBase());
1762 return CheckAddressConstantExpressionLValue(M->getBase());
1763 }
1764 case Expr::ArraySubscriptExprClass: {
1765 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1766 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1767 return CheckAddressConstantExpression(ASE->getBase()) ||
1768 CheckArithmeticConstantExpression(ASE->getIdx());
1769 }
1770 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001771 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001772 return false;
1773 case Expr::UnaryOperatorClass: {
1774 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1775
1776 // C99 6.6p9
1777 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001778 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001779
Steve Narofffc08f5e2008-10-27 11:34:16 +00001780 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001781 return true;
1782 }
1783 }
1784}
1785
1786bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1787 switch (Init->getStmtClass()) {
1788 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001789 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001790 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001791 case Expr::ParenExprClass:
1792 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001793 case Expr::StringLiteralClass:
1794 case Expr::ObjCStringLiteralClass:
1795 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001796 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001797 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001798 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1799 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1800 Builtin::BI__builtin___CFStringMakeConstantString)
1801 return false;
1802
Steve Narofffc08f5e2008-10-27 11:34:16 +00001803 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001804 return true;
1805
Eli Friedman02c22ce2008-05-20 13:48:25 +00001806 case Expr::UnaryOperatorClass: {
1807 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1808
1809 // C99 6.6p9
1810 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1811 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1812
1813 if (Exp->getOpcode() == UnaryOperator::Extension)
1814 return CheckAddressConstantExpression(Exp->getSubExpr());
1815
Steve Narofffc08f5e2008-10-27 11:34:16 +00001816 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001817 return true;
1818 }
1819 case Expr::BinaryOperatorClass: {
1820 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1821 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1822
1823 Expr *PExp = Exp->getLHS();
1824 Expr *IExp = Exp->getRHS();
1825 if (IExp->getType()->isPointerType())
1826 std::swap(PExp, IExp);
1827
1828 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1829 return CheckAddressConstantExpression(PExp) ||
1830 CheckArithmeticConstantExpression(IExp);
1831 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001832 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001833 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001834 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001835 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1836 // Check for implicit promotion
1837 if (SubExpr->getType()->isFunctionType() ||
1838 SubExpr->getType()->isArrayType())
1839 return CheckAddressConstantExpressionLValue(SubExpr);
1840 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001841
1842 // Check for pointer->pointer cast
1843 if (SubExpr->getType()->isPointerType())
1844 return CheckAddressConstantExpression(SubExpr);
1845
Eli Friedman1fad3c62008-08-25 20:46:57 +00001846 if (SubExpr->getType()->isIntegralType()) {
1847 // Check for the special-case of a pointer->int->pointer cast;
1848 // this isn't standard, but some code requires it. See
1849 // PR2720 for an example.
1850 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1851 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1852 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1853 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1854 if (IntWidth >= PointerWidth) {
1855 return CheckAddressConstantExpression(SubCast->getSubExpr());
1856 }
1857 }
1858 }
1859 }
1860 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001861 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001862 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001863
Steve Narofffc08f5e2008-10-27 11:34:16 +00001864 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001865 return true;
1866 }
1867 case Expr::ConditionalOperatorClass: {
1868 // FIXME: Should we pedwarn here?
1869 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1870 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001871 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001872 return true;
1873 }
1874 if (CheckArithmeticConstantExpression(Exp->getCond()))
1875 return true;
1876 if (Exp->getLHS() &&
1877 CheckAddressConstantExpression(Exp->getLHS()))
1878 return true;
1879 return CheckAddressConstantExpression(Exp->getRHS());
1880 }
1881 case Expr::AddrLabelExprClass:
1882 return false;
1883 }
1884}
1885
Eli Friedman998dffb2008-06-09 05:05:07 +00001886static const Expr* FindExpressionBaseAddress(const Expr* E);
1887
1888static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1889 switch (E->getStmtClass()) {
1890 default:
1891 return E;
1892 case Expr::ParenExprClass: {
1893 const ParenExpr* PE = cast<ParenExpr>(E);
1894 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1895 }
1896 case Expr::MemberExprClass: {
1897 const MemberExpr *M = cast<MemberExpr>(E);
1898 if (M->isArrow())
1899 return FindExpressionBaseAddress(M->getBase());
1900 return FindExpressionBaseAddressLValue(M->getBase());
1901 }
1902 case Expr::ArraySubscriptExprClass: {
1903 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1904 return FindExpressionBaseAddress(ASE->getBase());
1905 }
1906 case Expr::UnaryOperatorClass: {
1907 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1908
1909 if (Exp->getOpcode() == UnaryOperator::Deref)
1910 return FindExpressionBaseAddress(Exp->getSubExpr());
1911
1912 return E;
1913 }
1914 }
1915}
1916
1917static const Expr* FindExpressionBaseAddress(const Expr* E) {
1918 switch (E->getStmtClass()) {
1919 default:
1920 return E;
1921 case Expr::ParenExprClass: {
1922 const ParenExpr* PE = cast<ParenExpr>(E);
1923 return FindExpressionBaseAddress(PE->getSubExpr());
1924 }
1925 case Expr::UnaryOperatorClass: {
1926 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1927
1928 // C99 6.6p9
1929 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1930 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1931
1932 if (Exp->getOpcode() == UnaryOperator::Extension)
1933 return FindExpressionBaseAddress(Exp->getSubExpr());
1934
1935 return E;
1936 }
1937 case Expr::BinaryOperatorClass: {
1938 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1939
1940 Expr *PExp = Exp->getLHS();
1941 Expr *IExp = Exp->getRHS();
1942 if (IExp->getType()->isPointerType())
1943 std::swap(PExp, IExp);
1944
1945 return FindExpressionBaseAddress(PExp);
1946 }
1947 case Expr::ImplicitCastExprClass: {
1948 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1949
1950 // Check for implicit promotion
1951 if (SubExpr->getType()->isFunctionType() ||
1952 SubExpr->getType()->isArrayType())
1953 return FindExpressionBaseAddressLValue(SubExpr);
1954
1955 // Check for pointer->pointer cast
1956 if (SubExpr->getType()->isPointerType())
1957 return FindExpressionBaseAddress(SubExpr);
1958
1959 // We assume that we have an arithmetic expression here;
1960 // if we don't, we'll figure it out later
1961 return 0;
1962 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001963 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001964 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1965
1966 // Check for pointer->pointer cast
1967 if (SubExpr->getType()->isPointerType())
1968 return FindExpressionBaseAddress(SubExpr);
1969
1970 // We assume that we have an arithmetic expression here;
1971 // if we don't, we'll figure it out later
1972 return 0;
1973 }
1974 }
1975}
1976
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001977bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001978 switch (Init->getStmtClass()) {
1979 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001980 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001981 return true;
1982 case Expr::ParenExprClass: {
1983 const ParenExpr* PE = cast<ParenExpr>(Init);
1984 return CheckArithmeticConstantExpression(PE->getSubExpr());
1985 }
1986 case Expr::FloatingLiteralClass:
1987 case Expr::IntegerLiteralClass:
1988 case Expr::CharacterLiteralClass:
1989 case Expr::ImaginaryLiteralClass:
1990 case Expr::TypesCompatibleExprClass:
1991 case Expr::CXXBoolLiteralExprClass:
1992 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001993 case Expr::CallExprClass:
1994 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001995 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001996
1997 // Allow any constant foldable calls to builtins.
1998 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001999 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002000
Steve Narofffc08f5e2008-10-27 11:34:16 +00002001 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002002 return true;
2003 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002004 case Expr::DeclRefExprClass:
2005 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002006 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2007 if (isa<EnumConstantDecl>(D))
2008 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002009 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002010 return true;
2011 }
2012 case Expr::CompoundLiteralExprClass:
2013 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2014 // but vectors are allowed to be magic.
2015 if (Init->getType()->isVectorType())
2016 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002017 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002018 return true;
2019 case Expr::UnaryOperatorClass: {
2020 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2021
2022 switch (Exp->getOpcode()) {
2023 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2024 // See C99 6.6p3.
2025 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002026 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002027 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002028 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002029 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2030 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002031 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002032 return true;
2033 case UnaryOperator::Extension:
2034 case UnaryOperator::LNot:
2035 case UnaryOperator::Plus:
2036 case UnaryOperator::Minus:
2037 case UnaryOperator::Not:
2038 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2039 }
2040 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002041 case Expr::SizeOfAlignOfExprClass: {
2042 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002043 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002044 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002045 return false;
2046 // alignof always evaluates to a constant.
2047 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002048 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002049 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002050 return true;
2051 }
2052 return false;
2053 }
2054 case Expr::BinaryOperatorClass: {
2055 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2056
2057 if (Exp->getLHS()->getType()->isArithmeticType() &&
2058 Exp->getRHS()->getType()->isArithmeticType()) {
2059 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2060 CheckArithmeticConstantExpression(Exp->getRHS());
2061 }
2062
Eli Friedman998dffb2008-06-09 05:05:07 +00002063 if (Exp->getLHS()->getType()->isPointerType() &&
2064 Exp->getRHS()->getType()->isPointerType()) {
2065 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2066 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2067
2068 // Only allow a null (constant integer) base; we could
2069 // allow some additional cases if necessary, but this
2070 // is sufficient to cover offsetof-like constructs.
2071 if (!LHSBase && !RHSBase) {
2072 return CheckAddressConstantExpression(Exp->getLHS()) ||
2073 CheckAddressConstantExpression(Exp->getRHS());
2074 }
2075 }
2076
Steve Narofffc08f5e2008-10-27 11:34:16 +00002077 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002078 return true;
2079 }
2080 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002081 case Expr::CStyleCastExprClass: {
Nuno Lopes7dd54222009-02-02 22:57:15 +00002082 const CastExpr *CE = cast<CastExpr>(Init);
2083 const Expr *SubExpr = CE->getSubExpr();
2084
Eli Friedmand662caa2008-09-01 22:08:17 +00002085 if (SubExpr->getType()->isArithmeticType())
2086 return CheckArithmeticConstantExpression(SubExpr);
2087
Eli Friedman266df142008-09-02 09:37:00 +00002088 if (SubExpr->getType()->isPointerType()) {
2089 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopes7dd54222009-02-02 22:57:15 +00002090 if (Base) {
2091 // the cast is only valid if done to a wide enough type
2092 if (Context.getTypeSize(CE->getType()) >=
2093 Context.getTypeSize(SubExpr->getType()))
2094 return false;
2095 } else {
2096 // If the pointer has a null base, this is an offsetof-like construct
2097 return CheckAddressConstantExpression(SubExpr);
2098 }
Eli Friedman266df142008-09-02 09:37:00 +00002099 }
2100
Steve Narofffc08f5e2008-10-27 11:34:16 +00002101 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002102 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002103 }
2104 case Expr::ConditionalOperatorClass: {
2105 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002106
2107 // If GNU extensions are disabled, we require all operands to be arithmetic
2108 // constant expressions.
2109 if (getLangOptions().NoExtensions) {
2110 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2111 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2112 CheckArithmeticConstantExpression(Exp->getRHS());
2113 }
2114
2115 // Otherwise, we have to emulate some of the behavior of fold here.
2116 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2117 // because it can constant fold things away. To retain compatibility with
2118 // GCC code, we see if we can fold the condition to a constant (which we
2119 // should always be able to do in theory). If so, we only require the
2120 // specified arm of the conditional to be a constant. This is a horrible
2121 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002122 Expr::EvalResult EvalResult;
2123 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2124 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002125 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002126 // won't be able to either. Use it to emit the diagnostic though.
2127 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002128 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002129 return Res;
2130 }
2131
2132 // Verify that the side following the condition is also a constant.
2133 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002134 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002135 std::swap(TrueSide, FalseSide);
2136
2137 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002138 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002139
2140 // Okay, the evaluated side evaluates to a constant, so we accept this.
2141 // Check to see if the other side is obviously not a constant. If so,
2142 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002143 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002144 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002145 diag::ext_typecheck_expression_not_constant_but_accepted)
2146 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002147 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002148 }
2149 }
2150}
2151
2152bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +00002153 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2154 Init = DIE->getInit();
2155
Nuno Lopese7280452008-07-07 16:46:50 +00002156 Init = Init->IgnoreParens();
2157
Nate Begemand6d2f772009-01-18 03:20:47 +00002158 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002159 return false;
2160
Eli Friedman02c22ce2008-05-20 13:48:25 +00002161 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2162 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2163 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2164
Nuno Lopese7280452008-07-07 16:46:50 +00002165 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2166 return CheckForConstantInitializer(e->getInitializer(), DclT);
2167
Douglas Gregorc9e012a2009-01-29 17:44:32 +00002168 if (isa<ImplicitValueInitExpr>(Init)) {
2169 // FIXME: In C++, check for non-POD types.
2170 return false;
2171 }
2172
Eli Friedman02c22ce2008-05-20 13:48:25 +00002173 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2174 unsigned numInits = Exp->getNumInits();
2175 for (unsigned i = 0; i < numInits; i++) {
2176 // FIXME: Need to get the type of the declaration for C++,
2177 // because it could be a reference?
Douglas Gregorf603b472009-01-28 21:54:33 +00002178
Eli Friedman02c22ce2008-05-20 13:48:25 +00002179 if (CheckForConstantInitializer(Exp->getInit(i),
2180 Exp->getInit(i)->getType()))
2181 return true;
2182 }
2183 return false;
2184 }
2185
Anders Carlssonf6791c62008-12-05 05:09:56 +00002186 // FIXME: We can probably remove some of this code below, now that
2187 // Expr::Evaluate is doing the heavy lifting for scalars.
2188
Eli Friedman02c22ce2008-05-20 13:48:25 +00002189 if (Init->isNullPointerConstant(Context))
2190 return false;
2191 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002192 QualType InitTy = Context.getCanonicalType(Init->getType())
2193 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002194 if (InitTy == Context.BoolTy) {
2195 // Special handling for pointers implicitly cast to bool;
2196 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2197 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2198 Expr* SubE = ICE->getSubExpr();
2199 if (SubE->getType()->isPointerType() ||
2200 SubE->getType()->isArrayType() ||
2201 SubE->getType()->isFunctionType()) {
2202 return CheckAddressConstantExpression(Init);
2203 }
2204 }
2205 } else if (InitTy->isIntegralType()) {
2206 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002207 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002208 SubE = CE->getSubExpr();
2209 // Special check for pointer cast to int; we allow as an extension
2210 // an address constant cast to an integer if the integer
2211 // is of an appropriate width (this sort of code is apparently used
2212 // in some places).
2213 // FIXME: Add pedwarn?
2214 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2215 if (SubE && (SubE->getType()->isPointerType() ||
2216 SubE->getType()->isArrayType() ||
2217 SubE->getType()->isFunctionType())) {
2218 unsigned IntWidth = Context.getTypeSize(Init->getType());
2219 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2220 if (IntWidth >= PointerWidth)
2221 return CheckAddressConstantExpression(Init);
2222 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002223 }
2224
2225 return CheckArithmeticConstantExpression(Init);
2226 }
2227
2228 if (Init->getType()->isPointerType())
2229 return CheckAddressConstantExpression(Init);
2230
Eli Friedman25086f02008-05-30 18:14:48 +00002231 // An array type at the top level that isn't an init-list must
2232 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002233 if (Init->getType()->isArrayType())
2234 return false;
2235
Nuno Lopes1dc26762008-09-01 18:42:41 +00002236 if (Init->getType()->isFunctionType())
2237 return false;
2238
Steve Naroffdff3fb22008-10-02 17:12:56 +00002239 // Allow block exprs at top level.
2240 if (Init->getType()->isBlockPointerType())
2241 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002242
2243 // GCC cast to union extension
2244 // note: the validity of the cast expr is checked by CheckCastTypes()
2245 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2246 QualType T = C->getType();
2247 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2248 }
2249
Steve Narofffc08f5e2008-10-27 11:34:16 +00002250 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002251 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002252}
2253
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002254void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002255 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2256}
2257
2258/// AddInitializerToDecl - Adds the initializer Init to the
2259/// declaration dcl. If DirectInit is true, this is C++ direct
2260/// initialization rather than copy initialization.
2261void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002262 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002263 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002264 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002265
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002266 // If there is no declaration, there was an error parsing it. Just ignore
2267 // the initializer.
2268 if (RealDecl == 0) {
2269 delete Init;
2270 return;
2271 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002272
Steve Naroff420d0f52007-09-12 20:13:48 +00002273 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2274 if (!VDecl) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002275 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002276 RealDecl->setInvalidDecl();
2277 return;
2278 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002279 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002280 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002281 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002282 if (VDecl->isBlockVarDecl()) {
2283 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002284 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002285 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002286 VDecl->setInvalidDecl();
2287 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002288 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002289 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002290 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002291
2292 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2293 if (!getLangOptions().CPlusPlus) {
2294 if (SC == VarDecl::Static) // C99 6.7.8p4.
2295 CheckForConstantInitializer(Init, DclT);
2296 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002297 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002298 } else if (VDecl->isFileVarDecl()) {
2299 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002300 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002301 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002302 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002303 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002304 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002305
Anders Carlssonea7140a2008-08-22 05:00:02 +00002306 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2307 if (!getLangOptions().CPlusPlus) {
2308 // C99 6.7.8p4. All file scoped initializers need to be constant.
2309 CheckForConstantInitializer(Init, DclT);
2310 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002311 }
2312 // If the type changed, it means we had an incomplete type that was
2313 // completed by the initializer. For example:
2314 // int ary[] = { 1, 3, 5 };
2315 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002316 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002317 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002318 Init->setType(DclT);
2319 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002320
2321 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002322 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002323 return;
2324}
2325
Douglas Gregor81c29152008-10-29 00:13:59 +00002326void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2327 Decl *RealDecl = static_cast<Decl *>(dcl);
2328
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002329 // If there is no declaration, there was an error parsing it. Just ignore it.
2330 if (RealDecl == 0)
2331 return;
2332
Douglas Gregor81c29152008-10-29 00:13:59 +00002333 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2334 QualType Type = Var->getType();
2335 // C++ [dcl.init.ref]p3:
2336 // The initializer can be omitted for a reference only in a
2337 // parameter declaration (8.3.5), in the declaration of a
2338 // function return type, in the declaration of a class member
2339 // within its class declaration (9.2), and where the extern
2340 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002341 if (Type->isReferenceType() &&
2342 Var->getStorageClass() != VarDecl::Extern &&
2343 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002344 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002345 << Var->getDeclName()
2346 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002347 Var->setInvalidDecl();
2348 return;
2349 }
2350
2351 // C++ [dcl.init]p9:
2352 //
2353 // If no initializer is specified for an object, and the object
2354 // is of (possibly cv-qualified) non-POD class type (or array
2355 // thereof), the object shall be default-initialized; if the
2356 // object is of const-qualified type, the underlying class type
2357 // shall have a user-declared default constructor.
2358 if (getLangOptions().CPlusPlus) {
2359 QualType InitType = Type;
2360 if (const ArrayType *Array = Context.getAsArrayType(Type))
2361 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002362 if (Var->getStorageClass() != VarDecl::Extern &&
2363 Var->getStorageClass() != VarDecl::PrivateExtern &&
2364 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002365 const CXXConstructorDecl *Constructor
2366 = PerformInitializationByConstructor(InitType, 0, 0,
2367 Var->getLocation(),
2368 SourceRange(Var->getLocation(),
2369 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002370 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002371 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002372 if (!Constructor)
2373 Var->setInvalidDecl();
2374 }
2375 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002376
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002377#if 0
2378 // FIXME: Temporarily disabled because we are not properly parsing
2379 // linkage specifications on declarations, e.g.,
2380 //
2381 // extern "C" const CGPoint CGPointerZero;
2382 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002383 // C++ [dcl.init]p9:
2384 //
2385 // If no initializer is specified for an object, and the
2386 // object is of (possibly cv-qualified) non-POD class type (or
2387 // array thereof), the object shall be default-initialized; if
2388 // the object is of const-qualified type, the underlying class
2389 // type shall have a user-declared default
2390 // constructor. Otherwise, if no initializer is specified for
2391 // an object, the object and its subobjects, if any, have an
2392 // indeterminate initial value; if the object or any of its
2393 // subobjects are of const-qualified type, the program is
2394 // ill-formed.
2395 //
2396 // This isn't technically an error in C, so we don't diagnose it.
2397 //
2398 // FIXME: Actually perform the POD/user-defined default
2399 // constructor check.
2400 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002401 Context.getCanonicalType(Type).isConstQualified() &&
2402 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002403 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2404 << Var->getName()
2405 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002406#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002407 }
2408}
2409
Chris Lattner4b009652007-07-25 00:24:17 +00002410/// The declarators are chained together backwards, reverse the list.
2411Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2412 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002413 Decl *GroupDecl = static_cast<Decl*>(group);
2414 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002415 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002416
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002417 Decl *Group = dyn_cast<Decl>(GroupDecl);
2418 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002419 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002420 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002421 else { // reverse the list.
2422 while (Group) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002423 Decl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002424 Group->setNextDeclarator(NewGroup);
2425 NewGroup = Group;
2426 Group = Next;
2427 }
2428 }
2429 // Perform semantic analysis that depends on having fully processed both
2430 // the declarator and initializer.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002431 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002432 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2433 if (!IDecl)
2434 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002435 QualType T = IDecl->getType();
2436
Anders Carlsson68adbd12008-12-07 00:20:55 +00002437 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002438 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002439
2440 // FIXME: This won't give the correct result for
2441 // int a[10][n];
2442 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002443 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002444 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2445 SizeRange;
2446
Eli Friedman8ff07782008-02-15 18:16:39 +00002447 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002448 } else {
2449 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2450 // static storage duration, it shall not have a variable length array.
2451 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002452 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2453 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002454 IDecl->setInvalidDecl();
2455 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002456 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2457 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002458 IDecl->setInvalidDecl();
2459 }
2460 }
2461 } else if (T->isVariablyModifiedType()) {
2462 if (IDecl->isFileVarDecl()) {
2463 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2464 IDecl->setInvalidDecl();
2465 } else {
2466 if (IDecl->getStorageClass() == VarDecl::Extern) {
2467 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2468 IDecl->setInvalidDecl();
2469 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002470 }
2471 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002472
Steve Naroff6a0e2092007-09-12 14:07:44 +00002473 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2474 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002475 if (IDecl->isBlockVarDecl() &&
2476 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002477 if (!IDecl->isInvalidDecl() &&
2478 DiagnoseIncompleteType(IDecl->getLocation(), T,
2479 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002480 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002481 }
2482 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2483 // object that has file scope without an initializer, and without a
2484 // storage-class specifier or with the storage-class specifier "static",
2485 // constitutes a tentative definition. Note: A tentative definition with
2486 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002487 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002488 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002489 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2490 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002491 } else if (!IDecl->isInvalidDecl() &&
2492 DiagnoseIncompleteType(IDecl->getLocation(), T,
2493 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002494 // C99 6.9.2p3: If the declaration of an identifier for an object is
2495 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2496 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002497 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002498 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002499 if (IDecl->isFileVarDecl())
2500 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002501 }
2502 return NewGroup;
2503}
Steve Naroff91b03f72007-08-28 03:03:08 +00002504
Chris Lattner3e254fb2008-04-08 04:40:51 +00002505/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2506/// to introduce parameters into function prototype scope.
2507Sema::DeclTy *
2508Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002509 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002510
Chris Lattner3e254fb2008-04-08 04:40:51 +00002511 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002512 VarDecl::StorageClass StorageClass = VarDecl::None;
2513 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2514 StorageClass = VarDecl::Register;
2515 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002516 Diag(DS.getStorageClassSpecLoc(),
2517 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002518 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002519 }
2520 if (DS.isThreadSpecified()) {
2521 Diag(DS.getThreadSpecLoc(),
2522 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002523 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002524 }
2525
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002526 // Check that there are no default arguments inside the type of this
2527 // parameter (C++ only).
2528 if (getLangOptions().CPlusPlus)
2529 CheckExtraCXXDefaultArguments(D);
2530
Chris Lattner3e254fb2008-04-08 04:40:51 +00002531 // In this context, we *do not* check D.getInvalidType(). If the declarator
2532 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2533 // though it will not reflect the user specified type.
2534 QualType parmDeclType = GetTypeForDeclarator(D, S);
2535
2536 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2537
Chris Lattner4b009652007-07-25 00:24:17 +00002538 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2539 // Can this happen for params? We already checked that they don't conflict
2540 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002541 IdentifierInfo *II = D.getIdentifier();
Chris Lattner310dea32009-01-21 02:38:50 +00002542 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00002543 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattner310dea32009-01-21 02:38:50 +00002544 if (PrevDecl->isTemplateParameter()) {
2545 // Maybe we will complain about the shadowed template parameter.
2546 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2547 // Just pretend that we didn't see the previous declaration.
2548 PrevDecl = 0;
2549 } else if (S->isDeclScope(PrevDecl)) {
2550 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002551
Chris Lattner310dea32009-01-21 02:38:50 +00002552 // Recover by removing the name
2553 II = 0;
2554 D.SetIdentifier(0, D.getIdentifierLoc());
2555 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002556 }
Chris Lattner4b009652007-07-25 00:24:17 +00002557 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002558
2559 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2560 // Doing the promotion here has a win and a loss. The win is the type for
2561 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2562 // code generator). The loss is the orginal type isn't preserved. For example:
2563 //
2564 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2565 // int blockvardecl[5];
2566 // sizeof(parmvardecl); // size == 4
2567 // sizeof(blockvardecl); // size == 20
2568 // }
2569 //
2570 // For expressions, all implicit conversions are captured using the
2571 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2572 //
2573 // FIXME: If a source translation tool needs to see the original type, then
2574 // we need to consider storing both types (in ParmVarDecl)...
2575 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002576 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002577 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002578 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002579 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002580 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002581
Chris Lattner3e254fb2008-04-08 04:40:51 +00002582 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2583 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002584 parmDeclType, StorageClass,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002585 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002586
Chris Lattner3e254fb2008-04-08 04:40:51 +00002587 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002588 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002589
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002590 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2591 if (D.getCXXScopeSpec().isSet()) {
2592 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2593 << D.getCXXScopeSpec().getRange();
2594 New->setInvalidDecl();
2595 }
2596
Douglas Gregor8acb7272008-12-11 16:49:14 +00002597 // Add the parameter declaration into this scope.
2598 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002599 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002600 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002601
Chris Lattner9b384ca2008-06-29 00:02:00 +00002602 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002603 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002604
Chris Lattner4b009652007-07-25 00:24:17 +00002605}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002606
Douglas Gregor65075ec2009-01-23 16:23:13 +00002607void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00002608 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2609 "Not a function declarator!");
2610 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002611
Chris Lattner4b009652007-07-25 00:24:17 +00002612 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2613 // for a K&R function.
2614 if (!FTI.hasPrototype) {
2615 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002616 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002617 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2618 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002619 // Implicitly declare the argument as type 'int' for lack of a better
2620 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002621 DeclSpec DS;
2622 const char* PrevSpec; // unused
2623 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2624 PrevSpec);
2625 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2626 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor65075ec2009-01-23 16:23:13 +00002627 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002628 }
2629 }
Douglas Gregor65075ec2009-01-23 16:23:13 +00002630 }
2631}
2632
2633Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2634 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2635 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2636 "Not a function declarator!");
2637 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2638
2639 if (FTI.hasPrototype) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002640 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002641 }
2642
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002643 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002644
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002645 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002646 ActOnDeclarator(ParentScope, D, 0,
2647 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002648}
2649
2650Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2651 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002652 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002653
2654 // See if this is a redefinition.
2655 const FunctionDecl *Definition;
2656 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002657 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002658 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002659 }
2660
Douglas Gregor8acb7272008-12-11 16:49:14 +00002661 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002662
Chris Lattner3e254fb2008-04-08 04:40:51 +00002663 // Check the validity of our function parameters
2664 CheckParmsForFunctionDef(FD);
2665
2666 // Introduce our parameters into the function scope
2667 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2668 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002669 Param->setOwningFunction(FD);
2670
Chris Lattner3e254fb2008-04-08 04:40:51 +00002671 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002672 if (Param->getIdentifier())
2673 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002674 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002675
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002676 // Checking attributes of current function definition
2677 // dllimport attribute.
2678 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2679 // dllimport attribute cannot be applied to definition.
2680 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2681 Diag(FD->getLocation(),
2682 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2683 << "dllimport";
2684 FD->setInvalidDecl();
2685 return FD;
2686 } else {
2687 // If a symbol previously declared dllimport is later defined, the
2688 // attribute is ignored in subsequent references, and a warning is
2689 // emitted.
2690 Diag(FD->getLocation(),
2691 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2692 << FD->getNameAsCString() << "dllimport";
2693 }
2694 }
Chris Lattner4b009652007-07-25 00:24:17 +00002695 return FD;
2696}
2697
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002698Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002699 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002700 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002701 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002702 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002703 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002704 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002705 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002706 } else
2707 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002708 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002709 // Verify and clean out per-function state.
2710
2711 // Check goto/label use.
2712 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2713 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2714 // Verify that we have no forward references left. If so, there was a goto
2715 // or address of a label taken, but no definition of it. Label fwd
2716 // definitions are indicated with a null substmt.
2717 if (I->second->getSubStmt() == 0) {
2718 LabelStmt *L = I->second;
2719 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002720 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002721
2722 // At this point, we have gotos that use the bogus label. Stitch it into
2723 // the function body so that they aren't leaked and that the AST is well
2724 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002725 if (Body) {
2726 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002727 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002728 } else {
2729 // The whole function wasn't parsed correctly, just delete this.
2730 delete L;
2731 }
Chris Lattner4b009652007-07-25 00:24:17 +00002732 }
2733 }
2734 LabelMap.clear();
2735
Steve Naroff99ee4302007-11-11 23:20:51 +00002736 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002737}
2738
Chris Lattner4b009652007-07-25 00:24:17 +00002739/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2740/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002741NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2742 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002743 // Extension in C99. Legal in C90, but warn about it.
2744 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002745 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002746 else
Chris Lattner65cae292008-11-19 08:23:25 +00002747 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002748
2749 // FIXME: handle stuff like:
2750 // void foo() { extern float X(); }
2751 // void bar() { X(); } <-- implicit decl for X in another scope.
2752
2753 // Set a Declarator for the implicit definition: int foo();
2754 const char *Dummy;
2755 DeclSpec DS;
2756 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2757 Error = Error; // Silence warning.
2758 assert(!Error && "Error setting up implicit decl!");
2759 Declarator D(DS, Declarator::BlockContext);
Chris Lattnerdefaf412009-01-20 19:11:22 +00002760 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Chris Lattner4b009652007-07-25 00:24:17 +00002761 D.SetIdentifier(&II, Loc);
2762
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002763 // Insert this function into translation-unit scope.
2764
2765 DeclContext *PrevDC = CurContext;
2766 CurContext = Context.getTranslationUnitDecl();
2767
Steve Naroff9104f3c2008-04-04 14:32:09 +00002768 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002769 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002770 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002771
2772 CurContext = PrevDC;
2773
Steve Naroff9104f3c2008-04-04 14:32:09 +00002774 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002775}
2776
2777
Chris Lattner82bb4792007-11-14 06:34:38 +00002778TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002779 Decl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002780 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002781 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002782
2783 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002784 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2785 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002786 D.getIdentifier(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002787 T);
2788 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002789 if (D.getInvalidType())
2790 NewTD->setInvalidDecl();
2791 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002792}
2793
Steve Naroff0acc9c92007-09-15 18:49:24 +00002794/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002795/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002796/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002797/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002798Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002799 SourceLocation KWLoc, const CXXScopeSpec &SS,
2800 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregord406b032009-02-06 22:42:48 +00002801 AttributeList *Attr) {
Douglas Gregorae644892008-12-15 16:32:14 +00002802 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002803 assert((Name != 0 || TK == TK_Definition) &&
2804 "Nameless record must be a definition!");
Douglas Gregor279272e2009-02-04 19:02:06 +00002805
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002806 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002807 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002808 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002809 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2810 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2811 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2812 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002813 }
2814
Douglas Gregorb748fc52009-01-12 22:49:06 +00002815 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002816 DeclContext *DC = CurContext;
Douglas Gregor09be81b2009-02-04 17:27:36 +00002817 NamedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002818
Douglas Gregor98b27542009-01-17 00:42:38 +00002819 bool Invalid = false;
2820
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002821 if (Name && SS.isNotEmpty()) {
2822 // We have a nested-name tag ('struct foo::bar').
2823
2824 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002825 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002826 Name = 0;
2827 goto CreateNewDecl;
2828 }
2829
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002830 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor2d87eb02009-02-03 00:34:39 +00002831 SearchDC = DC;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002832 // Look-up name inside 'foo::'.
Steve Naroffc349ee22009-01-29 00:07:50 +00002833 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor7a7be652009-02-03 19:21:40 +00002834 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002835
2836 // A tag 'foo::bar' must already exist.
2837 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002838 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002839 Name = 0;
2840 goto CreateNewDecl;
2841 }
Chris Lattner310dea32009-01-21 02:38:50 +00002842 } else if (Name) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002843 // If this is a named struct, check to see if there was a previous forward
2844 // declaration or definition.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002845 // FIXME: We're looking into outer scopes here, even when we
2846 // shouldn't be. Doing so can result in ambiguities that we
2847 // shouldn't be diagnosing.
Douglas Gregor362c8952009-02-03 19:26:08 +00002848 LookupResult R = LookupName(S, Name, LookupTagName,
2849 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor7a7be652009-02-03 19:21:40 +00002850 if (R.isAmbiguous()) {
2851 DiagnoseAmbiguousLookup(R, Name, NameLoc);
2852 // FIXME: This is not best way to recover from case like:
2853 //
2854 // struct S s;
2855 //
2856 // causes needless err_ovl_no_viable_function_in_init latter.
2857 Name = 0;
2858 PrevDecl = 0;
2859 Invalid = true;
2860 }
2861 else
Douglas Gregor09be81b2009-02-04 17:27:36 +00002862 PrevDecl = R;
Douglas Gregordb568cf2009-01-08 20:45:30 +00002863
2864 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2865 // FIXME: This makes sure that we ignore the contexts associated
2866 // with C structs, unions, and enums when looking for a matching
2867 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002868 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002869 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2870 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002871 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002872 }
2873
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002874 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002875 // Maybe we will complain about the shadowed template parameter.
2876 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2877 // Just pretend that we didn't see the previous declaration.
2878 PrevDecl = 0;
2879 }
2880
Ted Kremenekd4434152008-09-02 21:26:19 +00002881 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002882 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002883 // If this is a use of a previous tag, or if the tag is already declared
2884 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002885 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002886 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002887 // Make sure that this wasn't declared as an enum and now used as a
2888 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002889 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002890 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002891 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002892 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002893 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002894 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002895 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002896 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002897 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002898
Douglas Gregorae644892008-12-15 16:32:14 +00002899 // FIXME: In the future, return a variant or some other clue
2900 // for the consumer of this Decl to know it doesn't own it.
2901 // For our current ASTs this shouldn't be a problem, but will
2902 // need to be changed with DeclGroups.
2903 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002904 return PrevDecl;
Douglas Gregor279272e2009-02-04 19:02:06 +00002905
Douglas Gregorae644892008-12-15 16:32:14 +00002906 // Diagnose attempts to redefine a tag.
2907 if (TK == TK_Definition) {
2908 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2909 Diag(NameLoc, diag::err_redefinition) << Name;
2910 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002911 // If this is a redefinition, recover by making this
2912 // struct be anonymous, which will make any later
2913 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002914 Name = 0;
2915 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002916 Invalid = true;
2917 } else {
2918 // If the type is currently being defined, complain
2919 // about a nested redefinition.
2920 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2921 if (Tag->isBeingDefined()) {
2922 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2923 Diag(PrevTagDecl->getLocation(),
2924 diag::note_previous_definition);
2925 Name = 0;
2926 PrevDecl = 0;
2927 Invalid = true;
2928 }
Douglas Gregorae644892008-12-15 16:32:14 +00002929 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002930
Douglas Gregorae644892008-12-15 16:32:14 +00002931 // Okay, this is definition of a previously declared or referenced
2932 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002933 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002934 }
Douglas Gregorae644892008-12-15 16:32:14 +00002935 // If we get here we have (another) forward declaration or we
2936 // have a definition. Just create a new decl.
2937 } else {
2938 // If we get here, this is a definition of a new tag type in a nested
2939 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2940 // new decl/type. We set PrevDecl to NULL so that the entities
2941 // have distinct types.
2942 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002943 }
Douglas Gregorae644892008-12-15 16:32:14 +00002944 // If we get here, we're going to create a new Decl. If PrevDecl
2945 // is non-NULL, it's a definition of the tag declared by
2946 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002947 } else {
Douglas Gregorb31f2942009-01-28 17:15:10 +00002948 // PrevDecl is a namespace, template, or anything else
2949 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002950 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002951 // The tag name clashes with a namespace name, issue an error and
2952 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002953 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002954 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002955 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002956 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002957 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002958 } else {
2959 // The existing declaration isn't relevant to us; we're in a
2960 // new scope, so clear out the previous declaration.
2961 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002962 }
Chris Lattner4b009652007-07-25 00:24:17 +00002963 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002964 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2965 (Kind != TagDecl::TK_enum)) {
2966 // C++ [basic.scope.pdecl]p5:
2967 // -- for an elaborated-type-specifier of the form
2968 //
2969 // class-key identifier
2970 //
2971 // if the elaborated-type-specifier is used in the
2972 // decl-specifier-seq or parameter-declaration-clause of a
2973 // function defined in namespace scope, the identifier is
2974 // declared as a class-name in the namespace that contains
2975 // the declaration; otherwise, except as a friend
2976 // declaration, the identifier is declared in the smallest
2977 // non-class, non-function-prototype scope that contains the
2978 // declaration.
2979 //
2980 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2981 // C structs and unions.
2982
2983 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002984 // FIXME: We would like to maintain the current DeclContext as the
2985 // lexical context,
Douglas Gregor2d87eb02009-02-03 00:34:39 +00002986 while (SearchDC->isRecord())
2987 SearchDC = SearchDC->getParent();
Douglas Gregorcab994d2009-01-09 22:42:13 +00002988
2989 // Find the scope where we'll be declaring the tag.
2990 while (S->isClassScope() ||
2991 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00002992 ((S->getFlags() & Scope::DeclScope) == 0) ||
2993 (S->getEntity() &&
2994 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00002995 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00002996 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002997
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002998CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002999
3000 // If there is an identifier, use the location of the identifier as the
3001 // location of the decl, otherwise use the location of the struct/union
3002 // keyword.
3003 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3004
Douglas Gregorae644892008-12-15 16:32:14 +00003005 // Otherwise, create a new declaration. If there is a previous
3006 // declaration of the same entity, the two will be linked via
3007 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003008 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00003009
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003010 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003011 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3012 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003013 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003014 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003015 // If this is an undefined enum, warn.
3016 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003017 } else {
3018 // struct/union/class
3019
Chris Lattner4b009652007-07-25 00:24:17 +00003020 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3021 // struct X { int A; } D; D should chain to X.
Douglas Gregord406b032009-02-06 22:42:48 +00003022 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003023 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003024 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003025 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregord406b032009-02-06 22:42:48 +00003026 else
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003027 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorae644892008-12-15 16:32:14 +00003028 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003029 }
Douglas Gregorae644892008-12-15 16:32:14 +00003030
3031 if (Kind != TagDecl::TK_enum) {
3032 // Handle #pragma pack: if the #pragma pack stack has non-default
3033 // alignment, make up a packed attribute for this decl. These
3034 // attributes are checked when the ASTContext lays out the
3035 // structure.
3036 //
3037 // It is important for implementing the correct semantics that this
3038 // happen here (in act on tag decl). The #pragma pack stack is
3039 // maintained as a result of parser callbacks which can occur at
3040 // many points during the parsing of a struct declaration (because
3041 // the #pragma tokens are effectively skipped over during the
3042 // parsing of the struct).
3043 if (unsigned Alignment = PackContext.getAlignment())
3044 New->addAttr(new PackedAttr(Alignment * 8));
3045 }
3046
Douglas Gregorb31f2942009-01-28 17:15:10 +00003047 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3048 // C++ [dcl.typedef]p3:
3049 // [...] Similarly, in a given scope, a class or enumeration
3050 // shall not be declared with the same name as a typedef-name
3051 // that is declared in that scope and refers to a type other
3052 // than the class or enumeration itself.
Douglas Gregor52ae30c2009-01-30 01:04:22 +00003053 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregorb31f2942009-01-28 17:15:10 +00003054 TypedefDecl *PrevTypedef = 0;
3055 if (Lookup.getKind() == LookupResult::Found)
3056 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3057
3058 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3059 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3060 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3061 Diag(Loc, diag::err_tag_definition_of_typedef)
3062 << Context.getTypeDeclType(New)
3063 << PrevTypedef->getUnderlyingType();
3064 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3065 Invalid = true;
3066 }
3067 }
3068
Douglas Gregor98b27542009-01-17 00:42:38 +00003069 if (Invalid)
3070 New->setInvalidDecl();
3071
Douglas Gregorae644892008-12-15 16:32:14 +00003072 if (Attr)
3073 ProcessDeclAttributeList(New, Attr);
3074
Douglas Gregor98b27542009-01-17 00:42:38 +00003075 // If we're declaring or defining a tag in function prototype scope
3076 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003077 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3078 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3079
Douglas Gregorae644892008-12-15 16:32:14 +00003080 // Set the lexical context. If the tag has a C++ scope specifier, the
3081 // lexical context will be different from the semantic context.
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003082 New->setLexicalDeclContext(CurContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003083
3084 if (TK == TK_Definition)
3085 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003086
3087 // If this has an identifier, add it to the scope stack.
3088 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003089 S = getNonFieldDeclScope(S);
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003090 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003091 } else {
Douglas Gregor2d87eb02009-02-03 00:34:39 +00003092 CurContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003093 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003094
Chris Lattner4b009652007-07-25 00:24:17 +00003095 return New;
3096}
3097
Douglas Gregordb568cf2009-01-08 20:45:30 +00003098void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003099 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003100 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3101
3102 // Enter the tag context.
3103 PushDeclContext(S, Tag);
3104
3105 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3106 FieldCollector->StartClass();
3107
3108 if (Record->getIdentifier()) {
3109 // C++ [class]p2:
3110 // [...] The class-name is also inserted into the scope of the
3111 // class itself; this is known as the injected-class-name. For
3112 // purposes of access checking, the injected-class-name is treated
3113 // as if it were a public member name.
3114 RecordDecl *InjectedClassName
3115 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3116 CurContext, Record->getLocation(),
3117 Record->getIdentifier(), Record);
3118 InjectedClassName->setImplicit();
3119 PushOnScopeChains(InjectedClassName, S);
3120 }
3121 }
3122}
3123
3124void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregor279272e2009-02-04 19:02:06 +00003125 AdjustDeclIfTemplate(TagD);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003126 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3127
3128 if (isa<CXXRecordDecl>(Tag))
3129 FieldCollector->FinishClass();
3130
3131 // Exit this scope of this tag's definition.
3132 PopDeclContext();
3133
3134 // Notify the consumer that we've defined a tag.
3135 Consumer.HandleTagDeclDefinition(Tag);
3136}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003137
Chris Lattnera73e2202008-11-12 21:17:48 +00003138/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3139/// types into constant array types in certain situations which would otherwise
3140/// be errors (for GCC compatibility).
3141static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3142 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003143 // This method tries to turn a variable array into a constant
3144 // array even when the size isn't an ICE. This is necessary
3145 // for compatibility with code that depends on gcc's buggy
3146 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003147 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3148 if (!VLATy) return QualType();
3149
Anders Carlsson8c3de802008-12-19 20:58:05 +00003150 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003151 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003152 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003153 return QualType();
3154
Anders Carlsson8c3de802008-12-19 20:58:05 +00003155 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3156 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes5ba3b262009-02-02 22:32:08 +00003157 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3158 return Context.getConstantArrayType(VLATy->getElementType(),
3159 Res, ArrayType::Normal, 0);
3160 return QualType();
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003161}
3162
Anders Carlsson108229a2008-12-06 20:33:04 +00003163bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003164 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003165 // FIXME: 6.7.2.1p4 - verify the field type.
3166
3167 llvm::APSInt Value;
3168 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3169 return true;
3170
Chris Lattner8464c372008-12-12 04:56:04 +00003171 // Zero-width bitfield is ok for anonymous field.
3172 if (Value == 0 && FieldName)
3173 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3174
3175 if (Value.isNegative())
3176 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003177
3178 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3179 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003180 if (TypeSize && Value.getZExtValue() > TypeSize)
3181 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3182 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003183
3184 return false;
3185}
3186
Steve Naroff0acc9c92007-09-15 18:49:24 +00003187/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003188/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003189Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003190 SourceLocation DeclStart,
3191 Declarator &D, ExprTy *BitfieldWidth) {
3192 IdentifierInfo *II = D.getIdentifier();
3193 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003194 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003195 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003196 if (II) Loc = D.getIdentifierLoc();
3197
3198 // FIXME: Unnamed fields can be handled in various different ways, for
3199 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003200
Chris Lattner4b009652007-07-25 00:24:17 +00003201 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003202 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3203 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003204
Chris Lattner4b009652007-07-25 00:24:17 +00003205 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3206 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003207 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003208 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003209 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003210 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003211 T = FixedTy;
3212 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003213 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003214 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003215 InvalidDecl = true;
3216 }
Chris Lattner4b009652007-07-25 00:24:17 +00003217 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003218
3219 if (BitWidth) {
3220 if (VerifyBitField(Loc, II, T, BitWidth))
3221 InvalidDecl = true;
3222 } else {
3223 // Not a bitfield.
3224
3225 // validate II.
3226
3227 }
3228
Chris Lattner4b009652007-07-25 00:24:17 +00003229 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003230 FieldDecl *NewFD;
3231
Douglas Gregor8acb7272008-12-11 16:49:14 +00003232 NewFD = FieldDecl::Create(Context, Record,
3233 Loc, II, T, BitWidth,
3234 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003235 DeclSpec::SCS_mutable);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003236
Douglas Gregordb568cf2009-01-08 20:45:30 +00003237 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003238 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003239 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3240 && !isa<TagDecl>(PrevDecl)) {
3241 Diag(Loc, diag::err_duplicate_member) << II;
3242 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3243 NewFD->setInvalidDecl();
3244 Record->setInvalidDecl();
3245 }
3246 }
3247
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003248 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003249 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003250 if (!T->isPODType())
3251 cast<CXXRecordDecl>(Record)->setPOD(false);
3252 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003253
Chris Lattner9b384ca2008-06-29 00:02:00 +00003254 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003255
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003256 if (D.getInvalidType() || InvalidDecl)
3257 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003258
Douglas Gregordb568cf2009-01-08 20:45:30 +00003259 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003260 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003261 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003262 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003263
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003264 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003265}
3266
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003267/// TranslateIvarVisibility - Translate visibility from a token ID to an
3268/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003269static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003270TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003271 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003272 default: assert(0 && "Unknown visitibility kind");
3273 case tok::objc_private: return ObjCIvarDecl::Private;
3274 case tok::objc_public: return ObjCIvarDecl::Public;
3275 case tok::objc_protected: return ObjCIvarDecl::Protected;
3276 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003277 }
3278}
3279
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003280/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3281/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003282Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003283 SourceLocation DeclStart,
3284 Declarator &D, ExprTy *BitfieldWidth,
3285 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003286
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003287 IdentifierInfo *II = D.getIdentifier();
3288 Expr *BitWidth = (Expr*)BitfieldWidth;
3289 SourceLocation Loc = DeclStart;
3290 if (II) Loc = D.getIdentifierLoc();
3291
3292 // FIXME: Unnamed fields can be handled in various different ways, for
3293 // example, unnamed unions inject all members into the struct namespace!
3294
Anders Carlsson108229a2008-12-06 20:33:04 +00003295 QualType T = GetTypeForDeclarator(D, S);
3296 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3297 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003298
3299 if (BitWidth) {
3300 // TODO: Validate.
3301 //printf("WARNING: BITFIELDS IGNORED!\n");
3302
3303 // 6.7.2.1p3
3304 // 6.7.2.1p4
3305
3306 } else {
3307 // Not a bitfield.
3308
3309 // validate II.
3310
3311 }
3312
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003313 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3314 // than a variably modified type.
3315 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003316 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003317 InvalidDecl = true;
3318 }
3319
Ted Kremenek173dd312008-07-23 18:04:17 +00003320 // Get the visibility (access control) for this ivar.
3321 ObjCIvarDecl::AccessControl ac =
3322 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3323 : ObjCIvarDecl::None;
3324
3325 // Construct the decl.
3326 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003327 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003328
Douglas Gregordb568cf2009-01-08 20:45:30 +00003329 if (II) {
Douglas Gregor09be81b2009-02-04 17:27:36 +00003330 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003331 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3332 && !isa<TagDecl>(PrevDecl)) {
3333 Diag(Loc, diag::err_duplicate_member) << II;
3334 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3335 NewID->setInvalidDecl();
3336 }
3337 }
3338
Ted Kremenek173dd312008-07-23 18:04:17 +00003339 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003340 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003341
3342 if (D.getInvalidType() || InvalidDecl)
3343 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003344
Douglas Gregordb568cf2009-01-08 20:45:30 +00003345 if (II) {
3346 // FIXME: When interfaces are DeclContexts, we'll need to add
3347 // these to the interface.
3348 S->AddDecl(NewID);
3349 IdResolver.AddDecl(NewID);
3350 }
3351
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003352 return NewID;
3353}
3354
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003355void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003356 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003357 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003358 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003359 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003360 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3361 assert(EnclosingDecl && "missing record or interface decl");
3362 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3363
Chris Lattner4b009652007-07-25 00:24:17 +00003364 // Verify that all the fields are okay.
3365 unsigned NumNamedMembers = 0;
3366 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003367
Chris Lattner4b009652007-07-25 00:24:17 +00003368 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003369 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3370 assert(FD && "missing field decl");
3371
Chris Lattner4b009652007-07-25 00:24:17 +00003372 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003373 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003374
Douglas Gregordb568cf2009-01-08 20:45:30 +00003375 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003376 // Remember all fields written by the user.
3377 RecFields.push_back(FD);
3378 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003379
Chris Lattner4b009652007-07-25 00:24:17 +00003380 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003381 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003382 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003383 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003384 FD->setInvalidDecl();
3385 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003386 continue;
3387 }
Chris Lattner4b009652007-07-25 00:24:17 +00003388 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3389 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003390 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003391 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3392 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003393 FD->setInvalidDecl();
3394 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003395 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003396 }
Chris Lattner4b009652007-07-25 00:24:17 +00003397 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003398 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003399 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003400 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3401 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003402 FD->setInvalidDecl();
3403 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003404 continue;
3405 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003406 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003407 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003408 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003409 FD->setInvalidDecl();
3410 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003411 continue;
3412 }
Chris Lattner4b009652007-07-25 00:24:17 +00003413 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003414 if (Record)
3415 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003416 }
Chris Lattner4b009652007-07-25 00:24:17 +00003417 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3418 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003419 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003420 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3421 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003422 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003423 Record->setHasFlexibleArrayMember(true);
3424 } else {
3425 // If this is a struct/class and this is not the last element, reject
3426 // it. Note that GCC supports variable sized arrays in the middle of
3427 // structures.
3428 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003429 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003430 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003431 FD->setInvalidDecl();
3432 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003433 continue;
3434 }
Chris Lattner4b009652007-07-25 00:24:17 +00003435 // We support flexible arrays at the end of structs in other structs
3436 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003437 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003438 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003439 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003440 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003441 }
3442 }
3443 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003444 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003445 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003446 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003447 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003448 FD->setInvalidDecl();
3449 EnclosingDecl->setInvalidDecl();
3450 continue;
3451 }
Chris Lattner4b009652007-07-25 00:24:17 +00003452 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003453 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003454 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003455 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003456
Chris Lattner4b009652007-07-25 00:24:17 +00003457 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003458 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003459 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003460 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003461 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003462 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003463 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003464 // Must enforce the rule that ivars in the base classes may not be
3465 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003466 if (ID->getSuperClass()) {
3467 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3468 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3469 ObjCIvarDecl* Ivar = (*IVI);
3470 IdentifierInfo *II = Ivar->getIdentifier();
3471 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3472 if (prevIvar) {
3473 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003474 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003475 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003476 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003477 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003478 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003479 else if (ObjCImplementationDecl *IMPDecl =
3480 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003481 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3482 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003483 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003484 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003485 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003486
3487 if (Attr)
3488 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003489}
3490
Steve Naroff0acc9c92007-09-15 18:49:24 +00003491Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003492 DeclTy *lastEnumConst,
3493 SourceLocation IdLoc, IdentifierInfo *Id,
3494 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003495 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003496 EnumConstantDecl *LastEnumConst =
3497 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3498 Expr *Val = static_cast<Expr*>(val);
3499
Chris Lattnera7549902007-08-26 06:24:45 +00003500 // The scope passed in may not be a decl scope. Zip up the scope tree until
3501 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003502 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003503
Chris Lattner4b009652007-07-25 00:24:17 +00003504 // Verify that there isn't already something declared with this name in this
3505 // scope.
Douglas Gregor09be81b2009-02-04 17:27:36 +00003506 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003507 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003508 // Maybe we will complain about the shadowed template parameter.
3509 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3510 // Just pretend that we didn't see the previous declaration.
3511 PrevDecl = 0;
3512 }
3513
3514 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003515 // When in C++, we may get a TagDecl with the same name; in this case the
3516 // enum constant will 'hide' the tag.
3517 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3518 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003519 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003520 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003521 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003522 else
Chris Lattner65cae292008-11-19 08:23:25 +00003523 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003524 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003525 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003526 return 0;
3527 }
3528 }
3529
3530 llvm::APSInt EnumVal(32);
3531 QualType EltTy;
3532 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003533 // Make sure to promote the operand type to int.
3534 UsualUnaryConversions(Val);
3535
Chris Lattner4b009652007-07-25 00:24:17 +00003536 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3537 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003538 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003539 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003540 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003541 } else {
3542 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003543 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003544 }
3545
3546 if (!Val) {
3547 if (LastEnumConst) {
3548 // Assign the last value + 1.
3549 EnumVal = LastEnumConst->getInitVal();
3550 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003551
3552 // Check for overflow on increment.
3553 if (EnumVal < LastEnumConst->getInitVal())
3554 Diag(IdLoc, diag::warn_enum_value_overflow);
3555
Chris Lattnere7f53a42007-08-27 17:37:24 +00003556 EltTy = LastEnumConst->getType();
3557 } else {
3558 // First value, set to zero.
3559 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003560 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003561 }
Chris Lattner4b009652007-07-25 00:24:17 +00003562 }
3563
Chris Lattnere4650482008-03-15 06:12:44 +00003564 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003565 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003566 Val, EnumVal);
Chris Lattner4b009652007-07-25 00:24:17 +00003567
3568 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003569 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003570
Chris Lattner4b009652007-07-25 00:24:17 +00003571 return New;
3572}
3573
Steve Naroffb0726b82008-08-07 14:08:16 +00003574// FIXME: For consistency with ActOnFields(), we should have the parser
3575// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003576void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003577 DeclTy **Elements, unsigned NumElements) {
3578 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003579 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003580
Chris Lattner435c3fd2007-08-28 05:10:31 +00003581 // TODO: If the result value doesn't fit in an int, it must be a long or long
3582 // long value. ISO C does not support this, but GCC does as an extension,
3583 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003584 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003585
Chris Lattner206754a2007-08-28 06:15:15 +00003586 // Verify that all the values are okay, compute the size of the values, and
3587 // reverse the list.
3588 unsigned NumNegativeBits = 0;
3589 unsigned NumPositiveBits = 0;
3590
3591 // Keep track of whether all elements have type int.
3592 bool AllElementsInt = true;
3593
Chris Lattner4b009652007-07-25 00:24:17 +00003594 for (unsigned i = 0; i != NumElements; ++i) {
3595 EnumConstantDecl *ECD =
3596 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3597 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003598
3599 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003600 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003601 assert(InitVal.getBitWidth() >= IntWidth &&
3602 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003603 if (InitVal.getBitWidth() > IntWidth) {
3604 llvm::APSInt V(InitVal);
3605 V.trunc(IntWidth);
3606 V.extend(InitVal.getBitWidth());
3607 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003608 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3609 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003610 }
Chris Lattner206754a2007-08-28 06:15:15 +00003611
3612 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003613 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003614 NumPositiveBits = std::max(NumPositiveBits,
3615 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003616 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003617 NumNegativeBits = std::max(NumNegativeBits,
3618 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003619
Chris Lattner206754a2007-08-28 06:15:15 +00003620 // Keep track of whether every enum element has type int (very commmon).
3621 if (AllElementsInt)
3622 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003623 }
3624
Chris Lattner206754a2007-08-28 06:15:15 +00003625 // Figure out the type that should be used for this enum.
3626 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3627 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003628 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003629
3630 if (NumNegativeBits) {
3631 // If there is a negative value, figure out the smallest integer type (of
3632 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003633 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003634 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003635 BestWidth = IntWidth;
3636 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003637 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003638
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003639 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003640 BestType = Context.LongTy;
3641 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003642 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003643
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003644 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003645 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3646 BestType = Context.LongLongTy;
3647 }
3648 }
3649 } else {
3650 // If there is no negative value, figure out which of uint, ulong, ulonglong
3651 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003652 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003653 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003654 BestWidth = IntWidth;
3655 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003656 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003657 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003658 } else {
3659 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003660 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003661 "How could an initializer get larger than ULL?");
3662 BestType = Context.UnsignedLongLongTy;
3663 }
3664 }
3665
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003666 // Loop over all of the enumerator constants, changing their types to match
3667 // the type of the enum if needed.
3668 for (unsigned i = 0; i != NumElements; ++i) {
3669 EnumConstantDecl *ECD =
3670 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3671 if (!ECD) continue; // Already issued a diagnostic.
3672
3673 // Standard C says the enumerators have int type, but we allow, as an
3674 // extension, the enumerators to be larger than int size. If each
3675 // enumerator value fits in an int, type it as an int, otherwise type it the
3676 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3677 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003678 if (ECD->getType() == Context.IntTy) {
3679 // Make sure the init value is signed.
3680 llvm::APSInt IV = ECD->getInitVal();
3681 IV.setIsSigned(true);
3682 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003683
3684 if (getLangOptions().CPlusPlus)
3685 // C++ [dcl.enum]p4: Following the closing brace of an
3686 // enum-specifier, each enumerator has the type of its
3687 // enumeration.
3688 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003689 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003690 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003691
3692 // Determine whether the value fits into an int.
3693 llvm::APSInt InitVal = ECD->getInitVal();
3694 bool FitsInInt;
3695 if (InitVal.isUnsigned() || !InitVal.isNegative())
3696 FitsInInt = InitVal.getActiveBits() < IntWidth;
3697 else
3698 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3699
3700 // If it fits into an integer type, force it. Otherwise force it to match
3701 // the enum decl type.
3702 QualType NewTy;
3703 unsigned NewWidth;
3704 bool NewSign;
3705 if (FitsInInt) {
3706 NewTy = Context.IntTy;
3707 NewWidth = IntWidth;
3708 NewSign = true;
3709 } else if (ECD->getType() == BestType) {
3710 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003711 if (getLangOptions().CPlusPlus)
3712 // C++ [dcl.enum]p4: Following the closing brace of an
3713 // enum-specifier, each enumerator has the type of its
3714 // enumeration.
3715 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003716 continue;
3717 } else {
3718 NewTy = BestType;
3719 NewWidth = BestWidth;
3720 NewSign = BestType->isSignedIntegerType();
3721 }
3722
3723 // Adjust the APSInt value.
3724 InitVal.extOrTrunc(NewWidth);
3725 InitVal.setIsSigned(NewSign);
3726 ECD->setInitVal(InitVal);
3727
3728 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003729 if (ECD->getInitExpr())
3730 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3731 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003732 if (getLangOptions().CPlusPlus)
3733 // C++ [dcl.enum]p4: Following the closing brace of an
3734 // enum-specifier, each enumerator has the type of its
3735 // enumeration.
3736 ECD->setType(EnumType);
3737 else
3738 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003739 }
Chris Lattner206754a2007-08-28 06:15:15 +00003740
Douglas Gregor8acb7272008-12-11 16:49:14 +00003741 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003742}
3743
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003744Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003745 ExprArg expr) {
3746 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3747
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003748 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003749}
3750
Douglas Gregorad17e372008-12-16 22:23:02 +00003751
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003752void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3753 ExprTy *alignment, SourceLocation PragmaLoc,
3754 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3755 Expr *Alignment = static_cast<Expr *>(alignment);
3756
3757 // If specified then alignment must be a "small" power of two.
3758 unsigned AlignmentVal = 0;
3759 if (Alignment) {
3760 llvm::APSInt Val;
3761 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3762 !Val.isPowerOf2() ||
3763 Val.getZExtValue() > 16) {
3764 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3765 delete Alignment;
3766 return; // Ignore
3767 }
3768
3769 AlignmentVal = (unsigned) Val.getZExtValue();
3770 }
3771
3772 switch (Kind) {
3773 case Action::PPK_Default: // pack([n])
3774 PackContext.setAlignment(AlignmentVal);
3775 break;
3776
3777 case Action::PPK_Show: // pack(show)
3778 // Show the current alignment, making sure to show the right value
3779 // for the default.
3780 AlignmentVal = PackContext.getAlignment();
3781 // FIXME: This should come from the target.
3782 if (AlignmentVal == 0)
3783 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003784 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003785 break;
3786
3787 case Action::PPK_Push: // pack(push [, id] [, [n])
3788 PackContext.push(Name);
3789 // Set the new alignment if specified.
3790 if (Alignment)
3791 PackContext.setAlignment(AlignmentVal);
3792 break;
3793
3794 case Action::PPK_Pop: // pack(pop [, id] [, n])
3795 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3796 // "#pragma pack(pop, identifier, n) is undefined"
3797 if (Alignment && Name)
3798 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3799
3800 // Do the pop.
3801 if (!PackContext.pop(Name)) {
3802 // If a name was specified then failure indicates the name
3803 // wasn't found. Otherwise failure indicates the stack was
3804 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003805 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3806 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003807
3808 // FIXME: Warn about popping named records as MSVC does.
3809 } else {
3810 // Pop succeeded, set the new alignment if specified.
3811 if (Alignment)
3812 PackContext.setAlignment(AlignmentVal);
3813 }
3814 break;
3815
3816 default:
3817 assert(0 && "Invalid #pragma pack kind.");
3818 }
3819}
3820
3821bool PragmaPackStack::pop(IdentifierInfo *Name) {
3822 if (Stack.empty())
3823 return false;
3824
3825 // If name is empty just pop top.
3826 if (!Name) {
3827 Alignment = Stack.back().first;
3828 Stack.pop_back();
3829 return true;
3830 }
3831
3832 // Otherwise, find the named record.
3833 for (unsigned i = Stack.size(); i != 0; ) {
3834 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003835 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003836 // Found it, pop up to and including this record.
3837 Alignment = Stack[i].first;
3838 Stack.erase(Stack.begin() + i, Stack.end());
3839 return true;
3840 }
3841 }
3842
3843 return false;
3844}