blob: fe604960f7200d61a9ae6fc098e04563141d4340 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.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 Gregorb0212bd2008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000042 LookupResult Result = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000043
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000044 Decl *IIDecl = 0;
45 switch (Result.getKind()) {
46 case LookupResult::NotFound:
47 case LookupResult::FoundOverloaded:
48 case LookupResult::AmbiguousBaseSubobjectTypes:
49 case LookupResult::AmbiguousBaseSubobjects:
50 // FIXME: In the event of an ambiguous lookup, we could visit all of
51 // the entities found to determine whether they are all types. This
52 // might provide better diagnostics.
53 return 0;
54
55 case LookupResult::Found:
56 IIDecl = Result.getAsDecl();
57 break;
58 }
59
60 if (isa<TypedefDecl>(IIDecl) ||
61 isa<ObjCInterfaceDecl>(IIDecl) ||
62 isa<TagDecl>(IIDecl) ||
63 isa<TemplateTypeParmDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000064 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000065 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000066}
67
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000068DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000069 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000070 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000071 if (MD->isOutOfLineDefinition())
72 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073
74 // A C++ inline method is parsed *after* the topmost class it was declared in
75 // is fully parsed (it's "complete").
76 // The parsing of a C++ inline method happens at the declaration context of
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000077 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000078 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
79 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000080 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000081 DC = RD;
82
83 // Return the declaration context of the topmost class the inline method is
84 // declared in.
85 return DC;
86 }
87
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000088 if (isa<ObjCMethodDecl>(DC))
89 return Context.getTranslationUnitDecl();
90
91 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
92 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000093
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000094 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000095}
96
Douglas Gregor8acb7272008-12-11 16:49:14 +000097void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000098 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000099 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +0000100 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000101 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +0000102}
103
Chris Lattnerf3874bc2008-04-06 04:47:34 +0000104void Sema::PopDeclContext() {
105 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +0000106
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000107 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +0000108}
109
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000110/// Add this decl to the scope shadowed decl chains.
111void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-01-05 19:45:36 +0000112 // Move up the scope chain until we find the nearest enclosing
113 // non-transparent context. The declaration will be introduced into this
114 // scope.
115 while (S->getEntity() &&
116 ((DeclContext *)S->getEntity())->isTransparentContext())
117 S = S->getParent();
118
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000119 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000120
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000121 // Add scoped declarations into their context, so that they can be
122 // found later. Declarations without a context won't be inserted
123 // into any context.
124 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000125 CurContext->addDecl(SD);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000126
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000127 // C++ [basic.scope]p4:
128 // -- exactly one declaration shall declare a class name or
129 // enumeration name that is not a typedef name and the other
130 // declarations shall all refer to the same object or
131 // enumerator, or all refer to functions and function templates;
132 // in this case the class name or enumeration name is hidden.
133 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
134 // We are pushing the name of a tag (enum or class).
Douglas Gregor3a423132009-01-07 16:34:42 +0000135 if (CurContext->getLookupContext()
136 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000137 // We're pushing the tag into the current context, which might
138 // require some reshuffling in the identifier resolver.
139 IdentifierResolver::iterator
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000140 I = IdResolver.begin(TD->getDeclName(), CurContext,
141 false/*LookInParentCtx*/),
142 IEnd = IdResolver.end();
143 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
144 NamedDecl *PrevDecl = *I;
145 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
146 PrevDecl = *I, ++I) {
147 if (TD->declarationReplaces(*I)) {
148 // This is a redeclaration. Remove it from the chain and
149 // break out, so that we'll add in the shadowed
150 // declaration.
151 S->RemoveDecl(*I);
152 if (PrevDecl == *I) {
153 IdResolver.RemoveDecl(*I);
154 IdResolver.AddDecl(TD);
155 return;
156 } else {
157 IdResolver.RemoveDecl(*I);
158 break;
159 }
160 }
161 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000162
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000163 // There is already a declaration with the same name in the same
164 // scope, which is not a tag declaration. It must be found
165 // before we find the new declaration, so insert the new
166 // declaration at the end of the chain.
167 IdResolver.AddShadowedDecl(TD, PrevDecl);
168
169 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000170 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000171 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000172 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000173 // We are pushing the name of a function, which might be an
174 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000175 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000176 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000177 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000178 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000179 false/*LookInParentCtx*/),
180 IdResolver.end(),
181 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
182 FD));
183 if (Redecl != IdResolver.end()) {
184 // There is already a declaration of a function on our
185 // IdResolver chain. Replace it with this declaration.
186 S->RemoveDecl(*Redecl);
187 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000188 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000189 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000190
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000191 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000192}
193
Steve Naroff9637a9b2007-10-09 22:01:59 +0000194void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000195 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000196 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
197 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000198
Chris Lattner4b009652007-07-25 00:24:17 +0000199 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
200 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000201 Decl *TmpD = static_cast<Decl*>(*I);
202 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000203
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
205 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000206
Douglas Gregor8acb7272008-12-11 16:49:14 +0000207 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000208
Douglas Gregor8acb7272008-12-11 16:49:14 +0000209 // Remove this name from our lexical scope.
210 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000211 }
212}
213
Steve Naroffe57c21a2008-04-01 23:04:06 +0000214/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
215/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000216ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000217 // The third "scope" argument is 0 since we aren't enabling lazy built-in
218 // creation from this context.
219 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000220
Steve Naroff6384a012008-04-02 14:35:35 +0000221 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000222}
223
Douglas Gregor5eca99e2009-01-12 18:45:55 +0000224/// getNonFieldDeclScope - Retrieves the innermost scope, starting
225/// from S, where a non-field would be declared. This routine copes
226/// with the difference between C and C++ scoping rules in structs and
227/// unions. For example, the following code is well-formed in C but
228/// ill-formed in C++:
229/// @code
230/// struct S6 {
231/// enum { BAR } e;
232/// };
233///
234/// void test_S6() {
235/// struct S6 a;
236/// a.e = BAR;
237/// }
238/// @endcode
239/// For the declaration of BAR, this routine will return a different
240/// scope. The scope S will be the scope of the unnamed enumeration
241/// within S6. In C++, this routine will return the scope associated
242/// with S6, because the enumeration's scope is a transparent
243/// context but structures can contain non-field names. In C, this
244/// routine will return the translation unit scope, since the
245/// enumeration's scope is a transparent context and structures cannot
246/// contain non-field names.
247Scope *Sema::getNonFieldDeclScope(Scope *S) {
248 while (((S->getFlags() & Scope::DeclScope) == 0) ||
249 (S->getEntity() &&
250 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
251 (S->isClassScope() && !getLangOptions().CPlusPlus))
252 S = S->getParent();
253 return S;
254}
255
Steve Naroffe57c21a2008-04-01 23:04:06 +0000256/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000257/// namespace. NamespaceNameOnly - during lookup only namespace names
258/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
259/// 'When looking up a namespace-name in a using-directive or
260/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor78d70132009-01-14 22:20:51 +0000261///
262/// Note: The use of this routine is deprecated. Please use
263/// LookupName, LookupQualifiedName, or LookupParsedName instead.
264Sema::LookupResult
265Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
266 const DeclContext *LookupCtx,
267 bool enableLazyBuiltinCreation,
268 bool LookInParent,
269 bool NamespaceNameOnly) {
270 LookupCriteria::NameKind Kind;
271 if (NSI == Decl::IDNS_Ordinary) {
272 if (NamespaceNameOnly)
273 Kind = LookupCriteria::Namespace;
274 else
275 Kind = LookupCriteria::Ordinary;
276 } else if (NSI == Decl::IDNS_Tag)
277 Kind = LookupCriteria::Tag;
Chris Lattner50500f62009-01-16 19:44:00 +0000278 else {
279 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregor78d70132009-01-14 22:20:51 +0000280 Kind = LookupCriteria::Member;
Chris Lattner50500f62009-01-16 19:44:00 +0000281 }
282
Douglas Gregor78d70132009-01-14 22:20:51 +0000283 if (LookupCtx)
284 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
285 LookupCriteria(Kind, !LookInParent,
286 getLangOptions().CPlusPlus));
Douglas Gregordb568cf2009-01-08 20:45:30 +0000287
Douglas Gregor78d70132009-01-14 22:20:51 +0000288 // Unqualified lookup
289 return LookupName(S, Name,
290 LookupCriteria(Kind, !LookInParent,
291 getLangOptions().CPlusPlus));
Chris Lattner4b009652007-07-25 00:24:17 +0000292}
293
Chris Lattnera9c87f22008-05-05 22:18:14 +0000294void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000295 if (!Context.getBuiltinVaListType().isNull())
296 return;
297
298 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000299 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000300 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000301 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
302}
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
305/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000306ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
307 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000308 Builtin::ID BID = (Builtin::ID)bid;
309
Chris Lattnerb23469f2008-09-28 05:54:29 +0000310 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000311 InitBuiltinVaListType();
312
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000313 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000314 FunctionDecl *New = FunctionDecl::Create(Context,
315 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000316 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000317 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000318
Chris Lattnera9c87f22008-05-05 22:18:14 +0000319 // Create Decl objects for each parameter, adding them to the
320 // FunctionDecl.
321 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
322 llvm::SmallVector<ParmVarDecl*, 16> Params;
323 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
324 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
325 FT->getArgType(i), VarDecl::None, 0,
326 0));
Ted Kremenek8494c962009-01-14 00:42:25 +0000327 New->setParams(Context, &Params[0], Params.size());
Chris Lattnera9c87f22008-05-05 22:18:14 +0000328 }
329
330
331
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000332 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregord394a272009-01-09 18:51:29 +0000333 // FIXME: This is hideous. We need to teach PushOnScopeChains to
334 // relate Scopes to DeclContexts, and probably eliminate CurContext
335 // entirely, but we're not there yet.
336 DeclContext *SavedContext = CurContext;
337 CurContext = Context.getTranslationUnitDecl();
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000338 PushOnScopeChains(New, TUScope);
Douglas Gregord394a272009-01-09 18:51:29 +0000339 CurContext = SavedContext;
Chris Lattner4b009652007-07-25 00:24:17 +0000340 return New;
341}
342
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000343/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
344/// everything from the standard library is defined.
345NamespaceDecl *Sema::GetStdNamespace() {
346 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000347 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000348 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor78d70132009-01-14 22:20:51 +0000349 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000350 0, Global, /*enableLazyBuiltinCreation=*/false);
351 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
352 }
353 return StdNamespace;
354}
355
Chris Lattner4b009652007-07-25 00:24:17 +0000356/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
357/// and scope as a previous declaration 'Old'. Figure out how to resolve this
358/// situation, merging decls or emitting diagnostics as appropriate.
359///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000360TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahaniande939672009-01-16 19:58:32 +0000361 bool objc_types = false;
Steve Naroff453a8782008-09-09 14:32:20 +0000362 // Allow multiple definitions for ObjC built-in typedefs.
363 // FIXME: Verify the underlying types are equivalent!
364 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000365 const IdentifierInfo *TypeID = New->getIdentifier();
366 switch (TypeID->getLength()) {
367 default: break;
368 case 2:
369 if (!TypeID->isStr("id"))
370 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000371 Context.setObjCIdType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000372 objc_types = true;
373 break;
Chris Lattner6d16b052008-11-20 05:41:43 +0000374 case 5:
375 if (!TypeID->isStr("Class"))
376 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000377 Context.setObjCClassType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000378 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000379 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000380 case 3:
381 if (!TypeID->isStr("SEL"))
382 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000383 Context.setObjCSelType(New);
Fariborz Jahaniande939672009-01-16 19:58:32 +0000384 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000385 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000386 case 8:
387 if (!TypeID->isStr("Protocol"))
388 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000389 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahaniande939672009-01-16 19:58:32 +0000390 objc_types = true;
Steve Naroff453a8782008-09-09 14:32:20 +0000391 return New;
392 }
393 // Fall through - the typedef name was not a builtin type.
394 }
Chris Lattner4b009652007-07-25 00:24:17 +0000395 // Verify the old decl was also a typedef.
396 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
397 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000398 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000399 << New->getDeclName();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000400 if (!objc_types)
401 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000402 return New;
403 }
404
Chris Lattnerbef8d622008-07-25 18:44:27 +0000405 // If the typedef types are not identical, reject them in all languages and
406 // with any extensions enabled.
407 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
408 Context.getCanonicalType(Old->getUnderlyingType()) !=
409 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000410 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000411 << New->getUnderlyingType() << Old->getUnderlyingType();
Fariborz Jahaniande939672009-01-16 19:58:32 +0000412 if (!objc_types)
413 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregord1675382009-01-09 19:42:16 +0000414 return New;
Chris Lattnerbef8d622008-07-25 18:44:27 +0000415 }
Fariborz Jahaniande939672009-01-16 19:58:32 +0000416 if (objc_types) return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000417 if (getLangOptions().Microsoft) return New;
418
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000419 // C++ [dcl.typedef]p2:
420 // In a given non-class scope, a typedef specifier can be used to
421 // redefine the name of any type declared in that scope to refer
422 // to the type to which it already refers.
423 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
424 return New;
425
426 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000427 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
428 // *either* declaration is in a system header. The code below implements
429 // this adhoc compatibility rule. FIXME: The following code will not
430 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000431 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
432 SourceManager &SrcMgr = Context.getSourceManager();
433 if (SrcMgr.isInSystemHeader(Old->getLocation()))
434 return New;
435 if (SrcMgr.isInSystemHeader(New->getLocation()))
436 return New;
437 }
Eli Friedman324d5032008-06-11 06:20:39 +0000438
Chris Lattnerb1753422008-11-23 21:45:46 +0000439 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000440 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000441 return New;
442}
443
Chris Lattner6953a072008-06-26 18:38:35 +0000444/// DeclhasAttr - returns true if decl Declaration already has the target
445/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000446static bool DeclHasAttr(const Decl *decl, const Attr *target) {
447 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
448 if (attr->getKind() == target->getKind())
449 return true;
450
451 return false;
452}
453
454/// MergeAttributes - append attributes from the Old decl to the New one.
455static void MergeAttributes(Decl *New, Decl *Old) {
456 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
457
Chris Lattner402b3372008-03-03 03:28:21 +0000458 while (attr) {
459 tmp = attr;
460 attr = attr->getNext();
461
462 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000463 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000464 New->addAttr(tmp);
465 } else {
466 tmp->setNext(0);
467 delete(tmp);
468 }
469 }
Nuno Lopes77654342008-06-01 22:53:53 +0000470
471 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000472}
473
Chris Lattner3e254fb2008-04-08 04:40:51 +0000474/// MergeFunctionDecl - We just parsed a function 'New' from
475/// declarator D which has the same name and scope as a previous
476/// declaration 'Old'. Figure out how to resolve this situation,
477/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478/// Redeclaration will be set true if this New is a redeclaration OldD.
479///
480/// In C++, New and Old must be declarations that are not
481/// overloaded. Use IsOverload to determine whether New and Old are
482/// overloaded, and to select the Old declaration that New should be
483/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000484FunctionDecl *
485Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486 assert(!isa<OverloadedFunctionDecl>(OldD) &&
487 "Cannot merge with an overloaded function declaration");
488
Douglas Gregor42214c52008-04-21 02:02:58 +0000489 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000490 // Verify the old decl was also a function.
491 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
492 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000493 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000494 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000495 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000496 return New;
497 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000498
499 // Determine whether the previous declaration was a definition,
500 // implicit declaration, or a declaration.
501 diag::kind PrevDiag;
502 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000503 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000504 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000505 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000506 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000507 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000508
Chris Lattner42a21742008-04-06 23:10:54 +0000509 QualType OldQType = Context.getCanonicalType(Old->getType());
510 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000511
Douglas Gregord2baafd2008-10-21 16:13:35 +0000512 if (getLangOptions().CPlusPlus) {
513 // (C++98 13.1p2):
514 // Certain function declarations cannot be overloaded:
515 // -- Function declarations that differ only in the return type
516 // cannot be overloaded.
517 QualType OldReturnType
518 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
519 QualType NewReturnType
520 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
521 if (OldReturnType != NewReturnType) {
522 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
523 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000524 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525 return New;
526 }
527
528 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
529 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
530 if (OldMethod && NewMethod) {
531 // -- Member function declarations with the same name and the
532 // same parameter types cannot be overloaded if any of them
533 // is a static member function declaration.
534 if (OldMethod->isStatic() || NewMethod->isStatic()) {
535 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
536 Diag(Old->getLocation(), PrevDiag);
537 return New;
538 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000539
540 // C++ [class.mem]p1:
541 // [...] A member shall not be declared twice in the
542 // member-specification, except that a nested class or member
543 // class template can be declared and then later defined.
544 if (OldMethod->getLexicalDeclContext() ==
545 NewMethod->getLexicalDeclContext()) {
546 unsigned NewDiag;
547 if (isa<CXXConstructorDecl>(OldMethod))
548 NewDiag = diag::err_constructor_redeclared;
549 else if (isa<CXXDestructorDecl>(NewMethod))
550 NewDiag = diag::err_destructor_redeclared;
551 else if (isa<CXXConversionDecl>(NewMethod))
552 NewDiag = diag::err_conv_function_redeclared;
553 else
554 NewDiag = diag::err_member_redeclared;
555
556 Diag(New->getLocation(), NewDiag);
557 Diag(Old->getLocation(), PrevDiag);
558 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 }
560
561 // (C++98 8.3.5p3):
562 // All declarations for a function shall agree exactly in both the
563 // return type and the parameter-type-list.
564 if (OldQType == NewQType) {
565 // We have a redeclaration.
566 MergeAttributes(New, Old);
567 Redeclaration = true;
568 return MergeCXXFunctionDecl(New, Old);
569 }
570
571 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000572 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000573
574 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000575 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000576 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000577 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000578 MergeAttributes(New, Old);
579 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000580 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000581 }
Chris Lattner1470b072007-11-06 06:07:26 +0000582
Steve Naroff6c9e7922008-01-16 15:01:34 +0000583 // A function that has already been declared has been redeclared or defined
584 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000585
Chris Lattner4b009652007-07-25 00:24:17 +0000586 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
587 // TODO: This is totally simplistic. It should handle merging functions
588 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000589 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000590 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000591 return New;
592}
593
Steve Naroffb5e78152008-08-08 17:50:35 +0000594/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000595static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000596 if (VD->isFileVarDecl())
597 return (!VD->getInit() &&
598 (VD->getStorageClass() == VarDecl::None ||
599 VD->getStorageClass() == VarDecl::Static));
600 return false;
601}
602
603/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
604/// when dealing with C "tentative" external object definitions (C99 6.9.2).
605void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
606 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000607 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000608
Douglas Gregor3a423132009-01-07 16:34:42 +0000609 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000610 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000611 for (IdentifierResolver::iterator
612 I = IdResolver.begin(VD->getIdentifier(),
613 VD->getDeclContext(), false/*LookInParentCtx*/),
614 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000615 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000616 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
617
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000618 // Handle the following case:
619 // int a[10];
620 // int a[]; - the code below makes sure we set the correct type.
621 // int a[11]; - this is an error, size isn't 10.
622 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
623 OldDecl->getType()->isConstantArrayType())
624 VD->setType(OldDecl->getType());
625
Steve Naroffb5e78152008-08-08 17:50:35 +0000626 // Check for "tentative" definitions. We can't accomplish this in
627 // MergeVarDecl since the initializer hasn't been attached.
628 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
629 continue;
630
631 // Handle __private_extern__ just like extern.
632 if (OldDecl->getStorageClass() != VarDecl::Extern &&
633 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
634 VD->getStorageClass() != VarDecl::Extern &&
635 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000636 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000637 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000638 }
639 }
640 }
641}
642
Chris Lattner4b009652007-07-25 00:24:17 +0000643/// MergeVarDecl - We just parsed a variable 'New' which has the same name
644/// and scope as a previous declaration 'Old'. Figure out how to resolve this
645/// situation, merging decls or emitting diagnostics as appropriate.
646///
Steve Naroffb5e78152008-08-08 17:50:35 +0000647/// Tentative definition rules (C99 6.9.2p2) are checked by
648/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
649/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000650///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000651VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000652 // Verify the old decl was also a variable.
653 VarDecl *Old = dyn_cast<VarDecl>(OldD);
654 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000655 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000656 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000657 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000658 return New;
659 }
Chris Lattner402b3372008-03-03 03:28:21 +0000660
661 MergeAttributes(New, Old);
662
Chris Lattner4b009652007-07-25 00:24:17 +0000663 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000664 QualType OldCType = Context.getCanonicalType(Old->getType());
665 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000666 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregord1675382009-01-09 19:42:16 +0000667 Diag(New->getLocation(), diag::err_redefinition_different_type)
668 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000669 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000670 return New;
671 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000672 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
673 if (New->getStorageClass() == VarDecl::Static &&
674 (Old->getStorageClass() == VarDecl::None ||
675 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000676 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000678 return New;
679 }
680 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
681 if (New->getStorageClass() != VarDecl::Static &&
682 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000683 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000684 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000685 return New;
686 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000687 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
688 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000689 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000690 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000691 }
692 return New;
693}
694
Chris Lattner3e254fb2008-04-08 04:40:51 +0000695/// CheckParmsForFunctionDef - Check that the parameters of the given
696/// function are appropriate for the definition of a function. This
697/// takes care of any checks that cannot be performed on the
698/// declaration itself, e.g., that the types of each of the function
699/// parameters are complete.
700bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
701 bool HasInvalidParm = false;
702 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
703 ParmVarDecl *Param = FD->getParamDecl(p);
704
705 // C99 6.7.5.3p4: the parameters in a parameter type list in a
706 // function declarator that is part of a function definition of
707 // that function shall not have incomplete type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000708 if (!Param->isInvalidDecl() &&
709 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
710 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000711 Param->setInvalidDecl();
712 HasInvalidParm = true;
713 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000714
715 // C99 6.9.1p5: If the declarator includes a parameter type list, the
716 // declaration of each parameter shall include an identifier.
717 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
718 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000719 }
720
721 return HasInvalidParm;
722}
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
725/// no declarator (e.g. "struct foo;") is parsed.
726Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000727 TagDecl *Tag
728 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
729 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
730 if (!Record->getDeclName() && Record->isDefinition() &&
731 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
732 return BuildAnonymousStructOrUnion(S, DS, Record);
733
734 // Microsoft allows unnamed struct/union fields. Don't complain
735 // about them.
736 // FIXME: Should we support Microsoft's extensions in this area?
737 if (Record->getDeclName() && getLangOptions().Microsoft)
738 return Tag;
739 }
740
Douglas Gregor80c720e2009-01-13 23:10:51 +0000741 // Permit typedefs without declarators as a Microsoft extension.
Sebastian Redlb7605e82008-12-28 15:28:59 +0000742 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor72de8492009-01-17 02:55:50 +0000743 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
744 Tag && isa<EnumDecl>(Tag)) {
745 Diag(DS.getSourceRange().getBegin(), diag::warn_no_declarators)
Douglas Gregor80c720e2009-01-13 23:10:51 +0000746 << DS.getSourceRange();
747 return Tag;
748 }
749
Sebastian Redlb7605e82008-12-28 15:28:59 +0000750 // FIXME: This diagnostic is emitted even when various previous
751 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
752 // DeclSpec has no means of communicating this information, and the
753 // responsible parser functions are quite far apart.
754 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
755 << DS.getSourceRange();
756 return 0;
757 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000758
Douglas Gregor723d3332009-01-07 00:43:41 +0000759 return Tag;
760}
761
762/// InjectAnonymousStructOrUnionMembers - Inject the members of the
763/// anonymous struct or union AnonRecord into the owning context Owner
764/// and scope S. This routine will be invoked just after we realize
765/// that an unnamed union or struct is actually an anonymous union or
766/// struct, e.g.,
767///
768/// @code
769/// union {
770/// int i;
771/// float f;
772/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
773/// // f into the surrounding scope.x
774/// @endcode
775///
776/// This routine is recursive, injecting the names of nested anonymous
777/// structs/unions into the owning context and scope as well.
778bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
779 RecordDecl *AnonRecord) {
780 bool Invalid = false;
781 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
782 FEnd = AnonRecord->field_end();
783 F != FEnd; ++F) {
784 if ((*F)->getDeclName()) {
785 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
786 S, Owner, false, false, false);
787 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
788 // C++ [class.union]p2:
789 // The names of the members of an anonymous union shall be
790 // distinct from the names of any other entity in the
791 // scope in which the anonymous union is declared.
792 unsigned diagKind
793 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
794 : diag::err_anonymous_struct_member_redecl;
795 Diag((*F)->getLocation(), diagKind)
796 << (*F)->getDeclName();
797 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
798 Invalid = true;
799 } else {
800 // C++ [class.union]p2:
801 // For the purpose of name lookup, after the anonymous union
802 // definition, the members of the anonymous union are
803 // considered to have been defined in the scope in which the
804 // anonymous union is declared.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000805 Owner->insert(*F);
Douglas Gregor723d3332009-01-07 00:43:41 +0000806 S->AddDecl(*F);
807 IdResolver.AddDecl(*F);
808 }
809 } else if (const RecordType *InnerRecordType
810 = (*F)->getType()->getAsRecordType()) {
811 RecordDecl *InnerRecord = InnerRecordType->getDecl();
812 if (InnerRecord->isAnonymousStructOrUnion())
813 Invalid = Invalid ||
814 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
815 }
816 }
817
818 return Invalid;
819}
820
821/// ActOnAnonymousStructOrUnion - Handle the declaration of an
822/// anonymous structure or union. Anonymous unions are a C++ feature
823/// (C++ [class.union]) and a GNU C extension; anonymous structures
824/// are a GNU C and GNU C++ extension.
825Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
826 RecordDecl *Record) {
827 DeclContext *Owner = Record->getDeclContext();
828
829 // Diagnose whether this anonymous struct/union is an extension.
830 if (Record->isUnion() && !getLangOptions().CPlusPlus)
831 Diag(Record->getLocation(), diag::ext_anonymous_union);
832 else if (!Record->isUnion())
833 Diag(Record->getLocation(), diag::ext_anonymous_struct);
834
835 // C and C++ require different kinds of checks for anonymous
836 // structs/unions.
837 bool Invalid = false;
838 if (getLangOptions().CPlusPlus) {
839 const char* PrevSpec = 0;
840 // C++ [class.union]p3:
841 // Anonymous unions declared in a named namespace or in the
842 // global namespace shall be declared static.
843 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
844 (isa<TranslationUnitDecl>(Owner) ||
845 (isa<NamespaceDecl>(Owner) &&
846 cast<NamespaceDecl>(Owner)->getDeclName()))) {
847 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
848 Invalid = true;
849
850 // Recover by adding 'static'.
851 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
852 }
853 // C++ [class.union]p3:
854 // A storage class is not allowed in a declaration of an
855 // anonymous union in a class scope.
856 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
857 isa<RecordDecl>(Owner)) {
858 Diag(DS.getStorageClassSpecLoc(),
859 diag::err_anonymous_union_with_storage_spec);
860 Invalid = true;
861
862 // Recover by removing the storage specifier.
863 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
864 PrevSpec);
865 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000866
867 // C++ [class.union]p2:
868 // The member-specification of an anonymous union shall only
869 // define non-static data members. [Note: nested types and
870 // functions cannot be declared within an anonymous union. ]
871 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
872 MemEnd = Record->decls_end();
873 Mem != MemEnd; ++Mem) {
874 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
875 // C++ [class.union]p3:
876 // An anonymous union shall not have private or protected
877 // members (clause 11).
878 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
879 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
880 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
881 Invalid = true;
882 }
883 } else if ((*Mem)->isImplicit()) {
884 // Any implicit members are fine.
885 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
886 if (!MemRecord->isAnonymousStructOrUnion() &&
887 MemRecord->getDeclName()) {
888 // This is a nested type declaration.
889 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
890 << (int)Record->isUnion();
891 Invalid = true;
892 }
893 } else {
894 // We have something that isn't a non-static data
895 // member. Complain about it.
896 unsigned DK = diag::err_anonymous_record_bad_member;
897 if (isa<TypeDecl>(*Mem))
898 DK = diag::err_anonymous_record_with_type;
899 else if (isa<FunctionDecl>(*Mem))
900 DK = diag::err_anonymous_record_with_function;
901 else if (isa<VarDecl>(*Mem))
902 DK = diag::err_anonymous_record_with_static;
903 Diag((*Mem)->getLocation(), DK)
904 << (int)Record->isUnion();
905 Invalid = true;
906 }
907 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000908 } else {
909 // FIXME: Check GNU C semantics
Douglas Gregorb748fc52009-01-12 22:49:06 +0000910 if (Record->isUnion() && !Owner->isRecord()) {
911 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
912 << (int)getLangOptions().CPlusPlus;
913 Invalid = true;
914 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000915 }
916
917 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorb748fc52009-01-12 22:49:06 +0000918 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
919 << (int)getLangOptions().CPlusPlus;
Douglas Gregor723d3332009-01-07 00:43:41 +0000920 Invalid = true;
921 }
922
923 // Create a declaration for this anonymous struct/union.
924 ScopedDecl *Anon = 0;
925 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
926 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
927 /*IdentifierInfo=*/0,
928 Context.getTypeDeclType(Record),
929 /*BitWidth=*/0, /*Mutable=*/false,
930 /*PrevDecl=*/0);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000931 Anon->setAccess(AS_public);
932 if (getLangOptions().CPlusPlus)
933 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +0000934 } else {
935 VarDecl::StorageClass SC;
936 switch (DS.getStorageClassSpec()) {
937 default: assert(0 && "Unknown storage class!");
938 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
939 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
940 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
941 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
942 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
943 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
944 case DeclSpec::SCS_mutable:
945 // mutable can only appear on non-static class members, so it's always
946 // an error here
947 Diag(Record->getLocation(), diag::err_mutable_nonmember);
948 Invalid = true;
949 SC = VarDecl::None;
950 break;
951 }
952
953 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
954 /*IdentifierInfo=*/0,
955 Context.getTypeDeclType(Record),
956 SC, /*FIXME:LastDeclarator=*/0,
957 DS.getSourceRange().getBegin());
958 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000959 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +0000960
961 // Add the anonymous struct/union object to the current
962 // context. We'll be referencing this object when we refer to one of
963 // its members.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000964 Owner->addDecl(Anon);
Douglas Gregor723d3332009-01-07 00:43:41 +0000965
966 // Inject the members of the anonymous struct/union into the owning
967 // context and into the identifier resolver chain for name lookup
968 // purposes.
Douglas Gregorb748fc52009-01-12 22:49:06 +0000969 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
970 Invalid = true;
Douglas Gregor723d3332009-01-07 00:43:41 +0000971
972 // Mark this as an anonymous struct/union type. Note that we do not
973 // do this until after we have already checked and injected the
974 // members of this anonymous struct/union type, because otherwise
975 // the members could be injected twice: once by DeclContext when it
976 // builds its lookup table, and once by
977 // InjectAnonymousStructOrUnionMembers.
978 Record->setAnonymousStructOrUnion(true);
979
980 if (Invalid)
981 Anon->setInvalidDecl();
982
983 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +0000984}
985
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000986bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
987 bool DirectInit) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000988 // Get the type before calling CheckSingleAssignmentConstraints(), since
989 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000990 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000991
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000992 if (getLangOptions().CPlusPlus) {
993 // FIXME: I dislike this error message. A lot.
994 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
995 return Diag(Init->getSourceRange().getBegin(),
996 diag::err_typecheck_convert_incompatible)
997 << DeclType << Init->getType() << "initializing"
998 << Init->getSourceRange();
999
1000 return false;
1001 }
Douglas Gregor6fd35572008-12-19 17:40:08 +00001002
Chris Lattner005ed752008-01-04 18:04:52 +00001003 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1004 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1005 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001006}
1007
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001008bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001009 const ArrayType *AT = Context.getAsArrayType(DeclT);
1010
1011 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001012 // C99 6.7.8p14. We have an array of character type with unknown size
1013 // being initialized to a string literal.
1014 llvm::APSInt ConstVal(32);
1015 ConstVal = strLiteral->getByteLength() + 1;
1016 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001017 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001018 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001019 } else {
1020 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001021 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001022 // FIXME: Avoid truncation for 64-bit length strings.
1023 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001024 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001025 diag::warn_initializer_string_for_char_array_too_long)
1026 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001027 }
1028 // Set type from "char *" to "constant array of char".
1029 strLiteral->setType(DeclT);
1030 // For now, we always return false (meaning success).
1031 return false;
1032}
1033
1034StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001035 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001036 if (AT && AT->getElementType()->isCharType()) {
1037 return dyn_cast<StringLiteral>(Init);
1038 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001039 return 0;
1040}
1041
Douglas Gregor6428e762008-11-05 15:29:30 +00001042bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1043 SourceLocation InitLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001044 DeclarationName InitEntity,
1045 bool DirectInit) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001046 if (DeclType->isDependentType() || Init->isTypeDependent())
1047 return false;
1048
Douglas Gregor81c29152008-10-29 00:13:59 +00001049 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001050 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001051 // (8.3.2), shall be initialized by an object, or function, of
1052 // type T or by an object that can be converted into a T.
1053 if (DeclType->isReferenceType())
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001054 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor81c29152008-10-29 00:13:59 +00001055
Steve Naroff8e9337f2008-01-21 23:53:58 +00001056 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1057 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001058 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001059 return Diag(InitLoc, diag::err_variable_object_no_init)
1060 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001061
Steve Naroffcb69fb72007-12-10 22:44:33 +00001062 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1063 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001064 // FIXME: Handle wide strings
1065 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1066 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001067
Douglas Gregor6428e762008-11-05 15:29:30 +00001068 // C++ [dcl.init]p14:
1069 // -- If the destination type is a (possibly cv-qualified) class
1070 // type:
1071 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1072 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1073 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1074
1075 // -- If the initialization is direct-initialization, or if it is
1076 // copy-initialization where the cv-unqualified version of the
1077 // source type is the same class as, or a derived class of, the
1078 // class of the destination, constructors are considered.
1079 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1080 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1081 CXXConstructorDecl *Constructor
1082 = PerformInitializationByConstructor(DeclType, &Init, 1,
1083 InitLoc, Init->getSourceRange(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001084 InitEntity,
1085 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6428e762008-11-05 15:29:30 +00001086 return Constructor == 0;
1087 }
1088
1089 // -- Otherwise (i.e., for the remaining copy-initialization
1090 // cases), user-defined conversion sequences that can
1091 // convert from the source type to the destination type or
1092 // (when a conversion function is used) to a derived class
1093 // thereof are enumerated as described in 13.3.1.4, and the
1094 // best one is chosen through overload resolution
1095 // (13.3). If the conversion cannot be done or is
1096 // ambiguous, the initialization is ill-formed. The
1097 // function selected is called with the initializer
1098 // expression as its argument; if the function is a
1099 // constructor, the call initializes a temporary of the
1100 // destination type.
1101 // FIXME: We're pretending to do copy elision here; return to
1102 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001103 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001104 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001105
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001106 if (InitEntity)
1107 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1108 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1109 << Init->getType() << Init->getSourceRange();
1110 else
1111 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1112 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1113 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001114 }
1115
Steve Naroffb2f72412008-09-29 20:07:05 +00001116 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001117 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001118 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1119 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001120
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001121 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor15e04622008-11-05 16:20:31 +00001122 } else if (getLangOptions().CPlusPlus) {
1123 // C++ [dcl.init]p14:
1124 // [...] If the class is an aggregate (8.5.1), and the initializer
1125 // is a brace-enclosed list, see 8.5.1.
1126 //
1127 // Note: 8.5.1 is handled below; here, we diagnose the case where
1128 // we have an initializer list and a destination type that is not
1129 // an aggregate.
1130 // FIXME: In C++0x, this is yet another form of initialization.
1131 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1132 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1133 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001134 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001135 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001136 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001137 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001138
Steve Naroffc4d4a482008-05-01 22:18:59 +00001139 InitListChecker CheckInitList(this, InitList, DeclType);
1140 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +00001141}
1142
Douglas Gregor6704b312008-11-17 22:58:34 +00001143/// GetNameForDeclarator - Determine the full declaration name for the
1144/// given Declarator.
1145DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1146 switch (D.getKind()) {
1147 case Declarator::DK_Abstract:
1148 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1149 return DeclarationName();
1150
1151 case Declarator::DK_Normal:
1152 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1153 return DeclarationName(D.getIdentifier());
1154
1155 case Declarator::DK_Constructor: {
1156 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1157 Ty = Context.getCanonicalType(Ty);
1158 return Context.DeclarationNames.getCXXConstructorName(Ty);
1159 }
1160
1161 case Declarator::DK_Destructor: {
1162 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1163 Ty = Context.getCanonicalType(Ty);
1164 return Context.DeclarationNames.getCXXDestructorName(Ty);
1165 }
1166
1167 case Declarator::DK_Conversion: {
1168 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1169 Ty = Context.getCanonicalType(Ty);
1170 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1171 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001172
1173 case Declarator::DK_Operator:
1174 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1175 return Context.DeclarationNames.getCXXOperatorName(
1176 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001177 }
1178
1179 assert(false && "Unknown name kind");
1180 return DeclarationName();
1181}
1182
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001183/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1184/// functions Declaration and Definition are "nearly" matching. This
1185/// heuristic is used to improve diagnostics in the case where an
1186/// out-of-line member function definition doesn't match any
1187/// declaration within the class.
1188static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1189 FunctionDecl *Declaration,
1190 FunctionDecl *Definition) {
1191 if (Declaration->param_size() != Definition->param_size())
1192 return false;
1193 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1194 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1195 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1196
1197 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1198 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1199 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1200 return false;
1201 }
1202
1203 return true;
1204}
1205
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001206Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001207Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1208 bool IsFunctionDefinition) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001209 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001210 DeclarationName Name = GetNameForDeclarator(D);
1211
Chris Lattner4b009652007-07-25 00:24:17 +00001212 // All of these full declarators require an identifier. If it doesn't have
1213 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001214 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001215 if (!D.getInvalidType()) // Reject this if we think it is valid.
1216 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001217 diag::err_declarator_need_ident)
1218 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001219 return 0;
1220 }
1221
Chris Lattnera7549902007-08-26 06:24:45 +00001222 // The scope passed in may not be a decl scope. Zip up the scope tree until
1223 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001224 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1225 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001226 S = S->getParent();
1227
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001228 DeclContext *DC;
1229 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001230 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001231 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001232
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001233 // See if this is a redefinition of a variable in the same scope.
1234 if (!D.getCXXScopeSpec().isSet()) {
1235 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +00001236 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001237 } else { // Something like "int foo::x;"
1238 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +00001239 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001240
1241 // C++ 7.3.1.2p2:
1242 // Members (including explicit specializations of templates) of a named
1243 // namespace can also be defined outside that namespace by explicit
1244 // qualification of the name being defined, provided that the entity being
1245 // defined was already declared in the namespace and the definition appears
1246 // after the point of declaration in a namespace that encloses the
1247 // declarations namespace.
1248 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001249 // Note that we only check the context at this point. We don't yet
1250 // have enough information to make sure that PrevDecl is actually
1251 // the declaration we want to match. For example, given:
1252 //
Douglas Gregor98341042008-12-12 08:25:50 +00001253 // class X {
1254 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001255 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001256 // };
1257 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001258 // void X::f(int) { } // ill-formed
1259 //
1260 // In this case, PrevDecl will point to the overload set
1261 // containing the two f's declared in X, but neither of them
1262 // matches.
1263 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001264 // The qualifying scope doesn't enclose the original declaration.
1265 // Emit diagnostic based on current scope.
1266 SourceLocation L = D.getIdentifierLoc();
1267 SourceRange R = D.getCXXScopeSpec().getRange();
1268 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001269 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001270 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001271 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001272 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001273 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001274 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001275 }
1276 }
1277
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001278 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001279 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001280 InvalidDecl = InvalidDecl
1281 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001282 // Just pretend that we didn't see the previous declaration.
1283 PrevDecl = 0;
1284 }
1285
Douglas Gregor1d661552008-04-13 21:07:44 +00001286 // In C++, the previous declaration we find might be a tag type
1287 // (class or enum). In this case, the new declaration will hide the
1288 // tag type.
1289 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1290 PrevDecl = 0;
1291
Chris Lattner82bb4792007-11-14 06:34:38 +00001292 QualType R = GetTypeForDeclarator(D, S);
1293 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1294
Chris Lattner4b009652007-07-25 00:24:17 +00001295 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001296 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1297 InvalidDecl);
Chris Lattner82bb4792007-11-14 06:34:38 +00001298 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001299 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1300 IsFunctionDefinition, InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001301 } else {
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001302 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1303 InvalidDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001304 }
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001305
1306 if (New == 0)
1307 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +00001308
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001309 // Set the lexical context. If the declarator has a C++ scope specifier, the
1310 // lexical context will be different from the semantic context.
1311 New->setLexicalDeclContext(CurContext);
1312
Chris Lattner4b009652007-07-25 00:24:17 +00001313 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001314 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001315 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001316 // If any semantic error occurred, mark the decl as invalid.
1317 if (D.getInvalidType() || InvalidDecl)
1318 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001319
1320 return New;
1321}
1322
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001323ScopedDecl*
Zhongxing Xu2b3c3dd2009-01-16 03:34:13 +00001324Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1325 QualType R, ScopedDecl* LastDeclarator,
1326 Decl* PrevDecl, bool& InvalidDecl) {
1327 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1328 if (D.getCXXScopeSpec().isSet()) {
1329 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1330 << D.getCXXScopeSpec().getRange();
1331 InvalidDecl = true;
1332 // Pretend we didn't see the scope specifier.
1333 DC = 0;
1334 }
1335
1336 // Check that there are no default arguments (C++ only).
1337 if (getLangOptions().CPlusPlus)
1338 CheckExtraCXXDefaultArguments(D);
1339
1340 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1341 if (!NewTD) return 0;
1342
1343 // Handle attributes prior to checking for duplicates in MergeVarDecl
1344 ProcessDeclAttributes(NewTD, D);
1345 // Merge the decl with the existing one if appropriate. If the decl is
1346 // in an outer scope, it isn't the same thing.
1347 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1348 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1349 if (NewTD == 0) return 0;
1350 }
1351
1352 if (S->getFnParent() == 0) {
1353 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1354 // then it shall have block scope.
1355 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1356 if (NewTD->getUnderlyingType()->isVariableArrayType())
1357 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1358 else
1359 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1360
1361 InvalidDecl = true;
1362 }
1363 }
1364 return NewTD;
1365}
1366
1367ScopedDecl*
Zhongxing Xu511d45b2009-01-16 02:36:34 +00001368Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1369 QualType R, ScopedDecl* LastDeclarator,
1370 Decl* PrevDecl, bool& InvalidDecl) {
1371 DeclarationName Name = GetNameForDeclarator(D);
1372
1373 // Check that there are no default arguments (C++ only).
1374 if (getLangOptions().CPlusPlus)
1375 CheckExtraCXXDefaultArguments(D);
1376
1377 if (R.getTypePtr()->isObjCInterfaceType()) {
1378 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1379 << D.getIdentifier();
1380 InvalidDecl = true;
1381 }
1382
1383 VarDecl *NewVD;
1384 VarDecl::StorageClass SC;
1385 switch (D.getDeclSpec().getStorageClassSpec()) {
1386 default: assert(0 && "Unknown storage class!");
1387 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1388 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1389 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1390 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1391 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1392 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1393 case DeclSpec::SCS_mutable:
1394 // mutable can only appear on non-static class members, so it's always
1395 // an error here
1396 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1397 InvalidDecl = true;
1398 SC = VarDecl::None;
1399 break;
1400 }
1401
1402 IdentifierInfo *II = Name.getAsIdentifierInfo();
1403 if (!II) {
1404 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1405 << Name.getAsString();
1406 return 0;
1407 }
1408
1409 if (DC->isRecord()) {
1410 // This is a static data member for a C++ class.
1411 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1412 D.getIdentifierLoc(), II,
1413 R, LastDeclarator);
1414 } else {
1415 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1416 if (S->getFnParent() == 0) {
1417 // C99 6.9p2: The storage-class specifiers auto and register shall not
1418 // appear in the declaration specifiers in an external declaration.
1419 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1420 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1421 InvalidDecl = true;
1422 }
1423 }
1424 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1425 II, R, SC, LastDeclarator,
1426 // FIXME: Move to DeclGroup...
1427 D.getDeclSpec().getSourceRange().getBegin());
1428 NewVD->setThreadSpecified(ThreadSpecified);
1429 }
1430 // Handle attributes prior to checking for duplicates in MergeVarDecl
1431 ProcessDeclAttributes(NewVD, D);
1432
1433 // Handle GNU asm-label extension (encoded as an attribute).
1434 if (Expr *E = (Expr*) D.getAsmLabel()) {
1435 // The parser guarantees this is a string.
1436 StringLiteral *SE = cast<StringLiteral>(E);
1437 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1438 SE->getByteLength())));
1439 }
1440
1441 // Emit an error if an address space was applied to decl with local storage.
1442 // This includes arrays of objects with address space qualifiers, but not
1443 // automatic variables that point to other address spaces.
1444 // ISO/IEC TR 18037 S5.1.2
1445 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1446 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1447 InvalidDecl = true;
1448 }
1449 // Merge the decl with the existing one if appropriate. If the decl is
1450 // in an outer scope, it isn't the same thing.
1451 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1452 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1453 // The user tried to define a non-static data member
1454 // out-of-line (C++ [dcl.meaning]p1).
1455 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1456 << D.getCXXScopeSpec().getRange();
1457 NewVD->Destroy(Context);
1458 return 0;
1459 }
1460
1461 NewVD = MergeVarDecl(NewVD, PrevDecl);
1462 if (NewVD == 0) return 0;
1463
1464 if (D.getCXXScopeSpec().isSet()) {
1465 // No previous declaration in the qualifying scope.
1466 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1467 << Name << D.getCXXScopeSpec().getRange();
1468 InvalidDecl = true;
1469 }
1470 }
1471 return NewVD;
1472}
1473
Zhongxing Xu7502dec2009-01-16 01:13:29 +00001474ScopedDecl*
1475Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1476 QualType R, ScopedDecl *LastDeclarator,
1477 Decl* PrevDecl, bool IsFunctionDefinition,
1478 bool& InvalidDecl) {
1479 assert(R.getTypePtr()->isFunctionType());
1480
1481 DeclarationName Name = GetNameForDeclarator(D);
1482 FunctionDecl::StorageClass SC = FunctionDecl::None;
1483 switch (D.getDeclSpec().getStorageClassSpec()) {
1484 default: assert(0 && "Unknown storage class!");
1485 case DeclSpec::SCS_auto:
1486 case DeclSpec::SCS_register:
1487 case DeclSpec::SCS_mutable:
1488 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1489 InvalidDecl = true;
1490 break;
1491 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1492 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1493 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1494 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1495 }
1496
1497 bool isInline = D.getDeclSpec().isInlineSpecified();
1498 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1499 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1500
1501 FunctionDecl *NewFD;
1502 if (D.getKind() == Declarator::DK_Constructor) {
1503 // This is a C++ constructor declaration.
1504 assert(DC->isRecord() &&
1505 "Constructors can only be declared in a member context");
1506
1507 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1508
1509 // Create the new declaration
1510 NewFD = CXXConstructorDecl::Create(Context,
1511 cast<CXXRecordDecl>(DC),
1512 D.getIdentifierLoc(), Name, R,
1513 isExplicit, isInline,
1514 /*isImplicitlyDeclared=*/false);
1515
1516 if (InvalidDecl)
1517 NewFD->setInvalidDecl();
1518 } else if (D.getKind() == Declarator::DK_Destructor) {
1519 // This is a C++ destructor declaration.
1520 if (DC->isRecord()) {
1521 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1522
1523 NewFD = CXXDestructorDecl::Create(Context,
1524 cast<CXXRecordDecl>(DC),
1525 D.getIdentifierLoc(), Name, R,
1526 isInline,
1527 /*isImplicitlyDeclared=*/false);
1528
1529 if (InvalidDecl)
1530 NewFD->setInvalidDecl();
1531 } else {
1532 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1533
1534 // Create a FunctionDecl to satisfy the function definition parsing
1535 // code path.
1536 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
1537 Name, R, SC, isInline, LastDeclarator,
1538 // FIXME: Move to DeclGroup...
1539 D.getDeclSpec().getSourceRange().getBegin());
1540 InvalidDecl = true;
1541 NewFD->setInvalidDecl();
1542 }
1543 } else if (D.getKind() == Declarator::DK_Conversion) {
1544 if (!DC->isRecord()) {
1545 Diag(D.getIdentifierLoc(),
1546 diag::err_conv_function_not_member);
1547 return 0;
1548 } else {
1549 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1550
1551 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1552 D.getIdentifierLoc(), Name, R,
1553 isInline, isExplicit);
1554
1555 if (InvalidDecl)
1556 NewFD->setInvalidDecl();
1557 }
1558 } else if (DC->isRecord()) {
1559 // This is a C++ method declaration.
1560 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1561 D.getIdentifierLoc(), Name, R,
1562 (SC == FunctionDecl::Static), isInline,
1563 LastDeclarator);
1564 } else {
1565 NewFD = FunctionDecl::Create(Context, DC,
1566 D.getIdentifierLoc(),
1567 Name, R, SC, isInline, LastDeclarator,
1568 // FIXME: Move to DeclGroup...
1569 D.getDeclSpec().getSourceRange().getBegin());
1570 }
1571
1572 // Set the lexical context. If the declarator has a C++
1573 // scope specifier, the lexical context will be different
1574 // from the semantic context.
1575 NewFD->setLexicalDeclContext(CurContext);
1576
1577 // Handle GNU asm-label extension (encoded as an attribute).
1578 if (Expr *E = (Expr*) D.getAsmLabel()) {
1579 // The parser guarantees this is a string.
1580 StringLiteral *SE = cast<StringLiteral>(E);
1581 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1582 SE->getByteLength())));
1583 }
1584
1585 // Copy the parameter declarations from the declarator D to
1586 // the function declaration NewFD, if they are available.
1587 if (D.getNumTypeObjects() > 0) {
1588 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1589
1590 // Create Decl objects for each parameter, adding them to the
1591 // FunctionDecl.
1592 llvm::SmallVector<ParmVarDecl*, 16> Params;
1593
1594 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1595 // function that takes no arguments, not a function that takes a
1596 // single void argument.
1597 // We let through "const void" here because Sema::GetTypeForDeclarator
1598 // already checks for that case.
1599 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1600 FTI.ArgInfo[0].Param &&
1601 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1602 // empty arg list, don't push any params.
1603 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1604
1605 // In C++, the empty parameter-type-list must be spelled "void"; a
1606 // typedef of void is not permitted.
1607 if (getLangOptions().CPlusPlus &&
1608 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1609 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1610 }
1611 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1612 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1613 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1614 }
1615
1616 NewFD->setParams(Context, &Params[0], Params.size());
1617 } else if (R->getAsTypedefType()) {
1618 // When we're declaring a function with a typedef, as in the
1619 // following example, we'll need to synthesize (unnamed)
1620 // parameters for use in the declaration.
1621 //
1622 // @code
1623 // typedef void fn(int);
1624 // fn f;
1625 // @endcode
1626 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1627 if (!FT) {
1628 // This is a typedef of a function with no prototype, so we
1629 // don't need to do anything.
1630 } else if ((FT->getNumArgs() == 0) ||
1631 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1632 FT->getArgType(0)->isVoidType())) {
1633 // This is a zero-argument function. We don't need to do anything.
1634 } else {
1635 // Synthesize a parameter for each argument type.
1636 llvm::SmallVector<ParmVarDecl*, 16> Params;
1637 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1638 ArgType != FT->arg_type_end(); ++ArgType) {
1639 Params.push_back(ParmVarDecl::Create(Context, DC,
1640 SourceLocation(), 0,
1641 *ArgType, VarDecl::None,
1642 0, 0));
1643 }
1644
1645 NewFD->setParams(Context, &Params[0], Params.size());
1646 }
1647 }
1648
1649 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1650 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1651 else if (isa<CXXDestructorDecl>(NewFD)) {
1652 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1653 Record->setUserDeclaredDestructor(true);
1654 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1655 // user-defined destructor.
1656 Record->setPOD(false);
1657 } else if (CXXConversionDecl *Conversion =
1658 dyn_cast<CXXConversionDecl>(NewFD))
1659 ActOnConversionDeclarator(Conversion);
1660
1661 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1662 if (NewFD->isOverloadedOperator() &&
1663 CheckOverloadedOperatorDeclaration(NewFD))
1664 NewFD->setInvalidDecl();
1665
1666 // Merge the decl with the existing one if appropriate. Since C functions
1667 // are in a flat namespace, make sure we consider decls in outer scopes.
1668 if (PrevDecl &&
1669 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1670 bool Redeclaration = false;
1671
1672 // If C++, determine whether NewFD is an overload of PrevDecl or
1673 // a declaration that requires merging. If it's an overload,
1674 // there's no more work to do here; we'll just add the new
1675 // function to the scope.
1676 OverloadedFunctionDecl::function_iterator MatchedDecl;
1677 if (!getLangOptions().CPlusPlus ||
1678 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1679 Decl *OldDecl = PrevDecl;
1680
1681 // If PrevDecl was an overloaded function, extract the
1682 // FunctionDecl that matched.
1683 if (isa<OverloadedFunctionDecl>(PrevDecl))
1684 OldDecl = *MatchedDecl;
1685
1686 // NewFD and PrevDecl represent declarations that need to be
1687 // merged.
1688 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1689
1690 if (NewFD == 0) return 0;
1691 if (Redeclaration) {
1692 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1693
1694 // An out-of-line member function declaration must also be a
1695 // definition (C++ [dcl.meaning]p1).
1696 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1697 !InvalidDecl) {
1698 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1699 << D.getCXXScopeSpec().getRange();
1700 NewFD->setInvalidDecl();
1701 }
1702 }
1703 }
1704
1705 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1706 // The user tried to provide an out-of-line definition for a
1707 // member function, but there was no such member function
1708 // declared (C++ [class.mfct]p2). For example:
1709 //
1710 // class X {
1711 // void f() const;
1712 // };
1713 //
1714 // void X::f() { } // ill-formed
1715 //
1716 // Complain about this problem, and attempt to suggest close
1717 // matches (e.g., those that differ only in cv-qualifiers and
1718 // whether the parameter types are references).
1719 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1720 << cast<CXXRecordDecl>(DC)->getDeclName()
1721 << D.getCXXScopeSpec().getRange();
1722 InvalidDecl = true;
1723
1724 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1725 if (!PrevDecl) {
1726 // Nothing to suggest.
1727 } else if (OverloadedFunctionDecl *Ovl
1728 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1729 for (OverloadedFunctionDecl::function_iterator
1730 Func = Ovl->function_begin(),
1731 FuncEnd = Ovl->function_end();
1732 Func != FuncEnd; ++Func) {
1733 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1734 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1735
1736 }
1737 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1738 // Suggest this no matter how mismatched it is; it's the only
1739 // thing we have.
1740 unsigned diag;
1741 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1742 diag = diag::note_member_def_close_match;
1743 else if (Method->getBody())
1744 diag = diag::note_previous_definition;
1745 else
1746 diag = diag::note_previous_declaration;
1747 Diag(Method->getLocation(), diag);
1748 }
1749
1750 PrevDecl = 0;
1751 }
1752 }
1753 // Handle attributes. We need to have merged decls when handling attributes
1754 // (for example to check for conflicts, etc).
1755 ProcessDeclAttributes(NewFD, D);
1756
1757 if (getLangOptions().CPlusPlus) {
1758 // In C++, check default arguments now that we have merged decls.
1759 CheckCXXDefaultArguments(NewFD);
1760
1761 // An out-of-line member function declaration must also be a
1762 // definition (C++ [dcl.meaning]p1).
1763 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1764 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1765 << D.getCXXScopeSpec().getRange();
1766 InvalidDecl = true;
1767 }
1768 }
1769 return NewFD;
1770}
1771
Steve Narofffc08f5e2008-10-27 11:34:16 +00001772void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001773 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1774 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001775}
1776
Eli Friedman02c22ce2008-05-20 13:48:25 +00001777bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1778 switch (Init->getStmtClass()) {
1779 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001780 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001781 return true;
1782 case Expr::ParenExprClass: {
1783 const ParenExpr* PE = cast<ParenExpr>(Init);
1784 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1785 }
1786 case Expr::CompoundLiteralExprClass:
1787 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001788 case Expr::DeclRefExprClass:
1789 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001790 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001791 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1792 if (VD->hasGlobalStorage())
1793 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001794 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001795 return true;
1796 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001797 if (isa<FunctionDecl>(D))
1798 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001799 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001800 return true;
1801 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001802 case Expr::MemberExprClass: {
1803 const MemberExpr *M = cast<MemberExpr>(Init);
1804 if (M->isArrow())
1805 return CheckAddressConstantExpression(M->getBase());
1806 return CheckAddressConstantExpressionLValue(M->getBase());
1807 }
1808 case Expr::ArraySubscriptExprClass: {
1809 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1810 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1811 return CheckAddressConstantExpression(ASE->getBase()) ||
1812 CheckArithmeticConstantExpression(ASE->getIdx());
1813 }
1814 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001815 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001816 return false;
1817 case Expr::UnaryOperatorClass: {
1818 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1819
1820 // C99 6.6p9
1821 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001822 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001823
Steve Narofffc08f5e2008-10-27 11:34:16 +00001824 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001825 return true;
1826 }
1827 }
1828}
1829
1830bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1831 switch (Init->getStmtClass()) {
1832 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001833 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001834 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001835 case Expr::ParenExprClass:
1836 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001837 case Expr::StringLiteralClass:
1838 case Expr::ObjCStringLiteralClass:
1839 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001840 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001841 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001842 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1843 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1844 Builtin::BI__builtin___CFStringMakeConstantString)
1845 return false;
1846
Steve Narofffc08f5e2008-10-27 11:34:16 +00001847 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001848 return true;
1849
Eli Friedman02c22ce2008-05-20 13:48:25 +00001850 case Expr::UnaryOperatorClass: {
1851 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1852
1853 // C99 6.6p9
1854 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1855 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1856
1857 if (Exp->getOpcode() == UnaryOperator::Extension)
1858 return CheckAddressConstantExpression(Exp->getSubExpr());
1859
Steve Narofffc08f5e2008-10-27 11:34:16 +00001860 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001861 return true;
1862 }
1863 case Expr::BinaryOperatorClass: {
1864 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1865 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1866
1867 Expr *PExp = Exp->getLHS();
1868 Expr *IExp = Exp->getRHS();
1869 if (IExp->getType()->isPointerType())
1870 std::swap(PExp, IExp);
1871
1872 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1873 return CheckAddressConstantExpression(PExp) ||
1874 CheckArithmeticConstantExpression(IExp);
1875 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001876 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001877 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001878 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001879 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1880 // Check for implicit promotion
1881 if (SubExpr->getType()->isFunctionType() ||
1882 SubExpr->getType()->isArrayType())
1883 return CheckAddressConstantExpressionLValue(SubExpr);
1884 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001885
1886 // Check for pointer->pointer cast
1887 if (SubExpr->getType()->isPointerType())
1888 return CheckAddressConstantExpression(SubExpr);
1889
Eli Friedman1fad3c62008-08-25 20:46:57 +00001890 if (SubExpr->getType()->isIntegralType()) {
1891 // Check for the special-case of a pointer->int->pointer cast;
1892 // this isn't standard, but some code requires it. See
1893 // PR2720 for an example.
1894 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1895 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1896 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1897 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1898 if (IntWidth >= PointerWidth) {
1899 return CheckAddressConstantExpression(SubCast->getSubExpr());
1900 }
1901 }
1902 }
1903 }
1904 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001905 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001906 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001907
Steve Narofffc08f5e2008-10-27 11:34:16 +00001908 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001909 return true;
1910 }
1911 case Expr::ConditionalOperatorClass: {
1912 // FIXME: Should we pedwarn here?
1913 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1914 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001915 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001916 return true;
1917 }
1918 if (CheckArithmeticConstantExpression(Exp->getCond()))
1919 return true;
1920 if (Exp->getLHS() &&
1921 CheckAddressConstantExpression(Exp->getLHS()))
1922 return true;
1923 return CheckAddressConstantExpression(Exp->getRHS());
1924 }
1925 case Expr::AddrLabelExprClass:
1926 return false;
1927 }
1928}
1929
Eli Friedman998dffb2008-06-09 05:05:07 +00001930static const Expr* FindExpressionBaseAddress(const Expr* E);
1931
1932static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1933 switch (E->getStmtClass()) {
1934 default:
1935 return E;
1936 case Expr::ParenExprClass: {
1937 const ParenExpr* PE = cast<ParenExpr>(E);
1938 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1939 }
1940 case Expr::MemberExprClass: {
1941 const MemberExpr *M = cast<MemberExpr>(E);
1942 if (M->isArrow())
1943 return FindExpressionBaseAddress(M->getBase());
1944 return FindExpressionBaseAddressLValue(M->getBase());
1945 }
1946 case Expr::ArraySubscriptExprClass: {
1947 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1948 return FindExpressionBaseAddress(ASE->getBase());
1949 }
1950 case Expr::UnaryOperatorClass: {
1951 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1952
1953 if (Exp->getOpcode() == UnaryOperator::Deref)
1954 return FindExpressionBaseAddress(Exp->getSubExpr());
1955
1956 return E;
1957 }
1958 }
1959}
1960
1961static const Expr* FindExpressionBaseAddress(const Expr* E) {
1962 switch (E->getStmtClass()) {
1963 default:
1964 return E;
1965 case Expr::ParenExprClass: {
1966 const ParenExpr* PE = cast<ParenExpr>(E);
1967 return FindExpressionBaseAddress(PE->getSubExpr());
1968 }
1969 case Expr::UnaryOperatorClass: {
1970 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1971
1972 // C99 6.6p9
1973 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1974 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1975
1976 if (Exp->getOpcode() == UnaryOperator::Extension)
1977 return FindExpressionBaseAddress(Exp->getSubExpr());
1978
1979 return E;
1980 }
1981 case Expr::BinaryOperatorClass: {
1982 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1983
1984 Expr *PExp = Exp->getLHS();
1985 Expr *IExp = Exp->getRHS();
1986 if (IExp->getType()->isPointerType())
1987 std::swap(PExp, IExp);
1988
1989 return FindExpressionBaseAddress(PExp);
1990 }
1991 case Expr::ImplicitCastExprClass: {
1992 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1993
1994 // Check for implicit promotion
1995 if (SubExpr->getType()->isFunctionType() ||
1996 SubExpr->getType()->isArrayType())
1997 return FindExpressionBaseAddressLValue(SubExpr);
1998
1999 // Check for pointer->pointer cast
2000 if (SubExpr->getType()->isPointerType())
2001 return FindExpressionBaseAddress(SubExpr);
2002
2003 // We assume that we have an arithmetic expression here;
2004 // if we don't, we'll figure it out later
2005 return 0;
2006 }
Douglas Gregor035d0882008-10-28 15:36:24 +00002007 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00002008 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2009
2010 // Check for pointer->pointer cast
2011 if (SubExpr->getType()->isPointerType())
2012 return FindExpressionBaseAddress(SubExpr);
2013
2014 // We assume that we have an arithmetic expression here;
2015 // if we don't, we'll figure it out later
2016 return 0;
2017 }
2018 }
2019}
2020
Anders Carlssone8bd9f22008-11-22 21:04:56 +00002021bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002022 switch (Init->getStmtClass()) {
2023 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002024 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002025 return true;
2026 case Expr::ParenExprClass: {
2027 const ParenExpr* PE = cast<ParenExpr>(Init);
2028 return CheckArithmeticConstantExpression(PE->getSubExpr());
2029 }
2030 case Expr::FloatingLiteralClass:
2031 case Expr::IntegerLiteralClass:
2032 case Expr::CharacterLiteralClass:
2033 case Expr::ImaginaryLiteralClass:
2034 case Expr::TypesCompatibleExprClass:
2035 case Expr::CXXBoolLiteralExprClass:
2036 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002037 case Expr::CallExprClass:
2038 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002039 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002040
2041 // Allow any constant foldable calls to builtins.
2042 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002043 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002044
Steve Narofffc08f5e2008-10-27 11:34:16 +00002045 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002046 return true;
2047 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002048 case Expr::DeclRefExprClass:
2049 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002050 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2051 if (isa<EnumConstantDecl>(D))
2052 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002053 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002054 return true;
2055 }
2056 case Expr::CompoundLiteralExprClass:
2057 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2058 // but vectors are allowed to be magic.
2059 if (Init->getType()->isVectorType())
2060 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002061 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002062 return true;
2063 case Expr::UnaryOperatorClass: {
2064 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2065
2066 switch (Exp->getOpcode()) {
2067 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2068 // See C99 6.6p3.
2069 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002070 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002071 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002072 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002073 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2074 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002075 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002076 return true;
2077 case UnaryOperator::Extension:
2078 case UnaryOperator::LNot:
2079 case UnaryOperator::Plus:
2080 case UnaryOperator::Minus:
2081 case UnaryOperator::Not:
2082 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2083 }
2084 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002085 case Expr::SizeOfAlignOfExprClass: {
2086 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002087 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002088 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002089 return false;
2090 // alignof always evaluates to a constant.
2091 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002092 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002093 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002094 return true;
2095 }
2096 return false;
2097 }
2098 case Expr::BinaryOperatorClass: {
2099 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2100
2101 if (Exp->getLHS()->getType()->isArithmeticType() &&
2102 Exp->getRHS()->getType()->isArithmeticType()) {
2103 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2104 CheckArithmeticConstantExpression(Exp->getRHS());
2105 }
2106
Eli Friedman998dffb2008-06-09 05:05:07 +00002107 if (Exp->getLHS()->getType()->isPointerType() &&
2108 Exp->getRHS()->getType()->isPointerType()) {
2109 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2110 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2111
2112 // Only allow a null (constant integer) base; we could
2113 // allow some additional cases if necessary, but this
2114 // is sufficient to cover offsetof-like constructs.
2115 if (!LHSBase && !RHSBase) {
2116 return CheckAddressConstantExpression(Exp->getLHS()) ||
2117 CheckAddressConstantExpression(Exp->getRHS());
2118 }
2119 }
2120
Steve Narofffc08f5e2008-10-27 11:34:16 +00002121 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002122 return true;
2123 }
2124 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002125 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002126 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002127 if (SubExpr->getType()->isArithmeticType())
2128 return CheckArithmeticConstantExpression(SubExpr);
2129
Eli Friedman266df142008-09-02 09:37:00 +00002130 if (SubExpr->getType()->isPointerType()) {
2131 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2132 // If the pointer has a null base, this is an offsetof-like construct
2133 if (!Base)
2134 return CheckAddressConstantExpression(SubExpr);
2135 }
2136
Steve Narofffc08f5e2008-10-27 11:34:16 +00002137 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002138 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002139 }
2140 case Expr::ConditionalOperatorClass: {
2141 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002142
2143 // If GNU extensions are disabled, we require all operands to be arithmetic
2144 // constant expressions.
2145 if (getLangOptions().NoExtensions) {
2146 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2147 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2148 CheckArithmeticConstantExpression(Exp->getRHS());
2149 }
2150
2151 // Otherwise, we have to emulate some of the behavior of fold here.
2152 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2153 // because it can constant fold things away. To retain compatibility with
2154 // GCC code, we see if we can fold the condition to a constant (which we
2155 // should always be able to do in theory). If so, we only require the
2156 // specified arm of the conditional to be a constant. This is a horrible
2157 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002158 Expr::EvalResult EvalResult;
2159 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2160 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002161 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002162 // won't be able to either. Use it to emit the diagnostic though.
2163 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002164 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002165 return Res;
2166 }
2167
2168 // Verify that the side following the condition is also a constant.
2169 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002170 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002171 std::swap(TrueSide, FalseSide);
2172
2173 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002174 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002175
2176 // Okay, the evaluated side evaluates to a constant, so we accept this.
2177 // Check to see if the other side is obviously not a constant. If so,
2178 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002179 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002180 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002181 diag::ext_typecheck_expression_not_constant_but_accepted)
2182 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002183 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002184 }
2185 }
2186}
2187
2188bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00002189 Init = Init->IgnoreParens();
2190
Nate Begemand6d2f772009-01-18 03:20:47 +00002191 if (Init->isEvaluatable(Context))
Anders Carlssonf6791c62008-12-05 05:09:56 +00002192 return false;
2193
Eli Friedman02c22ce2008-05-20 13:48:25 +00002194 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2195 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2196 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2197
Nuno Lopese7280452008-07-07 16:46:50 +00002198 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2199 return CheckForConstantInitializer(e->getInitializer(), DclT);
2200
Eli Friedman02c22ce2008-05-20 13:48:25 +00002201 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2202 unsigned numInits = Exp->getNumInits();
2203 for (unsigned i = 0; i < numInits; i++) {
2204 // FIXME: Need to get the type of the declaration for C++,
2205 // because it could be a reference?
2206 if (CheckForConstantInitializer(Exp->getInit(i),
2207 Exp->getInit(i)->getType()))
2208 return true;
2209 }
2210 return false;
2211 }
2212
Anders Carlssonf6791c62008-12-05 05:09:56 +00002213 // FIXME: We can probably remove some of this code below, now that
2214 // Expr::Evaluate is doing the heavy lifting for scalars.
2215
Eli Friedman02c22ce2008-05-20 13:48:25 +00002216 if (Init->isNullPointerConstant(Context))
2217 return false;
2218 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002219 QualType InitTy = Context.getCanonicalType(Init->getType())
2220 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002221 if (InitTy == Context.BoolTy) {
2222 // Special handling for pointers implicitly cast to bool;
2223 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2224 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2225 Expr* SubE = ICE->getSubExpr();
2226 if (SubE->getType()->isPointerType() ||
2227 SubE->getType()->isArrayType() ||
2228 SubE->getType()->isFunctionType()) {
2229 return CheckAddressConstantExpression(Init);
2230 }
2231 }
2232 } else if (InitTy->isIntegralType()) {
2233 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002234 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002235 SubE = CE->getSubExpr();
2236 // Special check for pointer cast to int; we allow as an extension
2237 // an address constant cast to an integer if the integer
2238 // is of an appropriate width (this sort of code is apparently used
2239 // in some places).
2240 // FIXME: Add pedwarn?
2241 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2242 if (SubE && (SubE->getType()->isPointerType() ||
2243 SubE->getType()->isArrayType() ||
2244 SubE->getType()->isFunctionType())) {
2245 unsigned IntWidth = Context.getTypeSize(Init->getType());
2246 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2247 if (IntWidth >= PointerWidth)
2248 return CheckAddressConstantExpression(Init);
2249 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002250 }
2251
2252 return CheckArithmeticConstantExpression(Init);
2253 }
2254
2255 if (Init->getType()->isPointerType())
2256 return CheckAddressConstantExpression(Init);
2257
Eli Friedman25086f02008-05-30 18:14:48 +00002258 // An array type at the top level that isn't an init-list must
2259 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002260 if (Init->getType()->isArrayType())
2261 return false;
2262
Nuno Lopes1dc26762008-09-01 18:42:41 +00002263 if (Init->getType()->isFunctionType())
2264 return false;
2265
Steve Naroffdff3fb22008-10-02 17:12:56 +00002266 // Allow block exprs at top level.
2267 if (Init->getType()->isBlockPointerType())
2268 return false;
Nuno Lopes8260d5d2009-01-15 16:44:45 +00002269
2270 // GCC cast to union extension
2271 // note: the validity of the cast expr is checked by CheckCastTypes()
2272 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2273 QualType T = C->getType();
2274 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2275 }
2276
Steve Narofffc08f5e2008-10-27 11:34:16 +00002277 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002278 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002279}
2280
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002281void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002282 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2283}
2284
2285/// AddInitializerToDecl - Adds the initializer Init to the
2286/// declaration dcl. If DirectInit is true, this is C++ direct
2287/// initialization rather than copy initialization.
2288void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002289 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002290 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002291 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002292
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002293 // If there is no declaration, there was an error parsing it. Just ignore
2294 // the initializer.
2295 if (RealDecl == 0) {
2296 delete Init;
2297 return;
2298 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002299
Steve Naroff420d0f52007-09-12 20:13:48 +00002300 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2301 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00002302 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2303 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002304 RealDecl->setInvalidDecl();
2305 return;
2306 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002307 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002308 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002309 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002310 if (VDecl->isBlockVarDecl()) {
2311 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002312 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002313 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002314 VDecl->setInvalidDecl();
2315 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002316 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002317 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002318 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002319
2320 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2321 if (!getLangOptions().CPlusPlus) {
2322 if (SC == VarDecl::Static) // C99 6.7.8p4.
2323 CheckForConstantInitializer(Init, DclT);
2324 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002325 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002326 } else if (VDecl->isFileVarDecl()) {
2327 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002328 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002329 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002330 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002331 VDecl->getDeclName(), DirectInit))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002332 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002333
Anders Carlssonea7140a2008-08-22 05:00:02 +00002334 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2335 if (!getLangOptions().CPlusPlus) {
2336 // C99 6.7.8p4. All file scoped initializers need to be constant.
2337 CheckForConstantInitializer(Init, DclT);
2338 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002339 }
2340 // If the type changed, it means we had an incomplete type that was
2341 // completed by the initializer. For example:
2342 // int ary[] = { 1, 3, 5 };
2343 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002344 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002345 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002346 Init->setType(DclT);
2347 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002348
2349 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002350 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002351 return;
2352}
2353
Douglas Gregor81c29152008-10-29 00:13:59 +00002354void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2355 Decl *RealDecl = static_cast<Decl *>(dcl);
2356
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002357 // If there is no declaration, there was an error parsing it. Just ignore it.
2358 if (RealDecl == 0)
2359 return;
2360
Douglas Gregor81c29152008-10-29 00:13:59 +00002361 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2362 QualType Type = Var->getType();
2363 // C++ [dcl.init.ref]p3:
2364 // The initializer can be omitted for a reference only in a
2365 // parameter declaration (8.3.5), in the declaration of a
2366 // function return type, in the declaration of a class member
2367 // within its class declaration (9.2), and where the extern
2368 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002369 if (Type->isReferenceType() &&
2370 Var->getStorageClass() != VarDecl::Extern &&
2371 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002372 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002373 << Var->getDeclName()
2374 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002375 Var->setInvalidDecl();
2376 return;
2377 }
2378
2379 // C++ [dcl.init]p9:
2380 //
2381 // If no initializer is specified for an object, and the object
2382 // is of (possibly cv-qualified) non-POD class type (or array
2383 // thereof), the object shall be default-initialized; if the
2384 // object is of const-qualified type, the underlying class type
2385 // shall have a user-declared default constructor.
2386 if (getLangOptions().CPlusPlus) {
2387 QualType InitType = Type;
2388 if (const ArrayType *Array = Context.getAsArrayType(Type))
2389 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002390 if (Var->getStorageClass() != VarDecl::Extern &&
2391 Var->getStorageClass() != VarDecl::PrivateExtern &&
2392 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002393 const CXXConstructorDecl *Constructor
2394 = PerformInitializationByConstructor(InitType, 0, 0,
2395 Var->getLocation(),
2396 SourceRange(Var->getLocation(),
2397 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002398 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002399 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002400 if (!Constructor)
2401 Var->setInvalidDecl();
2402 }
2403 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002404
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002405#if 0
2406 // FIXME: Temporarily disabled because we are not properly parsing
2407 // linkage specifications on declarations, e.g.,
2408 //
2409 // extern "C" const CGPoint CGPointerZero;
2410 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002411 // C++ [dcl.init]p9:
2412 //
2413 // If no initializer is specified for an object, and the
2414 // object is of (possibly cv-qualified) non-POD class type (or
2415 // array thereof), the object shall be default-initialized; if
2416 // the object is of const-qualified type, the underlying class
2417 // type shall have a user-declared default
2418 // constructor. Otherwise, if no initializer is specified for
2419 // an object, the object and its subobjects, if any, have an
2420 // indeterminate initial value; if the object or any of its
2421 // subobjects are of const-qualified type, the program is
2422 // ill-formed.
2423 //
2424 // This isn't technically an error in C, so we don't diagnose it.
2425 //
2426 // FIXME: Actually perform the POD/user-defined default
2427 // constructor check.
2428 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002429 Context.getCanonicalType(Type).isConstQualified() &&
2430 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002431 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2432 << Var->getName()
2433 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002434#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002435 }
2436}
2437
Chris Lattner4b009652007-07-25 00:24:17 +00002438/// The declarators are chained together backwards, reverse the list.
2439Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2440 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002441 Decl *GroupDecl = static_cast<Decl*>(group);
2442 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002443 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002444
2445 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2446 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002447 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002448 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002449 else { // reverse the list.
2450 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002451 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002452 Group->setNextDeclarator(NewGroup);
2453 NewGroup = Group;
2454 Group = Next;
2455 }
2456 }
2457 // Perform semantic analysis that depends on having fully processed both
2458 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002459 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002460 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2461 if (!IDecl)
2462 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002463 QualType T = IDecl->getType();
2464
Anders Carlsson68adbd12008-12-07 00:20:55 +00002465 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002466 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002467
2468 // FIXME: This won't give the correct result for
2469 // int a[10][n];
2470 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002471 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002472 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2473 SizeRange;
2474
Eli Friedman8ff07782008-02-15 18:16:39 +00002475 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002476 } else {
2477 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2478 // static storage duration, it shall not have a variable length array.
2479 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002480 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2481 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002482 IDecl->setInvalidDecl();
2483 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002484 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2485 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002486 IDecl->setInvalidDecl();
2487 }
2488 }
2489 } else if (T->isVariablyModifiedType()) {
2490 if (IDecl->isFileVarDecl()) {
2491 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2492 IDecl->setInvalidDecl();
2493 } else {
2494 if (IDecl->getStorageClass() == VarDecl::Extern) {
2495 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2496 IDecl->setInvalidDecl();
2497 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002498 }
2499 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002500
Steve Naroff6a0e2092007-09-12 14:07:44 +00002501 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2502 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002503 if (IDecl->isBlockVarDecl() &&
2504 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002505 if (!IDecl->isInvalidDecl() &&
2506 DiagnoseIncompleteType(IDecl->getLocation(), T,
2507 diag::err_typecheck_decl_incomplete_type))
Steve Naroff6a0e2092007-09-12 14:07:44 +00002508 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002509 }
2510 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2511 // object that has file scope without an initializer, and without a
2512 // storage-class specifier or with the storage-class specifier "static",
2513 // constitutes a tentative definition. Note: A tentative definition with
2514 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002515 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002516 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002517 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2518 // array to be completed. Don't issue a diagnostic.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002519 } else if (!IDecl->isInvalidDecl() &&
2520 DiagnoseIncompleteType(IDecl->getLocation(), T,
2521 diag::err_typecheck_decl_incomplete_type))
Steve Naroff60685462008-01-18 20:40:52 +00002522 // C99 6.9.2p3: If the declaration of an identifier for an object is
2523 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2524 // declared type shall not be an incomplete type.
Steve Naroff6a0e2092007-09-12 14:07:44 +00002525 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002526 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002527 if (IDecl->isFileVarDecl())
2528 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002529 }
2530 return NewGroup;
2531}
Steve Naroff91b03f72007-08-28 03:03:08 +00002532
Chris Lattner3e254fb2008-04-08 04:40:51 +00002533/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2534/// to introduce parameters into function prototype scope.
2535Sema::DeclTy *
2536Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002537 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002538
Chris Lattner3e254fb2008-04-08 04:40:51 +00002539 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002540 VarDecl::StorageClass StorageClass = VarDecl::None;
2541 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2542 StorageClass = VarDecl::Register;
2543 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002544 Diag(DS.getStorageClassSpecLoc(),
2545 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002546 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002547 }
2548 if (DS.isThreadSpecified()) {
2549 Diag(DS.getThreadSpecLoc(),
2550 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002551 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002552 }
2553
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002554 // Check that there are no default arguments inside the type of this
2555 // parameter (C++ only).
2556 if (getLangOptions().CPlusPlus)
2557 CheckExtraCXXDefaultArguments(D);
2558
Chris Lattner3e254fb2008-04-08 04:40:51 +00002559 // In this context, we *do not* check D.getInvalidType(). If the declarator
2560 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2561 // though it will not reflect the user specified type.
2562 QualType parmDeclType = GetTypeForDeclarator(D, S);
2563
2564 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2565
Chris Lattner4b009652007-07-25 00:24:17 +00002566 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2567 // Can this happen for params? We already checked that they don't conflict
2568 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002569 IdentifierInfo *II = D.getIdentifier();
2570 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002571 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002572 // Maybe we will complain about the shadowed template parameter.
2573 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2574 // Just pretend that we didn't see the previous declaration.
2575 PrevDecl = 0;
2576 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002577 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002578
2579 // Recover by removing the name
2580 II = 0;
2581 D.SetIdentifier(0, D.getIdentifierLoc());
2582 }
Chris Lattner4b009652007-07-25 00:24:17 +00002583 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002584
2585 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2586 // Doing the promotion here has a win and a loss. The win is the type for
2587 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2588 // code generator). The loss is the orginal type isn't preserved. For example:
2589 //
2590 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2591 // int blockvardecl[5];
2592 // sizeof(parmvardecl); // size == 4
2593 // sizeof(blockvardecl); // size == 20
2594 // }
2595 //
2596 // For expressions, all implicit conversions are captured using the
2597 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2598 //
2599 // FIXME: If a source translation tool needs to see the original type, then
2600 // we need to consider storing both types (in ParmVarDecl)...
2601 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002602 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002603 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002604 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002605 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002606 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002607
Chris Lattner3e254fb2008-04-08 04:40:51 +00002608 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2609 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002610 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002611 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002612
Chris Lattner3e254fb2008-04-08 04:40:51 +00002613 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002614 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002615
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002616 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2617 if (D.getCXXScopeSpec().isSet()) {
2618 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2619 << D.getCXXScopeSpec().getRange();
2620 New->setInvalidDecl();
2621 }
2622
Douglas Gregor8acb7272008-12-11 16:49:14 +00002623 // Add the parameter declaration into this scope.
2624 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002625 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002626 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002627
Chris Lattner9b384ca2008-06-29 00:02:00 +00002628 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002629 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002630
Chris Lattner4b009652007-07-25 00:24:17 +00002631}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002632
Chris Lattnerea148702007-10-09 17:14:05 +00002633Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002634 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002635 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2636 "Not a function declarator!");
2637 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002638
Chris Lattner4b009652007-07-25 00:24:17 +00002639 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2640 // for a K&R function.
2641 if (!FTI.hasPrototype) {
2642 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002643 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002644 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2645 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002646 // Implicitly declare the argument as type 'int' for lack of a better
2647 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002648 DeclSpec DS;
2649 const char* PrevSpec; // unused
2650 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2651 PrevSpec);
2652 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2653 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2654 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002655 }
2656 }
Chris Lattner4b009652007-07-25 00:24:17 +00002657 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002658 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002659 }
2660
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002661 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002662
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002663 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002664 ActOnDeclarator(ParentScope, D, 0,
2665 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002666}
2667
2668Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2669 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002670 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002671
2672 // See if this is a redefinition.
2673 const FunctionDecl *Definition;
2674 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002675 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002676 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002677 }
2678
Douglas Gregor8acb7272008-12-11 16:49:14 +00002679 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002680
Chris Lattner3e254fb2008-04-08 04:40:51 +00002681 // Check the validity of our function parameters
2682 CheckParmsForFunctionDef(FD);
2683
2684 // Introduce our parameters into the function scope
2685 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2686 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregord394a272009-01-09 18:51:29 +00002687 Param->setOwningFunction(FD);
2688
Chris Lattner3e254fb2008-04-08 04:40:51 +00002689 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002690 if (Param->getIdentifier())
2691 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002692 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002693
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002694 // Checking attributes of current function definition
2695 // dllimport attribute.
2696 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2697 // dllimport attribute cannot be applied to definition.
2698 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2699 Diag(FD->getLocation(),
2700 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2701 << "dllimport";
2702 FD->setInvalidDecl();
2703 return FD;
2704 } else {
2705 // If a symbol previously declared dllimport is later defined, the
2706 // attribute is ignored in subsequent references, and a warning is
2707 // emitted.
2708 Diag(FD->getLocation(),
2709 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2710 << FD->getNameAsCString() << "dllimport";
2711 }
2712 }
Chris Lattner4b009652007-07-25 00:24:17 +00002713 return FD;
2714}
2715
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002716Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002717 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002718 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002719 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002720 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002721 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002722 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002723 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002724 } else
2725 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002726 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002727 // Verify and clean out per-function state.
2728
2729 // Check goto/label use.
2730 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2731 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2732 // Verify that we have no forward references left. If so, there was a goto
2733 // or address of a label taken, but no definition of it. Label fwd
2734 // definitions are indicated with a null substmt.
2735 if (I->second->getSubStmt() == 0) {
2736 LabelStmt *L = I->second;
2737 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002738 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002739
2740 // At this point, we have gotos that use the bogus label. Stitch it into
2741 // the function body so that they aren't leaked and that the AST is well
2742 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002743 if (Body) {
2744 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002745 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002746 } else {
2747 // The whole function wasn't parsed correctly, just delete this.
2748 delete L;
2749 }
Chris Lattner4b009652007-07-25 00:24:17 +00002750 }
2751 }
2752 LabelMap.clear();
2753
Steve Naroff99ee4302007-11-11 23:20:51 +00002754 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002755}
2756
Chris Lattner4b009652007-07-25 00:24:17 +00002757/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2758/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002759ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2760 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002761 // Extension in C99. Legal in C90, but warn about it.
2762 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002763 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002764 else
Chris Lattner65cae292008-11-19 08:23:25 +00002765 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002766
2767 // FIXME: handle stuff like:
2768 // void foo() { extern float X(); }
2769 // void bar() { X(); } <-- implicit decl for X in another scope.
2770
2771 // Set a Declarator for the implicit definition: int foo();
2772 const char *Dummy;
2773 DeclSpec DS;
2774 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2775 Error = Error; // Silence warning.
2776 assert(!Error && "Error setting up implicit decl!");
2777 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002778 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002779 D.SetIdentifier(&II, Loc);
2780
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002781 // Insert this function into translation-unit scope.
2782
2783 DeclContext *PrevDC = CurContext;
2784 CurContext = Context.getTranslationUnitDecl();
2785
Steve Naroff9104f3c2008-04-04 14:32:09 +00002786 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002787 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002788 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002789
2790 CurContext = PrevDC;
2791
Steve Naroff9104f3c2008-04-04 14:32:09 +00002792 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002793}
2794
2795
Chris Lattner82bb4792007-11-14 06:34:38 +00002796TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002797 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002798 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002799 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002800
2801 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002802 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2803 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002804 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002805 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002806 if (D.getInvalidType())
2807 NewTD->setInvalidDecl();
2808 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002809}
2810
Steve Naroff0acc9c92007-09-15 18:49:24 +00002811/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002812/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor98b27542009-01-17 00:42:38 +00002813/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner4b009652007-07-25 00:24:17 +00002814/// reference/declaration/definition of a tag.
Douglas Gregor98b27542009-01-17 00:42:38 +00002815Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002816 SourceLocation KWLoc, const CXXScopeSpec &SS,
2817 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002818 AttributeList *Attr,
2819 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002820 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002821 assert((Name != 0 || TK == TK_Definition) &&
2822 "Nameless record must be a definition!");
2823
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002824 TagDecl::TagKind Kind;
Douglas Gregor98b27542009-01-17 00:42:38 +00002825 switch (TagSpec) {
Chris Lattner4b009652007-07-25 00:24:17 +00002826 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002827 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2828 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2829 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2830 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002831 }
2832
Douglas Gregorb748fc52009-01-12 22:49:06 +00002833 DeclContext *SearchDC = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002834 DeclContext *DC = CurContext;
Douglas Gregorcab994d2009-01-09 22:42:13 +00002835 DeclContext *LexicalContext = CurContext;
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002836 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002837
Douglas Gregor98b27542009-01-17 00:42:38 +00002838 bool Invalid = false;
2839
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002840 if (Name && SS.isNotEmpty()) {
2841 // We have a nested-name tag ('struct foo::bar').
2842
2843 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002844 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002845 Name = 0;
2846 goto CreateNewDecl;
2847 }
2848
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002849 DC = static_cast<DeclContext*>(SS.getScopeRep());
2850 // Look-up name inside 'foo::'.
Douglas Gregor78d70132009-01-14 22:20:51 +00002851 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2852 .getAsDecl());
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002853
2854 // A tag 'foo::bar' must already exist.
2855 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002856 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002857 Name = 0;
2858 goto CreateNewDecl;
2859 }
2860 } else {
2861 // If this is a named struct, check to see if there was a previous forward
2862 // declaration or definition.
2863 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Douglas Gregor78d70132009-01-14 22:20:51 +00002864 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
2865 .getAsDecl());
Douglas Gregordb568cf2009-01-08 20:45:30 +00002866
2867 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2868 // FIXME: This makes sure that we ignore the contexts associated
2869 // with C structs, unions, and enums when looking for a matching
2870 // tag declaration or definition. See the similar lookup tweak
2871 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregorb748fc52009-01-12 22:49:06 +00002872 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2873 SearchDC = SearchDC->getParent();
Douglas Gregordb568cf2009-01-08 20:45:30 +00002874 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002875 }
2876
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002877 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002878 // Maybe we will complain about the shadowed template parameter.
2879 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2880 // Just pretend that we didn't see the previous declaration.
2881 PrevDecl = 0;
2882 }
2883
Ted Kremenekd4434152008-09-02 21:26:19 +00002884 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002885 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2886 "unexpected Decl type");
2887 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002888 // If this is a use of a previous tag, or if the tag is already declared
2889 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002890 // rementions the tag), reuse the decl.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002891 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002892 // Make sure that this wasn't declared as an enum and now used as a
2893 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002894 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002895 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002896 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002897 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002898 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002899 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002900 Invalid = true;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002901 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002902 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002903
Douglas Gregorae644892008-12-15 16:32:14 +00002904 // FIXME: In the future, return a variant or some other clue
2905 // for the consumer of this Decl to know it doesn't own it.
2906 // For our current ASTs this shouldn't be a problem, but will
2907 // need to be changed with DeclGroups.
2908 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002909 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002910
2911 // Diagnose attempts to redefine a tag.
2912 if (TK == TK_Definition) {
2913 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2914 Diag(NameLoc, diag::err_redefinition) << Name;
2915 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor98b27542009-01-17 00:42:38 +00002916 // If this is a redefinition, recover by making this
2917 // struct be anonymous, which will make any later
2918 // references get the previous definition.
Douglas Gregorae644892008-12-15 16:32:14 +00002919 Name = 0;
2920 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002921 Invalid = true;
2922 } else {
2923 // If the type is currently being defined, complain
2924 // about a nested redefinition.
2925 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2926 if (Tag->isBeingDefined()) {
2927 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2928 Diag(PrevTagDecl->getLocation(),
2929 diag::note_previous_definition);
2930 Name = 0;
2931 PrevDecl = 0;
2932 Invalid = true;
2933 }
Douglas Gregorae644892008-12-15 16:32:14 +00002934 }
Douglas Gregor98b27542009-01-17 00:42:38 +00002935
Douglas Gregorae644892008-12-15 16:32:14 +00002936 // Okay, this is definition of a previously declared or referenced
2937 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor98b27542009-01-17 00:42:38 +00002938 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002939 }
Douglas Gregorae644892008-12-15 16:32:14 +00002940 // If we get here we have (another) forward declaration or we
2941 // have a definition. Just create a new decl.
2942 } else {
2943 // If we get here, this is a definition of a new tag type in a nested
2944 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2945 // new decl/type. We set PrevDecl to NULL so that the entities
2946 // have distinct types.
2947 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002948 }
Douglas Gregorae644892008-12-15 16:32:14 +00002949 // If we get here, we're going to create a new Decl. If PrevDecl
2950 // is non-NULL, it's a definition of the tag declared by
2951 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002952 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002953 // PrevDecl is a namespace.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002954 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002955 // The tag name clashes with a namespace name, issue an error and
2956 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002957 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002958 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002959 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002960 PrevDecl = 0;
Douglas Gregor98b27542009-01-17 00:42:38 +00002961 Invalid = true;
Douglas Gregorae644892008-12-15 16:32:14 +00002962 } else {
2963 // The existing declaration isn't relevant to us; we're in a
2964 // new scope, so clear out the previous declaration.
2965 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002966 }
Chris Lattner4b009652007-07-25 00:24:17 +00002967 }
Douglas Gregorcab994d2009-01-09 22:42:13 +00002968 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2969 (Kind != TagDecl::TK_enum)) {
2970 // C++ [basic.scope.pdecl]p5:
2971 // -- for an elaborated-type-specifier of the form
2972 //
2973 // class-key identifier
2974 //
2975 // if the elaborated-type-specifier is used in the
2976 // decl-specifier-seq or parameter-declaration-clause of a
2977 // function defined in namespace scope, the identifier is
2978 // declared as a class-name in the namespace that contains
2979 // the declaration; otherwise, except as a friend
2980 // declaration, the identifier is declared in the smallest
2981 // non-class, non-function-prototype scope that contains the
2982 // declaration.
2983 //
2984 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2985 // C structs and unions.
2986
2987 // Find the context where we'll be declaring the tag.
Douglas Gregorb748fc52009-01-12 22:49:06 +00002988 // FIXME: We would like to maintain the current DeclContext as the
2989 // lexical context,
Douglas Gregorcab994d2009-01-09 22:42:13 +00002990 while (DC->isRecord())
2991 DC = DC->getParent();
2992 LexicalContext = DC;
2993
2994 // Find the scope where we'll be declaring the tag.
2995 while (S->isClassScope() ||
2996 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor5eca99e2009-01-12 18:45:55 +00002997 ((S->getFlags() & Scope::DeclScope) == 0) ||
2998 (S->getEntity() &&
2999 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregorcab994d2009-01-09 22:42:13 +00003000 S = S->getParent();
Chris Lattner4b009652007-07-25 00:24:17 +00003001 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00003002
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003003CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00003004
3005 // If there is an identifier, use the location of the identifier as the
3006 // location of the decl, otherwise use the location of the struct/union
3007 // keyword.
3008 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3009
Douglas Gregorae644892008-12-15 16:32:14 +00003010 // Otherwise, create a new declaration. If there is a previous
3011 // declaration of the same entity, the two will be linked via
3012 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00003013 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00003014
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003015 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00003016 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3017 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00003018 New = EnumDecl::Create(Context, DC, Loc, Name,
3019 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003020 // If this is an undefined enum, warn.
3021 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003022 } else {
3023 // struct/union/class
3024
Chris Lattner4b009652007-07-25 00:24:17 +00003025 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3026 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003027 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00003028 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00003029 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3030 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003031 else
Douglas Gregorae644892008-12-15 16:32:14 +00003032 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3033 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003034 }
Douglas Gregorae644892008-12-15 16:32:14 +00003035
3036 if (Kind != TagDecl::TK_enum) {
3037 // Handle #pragma pack: if the #pragma pack stack has non-default
3038 // alignment, make up a packed attribute for this decl. These
3039 // attributes are checked when the ASTContext lays out the
3040 // structure.
3041 //
3042 // It is important for implementing the correct semantics that this
3043 // happen here (in act on tag decl). The #pragma pack stack is
3044 // maintained as a result of parser callbacks which can occur at
3045 // many points during the parsing of a struct declaration (because
3046 // the #pragma tokens are effectively skipped over during the
3047 // parsing of the struct).
3048 if (unsigned Alignment = PackContext.getAlignment())
3049 New->addAttr(new PackedAttr(Alignment * 8));
3050 }
3051
Douglas Gregor98b27542009-01-17 00:42:38 +00003052 if (Invalid)
3053 New->setInvalidDecl();
3054
Douglas Gregorae644892008-12-15 16:32:14 +00003055 if (Attr)
3056 ProcessDeclAttributeList(New, Attr);
3057
Douglas Gregor98b27542009-01-17 00:42:38 +00003058 // If we're declaring or defining a tag in function prototype scope
3059 // in C, note that this type can only be used within the function.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003060 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3061 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3062
Douglas Gregorae644892008-12-15 16:32:14 +00003063 // Set the lexical context. If the tag has a C++ scope specifier, the
3064 // lexical context will be different from the semantic context.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003065 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor98b27542009-01-17 00:42:38 +00003066
3067 if (TK == TK_Definition)
3068 New->startDefinition();
Chris Lattner4b009652007-07-25 00:24:17 +00003069
3070 // If this has an identifier, add it to the scope stack.
3071 if (Name) {
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003072 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003073
3074 // Add it to the decl chain.
Douglas Gregorcab994d2009-01-09 22:42:13 +00003075 if (LexicalContext != CurContext) {
3076 // FIXME: PushOnScopeChains should not rely on CurContext!
3077 DeclContext *OldContext = CurContext;
3078 CurContext = LexicalContext;
3079 PushOnScopeChains(New, S);
3080 CurContext = OldContext;
3081 } else
3082 PushOnScopeChains(New, S);
Douglas Gregorb748fc52009-01-12 22:49:06 +00003083 } else {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003084 LexicalContext->addDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +00003085 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003086
Chris Lattner4b009652007-07-25 00:24:17 +00003087 return New;
3088}
3089
Douglas Gregordb568cf2009-01-08 20:45:30 +00003090void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3091 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3092
3093 // Enter the tag context.
3094 PushDeclContext(S, Tag);
3095
3096 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3097 FieldCollector->StartClass();
3098
3099 if (Record->getIdentifier()) {
3100 // C++ [class]p2:
3101 // [...] The class-name is also inserted into the scope of the
3102 // class itself; this is known as the injected-class-name. For
3103 // purposes of access checking, the injected-class-name is treated
3104 // as if it were a public member name.
3105 RecordDecl *InjectedClassName
3106 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3107 CurContext, Record->getLocation(),
3108 Record->getIdentifier(), Record);
3109 InjectedClassName->setImplicit();
3110 PushOnScopeChains(InjectedClassName, S);
3111 }
3112 }
3113}
3114
3115void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3116 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3117
3118 if (isa<CXXRecordDecl>(Tag))
3119 FieldCollector->FinishClass();
3120
3121 // Exit this scope of this tag's definition.
3122 PopDeclContext();
3123
3124 // Notify the consumer that we've defined a tag.
3125 Consumer.HandleTagDeclDefinition(Tag);
3126}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003127
Chris Lattnera73e2202008-11-12 21:17:48 +00003128/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3129/// types into constant array types in certain situations which would otherwise
3130/// be errors (for GCC compatibility).
3131static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3132 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003133 // This method tries to turn a variable array into a constant
3134 // array even when the size isn't an ICE. This is necessary
3135 // for compatibility with code that depends on gcc's buggy
3136 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003137 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3138 if (!VLATy) return QualType();
3139
Anders Carlsson8c3de802008-12-19 20:58:05 +00003140 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003141 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003142 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003143 return QualType();
3144
Anders Carlsson8c3de802008-12-19 20:58:05 +00003145 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3146 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003147 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3148 return Context.getConstantArrayType(VLATy->getElementType(),
3149 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003150 return QualType();
3151}
3152
Anders Carlsson108229a2008-12-06 20:33:04 +00003153bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003154 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003155 // FIXME: 6.7.2.1p4 - verify the field type.
3156
3157 llvm::APSInt Value;
3158 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3159 return true;
3160
Chris Lattner8464c372008-12-12 04:56:04 +00003161 // Zero-width bitfield is ok for anonymous field.
3162 if (Value == 0 && FieldName)
3163 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3164
3165 if (Value.isNegative())
3166 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003167
3168 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3169 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003170 if (TypeSize && Value.getZExtValue() > TypeSize)
3171 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3172 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003173
3174 return false;
3175}
3176
Steve Naroff0acc9c92007-09-15 18:49:24 +00003177/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003178/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003179Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003180 SourceLocation DeclStart,
3181 Declarator &D, ExprTy *BitfieldWidth) {
3182 IdentifierInfo *II = D.getIdentifier();
3183 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003184 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003185 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003186 if (II) Loc = D.getIdentifierLoc();
3187
3188 // FIXME: Unnamed fields can be handled in various different ways, for
3189 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003190
Chris Lattner4b009652007-07-25 00:24:17 +00003191 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003192 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3193 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003194
Chris Lattner4b009652007-07-25 00:24:17 +00003195 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3196 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003197 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003198 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003199 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003200 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003201 T = FixedTy;
3202 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003203 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003204 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003205 InvalidDecl = true;
3206 }
Chris Lattner4b009652007-07-25 00:24:17 +00003207 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003208
3209 if (BitWidth) {
3210 if (VerifyBitField(Loc, II, T, BitWidth))
3211 InvalidDecl = true;
3212 } else {
3213 // Not a bitfield.
3214
3215 // validate II.
3216
3217 }
3218
Chris Lattner4b009652007-07-25 00:24:17 +00003219 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003220 FieldDecl *NewFD;
3221
Douglas Gregor8acb7272008-12-11 16:49:14 +00003222 NewFD = FieldDecl::Create(Context, Record,
3223 Loc, II, T, BitWidth,
3224 D.getDeclSpec().getStorageClassSpec() ==
3225 DeclSpec::SCS_mutable,
3226 /*PrevDecl=*/0);
3227
Douglas Gregordb568cf2009-01-08 20:45:30 +00003228 if (II) {
3229 Decl *PrevDecl
3230 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3231 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3232 && !isa<TagDecl>(PrevDecl)) {
3233 Diag(Loc, diag::err_duplicate_member) << II;
3234 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3235 NewFD->setInvalidDecl();
3236 Record->setInvalidDecl();
3237 }
3238 }
3239
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003240 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003241 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003242 if (!T->isPODType())
3243 cast<CXXRecordDecl>(Record)->setPOD(false);
3244 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003245
Chris Lattner9b384ca2008-06-29 00:02:00 +00003246 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003247
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003248 if (D.getInvalidType() || InvalidDecl)
3249 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003250
Douglas Gregordb568cf2009-01-08 20:45:30 +00003251 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003252 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003253 } else
Douglas Gregor03b2ad22009-01-12 23:27:07 +00003254 Record->addDecl(NewFD);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003255
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003256 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003257}
3258
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003259/// TranslateIvarVisibility - Translate visibility from a token ID to an
3260/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003261static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003262TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003263 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003264 default: assert(0 && "Unknown visitibility kind");
3265 case tok::objc_private: return ObjCIvarDecl::Private;
3266 case tok::objc_public: return ObjCIvarDecl::Public;
3267 case tok::objc_protected: return ObjCIvarDecl::Protected;
3268 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003269 }
3270}
3271
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003272/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3273/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003274Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003275 SourceLocation DeclStart,
3276 Declarator &D, ExprTy *BitfieldWidth,
3277 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003278
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003279 IdentifierInfo *II = D.getIdentifier();
3280 Expr *BitWidth = (Expr*)BitfieldWidth;
3281 SourceLocation Loc = DeclStart;
3282 if (II) Loc = D.getIdentifierLoc();
3283
3284 // FIXME: Unnamed fields can be handled in various different ways, for
3285 // example, unnamed unions inject all members into the struct namespace!
3286
Anders Carlsson108229a2008-12-06 20:33:04 +00003287 QualType T = GetTypeForDeclarator(D, S);
3288 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3289 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003290
3291 if (BitWidth) {
3292 // TODO: Validate.
3293 //printf("WARNING: BITFIELDS IGNORED!\n");
3294
3295 // 6.7.2.1p3
3296 // 6.7.2.1p4
3297
3298 } else {
3299 // Not a bitfield.
3300
3301 // validate II.
3302
3303 }
3304
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003305 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3306 // than a variably modified type.
3307 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003308 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003309 InvalidDecl = true;
3310 }
3311
Ted Kremenek173dd312008-07-23 18:04:17 +00003312 // Get the visibility (access control) for this ivar.
3313 ObjCIvarDecl::AccessControl ac =
3314 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3315 : ObjCIvarDecl::None;
3316
3317 // Construct the decl.
3318 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003319 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003320
Douglas Gregordb568cf2009-01-08 20:45:30 +00003321 if (II) {
3322 Decl *PrevDecl
3323 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3324 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3325 && !isa<TagDecl>(PrevDecl)) {
3326 Diag(Loc, diag::err_duplicate_member) << II;
3327 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3328 NewID->setInvalidDecl();
3329 }
3330 }
3331
Ted Kremenek173dd312008-07-23 18:04:17 +00003332 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003333 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003334
3335 if (D.getInvalidType() || InvalidDecl)
3336 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003337
Douglas Gregordb568cf2009-01-08 20:45:30 +00003338 if (II) {
3339 // FIXME: When interfaces are DeclContexts, we'll need to add
3340 // these to the interface.
3341 S->AddDecl(NewID);
3342 IdResolver.AddDecl(NewID);
3343 }
3344
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003345 return NewID;
3346}
3347
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003348void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003349 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003350 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003351 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003352 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003353 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3354 assert(EnclosingDecl && "missing record or interface decl");
3355 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3356
Chris Lattner4b009652007-07-25 00:24:17 +00003357 // Verify that all the fields are okay.
3358 unsigned NumNamedMembers = 0;
3359 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003360
Chris Lattner4b009652007-07-25 00:24:17 +00003361 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003362 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3363 assert(FD && "missing field decl");
3364
Chris Lattner4b009652007-07-25 00:24:17 +00003365 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003366 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003367
Douglas Gregordb568cf2009-01-08 20:45:30 +00003368 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003369 // Remember all fields written by the user.
3370 RecFields.push_back(FD);
3371 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003372
Chris Lattner4b009652007-07-25 00:24:17 +00003373 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003374 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003375 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003376 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003377 FD->setInvalidDecl();
3378 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003379 continue;
3380 }
Chris Lattner4b009652007-07-25 00:24:17 +00003381 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3382 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003383 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003384 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3385 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003386 FD->setInvalidDecl();
3387 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003388 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003389 }
Chris Lattner4b009652007-07-25 00:24:17 +00003390 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003391 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003392 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003393 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3394 diag::err_field_incomplete);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003395 FD->setInvalidDecl();
3396 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003397 continue;
3398 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003399 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003400 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003401 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003402 FD->setInvalidDecl();
3403 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003404 continue;
3405 }
Chris Lattner4b009652007-07-25 00:24:17 +00003406 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003407 if (Record)
3408 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003409 }
Chris Lattner4b009652007-07-25 00:24:17 +00003410 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3411 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003412 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003413 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3414 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003415 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003416 Record->setHasFlexibleArrayMember(true);
3417 } else {
3418 // If this is a struct/class and this is not the last element, reject
3419 // it. Note that GCC supports variable sized arrays in the middle of
3420 // structures.
3421 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003422 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003423 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003424 FD->setInvalidDecl();
3425 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003426 continue;
3427 }
Chris Lattner4b009652007-07-25 00:24:17 +00003428 // We support flexible arrays at the end of structs in other structs
3429 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003430 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003431 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003432 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003433 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003434 }
3435 }
3436 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003437 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003438 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003439 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003440 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003441 FD->setInvalidDecl();
3442 EnclosingDecl->setInvalidDecl();
3443 continue;
3444 }
Chris Lattner4b009652007-07-25 00:24:17 +00003445 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003446 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003447 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003448 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003449
Chris Lattner4b009652007-07-25 00:24:17 +00003450 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003451 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003452 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003453 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003454 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003455 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003456 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003457 // Must enforce the rule that ivars in the base classes may not be
3458 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003459 if (ID->getSuperClass()) {
3460 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3461 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3462 ObjCIvarDecl* Ivar = (*IVI);
3463 IdentifierInfo *II = Ivar->getIdentifier();
3464 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3465 if (prevIvar) {
3466 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003467 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003468 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003469 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003470 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003471 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003472 else if (ObjCImplementationDecl *IMPDecl =
3473 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003474 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3475 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003476 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003477 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003478 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003479
3480 if (Attr)
3481 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003482}
3483
Steve Naroff0acc9c92007-09-15 18:49:24 +00003484Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003485 DeclTy *lastEnumConst,
3486 SourceLocation IdLoc, IdentifierInfo *Id,
3487 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003488 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003489 EnumConstantDecl *LastEnumConst =
3490 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3491 Expr *Val = static_cast<Expr*>(val);
3492
Chris Lattnera7549902007-08-26 06:24:45 +00003493 // The scope passed in may not be a decl scope. Zip up the scope tree until
3494 // we find one that is.
Douglas Gregor5eca99e2009-01-12 18:45:55 +00003495 S = getNonFieldDeclScope(S);
Chris Lattnera7549902007-08-26 06:24:45 +00003496
Chris Lattner4b009652007-07-25 00:24:17 +00003497 // Verify that there isn't already something declared with this name in this
3498 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003499 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003500 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003501 // Maybe we will complain about the shadowed template parameter.
3502 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3503 // Just pretend that we didn't see the previous declaration.
3504 PrevDecl = 0;
3505 }
3506
3507 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003508 // When in C++, we may get a TagDecl with the same name; in this case the
3509 // enum constant will 'hide' the tag.
3510 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3511 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003512 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003513 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003514 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003515 else
Chris Lattner65cae292008-11-19 08:23:25 +00003516 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003517 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003518 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003519 return 0;
3520 }
3521 }
3522
3523 llvm::APSInt EnumVal(32);
3524 QualType EltTy;
3525 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003526 // Make sure to promote the operand type to int.
3527 UsualUnaryConversions(Val);
3528
Chris Lattner4b009652007-07-25 00:24:17 +00003529 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3530 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003531 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003532 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003533 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003534 } else {
3535 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003536 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003537 }
3538
3539 if (!Val) {
3540 if (LastEnumConst) {
3541 // Assign the last value + 1.
3542 EnumVal = LastEnumConst->getInitVal();
3543 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003544
3545 // Check for overflow on increment.
3546 if (EnumVal < LastEnumConst->getInitVal())
3547 Diag(IdLoc, diag::warn_enum_value_overflow);
3548
Chris Lattnere7f53a42007-08-27 17:37:24 +00003549 EltTy = LastEnumConst->getType();
3550 } else {
3551 // First value, set to zero.
3552 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003553 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003554 }
Chris Lattner4b009652007-07-25 00:24:17 +00003555 }
3556
Chris Lattnere4650482008-03-15 06:12:44 +00003557 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003558 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3559 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003560 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003561
3562 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003563 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003564
Chris Lattner4b009652007-07-25 00:24:17 +00003565 return New;
3566}
3567
Steve Naroffb0726b82008-08-07 14:08:16 +00003568// FIXME: For consistency with ActOnFields(), we should have the parser
3569// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003570void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003571 DeclTy **Elements, unsigned NumElements) {
3572 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003573 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003574
Chris Lattner435c3fd2007-08-28 05:10:31 +00003575 // TODO: If the result value doesn't fit in an int, it must be a long or long
3576 // long value. ISO C does not support this, but GCC does as an extension,
3577 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003578 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003579
Chris Lattner206754a2007-08-28 06:15:15 +00003580 // Verify that all the values are okay, compute the size of the values, and
3581 // reverse the list.
3582 unsigned NumNegativeBits = 0;
3583 unsigned NumPositiveBits = 0;
3584
3585 // Keep track of whether all elements have type int.
3586 bool AllElementsInt = true;
3587
Chris Lattner4b009652007-07-25 00:24:17 +00003588 for (unsigned i = 0; i != NumElements; ++i) {
3589 EnumConstantDecl *ECD =
3590 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3591 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003592
3593 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003594 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003595 assert(InitVal.getBitWidth() >= IntWidth &&
3596 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003597 if (InitVal.getBitWidth() > IntWidth) {
3598 llvm::APSInt V(InitVal);
3599 V.trunc(IntWidth);
3600 V.extend(InitVal.getBitWidth());
3601 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003602 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3603 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003604 }
Chris Lattner206754a2007-08-28 06:15:15 +00003605
3606 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003607 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003608 NumPositiveBits = std::max(NumPositiveBits,
3609 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003610 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003611 NumNegativeBits = std::max(NumNegativeBits,
3612 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003613
Chris Lattner206754a2007-08-28 06:15:15 +00003614 // Keep track of whether every enum element has type int (very commmon).
3615 if (AllElementsInt)
3616 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003617 }
3618
Chris Lattner206754a2007-08-28 06:15:15 +00003619 // Figure out the type that should be used for this enum.
3620 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3621 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003622 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003623
3624 if (NumNegativeBits) {
3625 // If there is a negative value, figure out the smallest integer type (of
3626 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003627 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003628 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003629 BestWidth = IntWidth;
3630 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003631 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003632
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003633 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003634 BestType = Context.LongTy;
3635 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003636 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003637
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003638 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003639 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3640 BestType = Context.LongLongTy;
3641 }
3642 }
3643 } else {
3644 // If there is no negative value, figure out which of uint, ulong, ulonglong
3645 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003646 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003647 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003648 BestWidth = IntWidth;
3649 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003650 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003651 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003652 } else {
3653 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003654 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003655 "How could an initializer get larger than ULL?");
3656 BestType = Context.UnsignedLongLongTy;
3657 }
3658 }
3659
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003660 // Loop over all of the enumerator constants, changing their types to match
3661 // the type of the enum if needed.
3662 for (unsigned i = 0; i != NumElements; ++i) {
3663 EnumConstantDecl *ECD =
3664 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3665 if (!ECD) continue; // Already issued a diagnostic.
3666
3667 // Standard C says the enumerators have int type, but we allow, as an
3668 // extension, the enumerators to be larger than int size. If each
3669 // enumerator value fits in an int, type it as an int, otherwise type it the
3670 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3671 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003672 if (ECD->getType() == Context.IntTy) {
3673 // Make sure the init value is signed.
3674 llvm::APSInt IV = ECD->getInitVal();
3675 IV.setIsSigned(true);
3676 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003677
3678 if (getLangOptions().CPlusPlus)
3679 // C++ [dcl.enum]p4: Following the closing brace of an
3680 // enum-specifier, each enumerator has the type of its
3681 // enumeration.
3682 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003683 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003684 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003685
3686 // Determine whether the value fits into an int.
3687 llvm::APSInt InitVal = ECD->getInitVal();
3688 bool FitsInInt;
3689 if (InitVal.isUnsigned() || !InitVal.isNegative())
3690 FitsInInt = InitVal.getActiveBits() < IntWidth;
3691 else
3692 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3693
3694 // If it fits into an integer type, force it. Otherwise force it to match
3695 // the enum decl type.
3696 QualType NewTy;
3697 unsigned NewWidth;
3698 bool NewSign;
3699 if (FitsInInt) {
3700 NewTy = Context.IntTy;
3701 NewWidth = IntWidth;
3702 NewSign = true;
3703 } else if (ECD->getType() == BestType) {
3704 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003705 if (getLangOptions().CPlusPlus)
3706 // C++ [dcl.enum]p4: Following the closing brace of an
3707 // enum-specifier, each enumerator has the type of its
3708 // enumeration.
3709 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003710 continue;
3711 } else {
3712 NewTy = BestType;
3713 NewWidth = BestWidth;
3714 NewSign = BestType->isSignedIntegerType();
3715 }
3716
3717 // Adjust the APSInt value.
3718 InitVal.extOrTrunc(NewWidth);
3719 InitVal.setIsSigned(NewSign);
3720 ECD->setInitVal(InitVal);
3721
3722 // Adjust the Expr initializer and type.
Chris Lattner8c6dc7a2009-01-15 19:19:42 +00003723 if (ECD->getInitExpr())
3724 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3725 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003726 if (getLangOptions().CPlusPlus)
3727 // C++ [dcl.enum]p4: Following the closing brace of an
3728 // enum-specifier, each enumerator has the type of its
3729 // enumeration.
3730 ECD->setType(EnumType);
3731 else
3732 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003733 }
Chris Lattner206754a2007-08-28 06:15:15 +00003734
Douglas Gregor8acb7272008-12-11 16:49:14 +00003735 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003736}
3737
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003738Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003739 ExprArg expr) {
3740 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3741
Chris Lattner81db64a2008-03-16 00:16:02 +00003742 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003743}
3744
Douglas Gregorad17e372008-12-16 22:23:02 +00003745
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003746void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3747 ExprTy *alignment, SourceLocation PragmaLoc,
3748 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3749 Expr *Alignment = static_cast<Expr *>(alignment);
3750
3751 // If specified then alignment must be a "small" power of two.
3752 unsigned AlignmentVal = 0;
3753 if (Alignment) {
3754 llvm::APSInt Val;
3755 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3756 !Val.isPowerOf2() ||
3757 Val.getZExtValue() > 16) {
3758 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3759 delete Alignment;
3760 return; // Ignore
3761 }
3762
3763 AlignmentVal = (unsigned) Val.getZExtValue();
3764 }
3765
3766 switch (Kind) {
3767 case Action::PPK_Default: // pack([n])
3768 PackContext.setAlignment(AlignmentVal);
3769 break;
3770
3771 case Action::PPK_Show: // pack(show)
3772 // Show the current alignment, making sure to show the right value
3773 // for the default.
3774 AlignmentVal = PackContext.getAlignment();
3775 // FIXME: This should come from the target.
3776 if (AlignmentVal == 0)
3777 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003778 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003779 break;
3780
3781 case Action::PPK_Push: // pack(push [, id] [, [n])
3782 PackContext.push(Name);
3783 // Set the new alignment if specified.
3784 if (Alignment)
3785 PackContext.setAlignment(AlignmentVal);
3786 break;
3787
3788 case Action::PPK_Pop: // pack(pop [, id] [, n])
3789 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3790 // "#pragma pack(pop, identifier, n) is undefined"
3791 if (Alignment && Name)
3792 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3793
3794 // Do the pop.
3795 if (!PackContext.pop(Name)) {
3796 // If a name was specified then failure indicates the name
3797 // wasn't found. Otherwise failure indicates the stack was
3798 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003799 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3800 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003801
3802 // FIXME: Warn about popping named records as MSVC does.
3803 } else {
3804 // Pop succeeded, set the new alignment if specified.
3805 if (Alignment)
3806 PackContext.setAlignment(AlignmentVal);
3807 }
3808 break;
3809
3810 default:
3811 assert(0 && "Invalid #pragma pack kind.");
3812 }
3813}
3814
3815bool PragmaPackStack::pop(IdentifierInfo *Name) {
3816 if (Stack.empty())
3817 return false;
3818
3819 // If name is empty just pop top.
3820 if (!Name) {
3821 Alignment = Stack.back().first;
3822 Stack.pop_back();
3823 return true;
3824 }
3825
3826 // Otherwise, find the named record.
3827 for (unsigned i = Stack.size(); i != 0; ) {
3828 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003829 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003830 // Found it, pop up to and including this record.
3831 Alignment = Stack[i].first;
3832 Stack.erase(Stack.begin() + i, Stack.end());
3833 return true;
3834 }
3835 }
3836
3837 return false;
3838}