blob: 0b05177dd37e5c2c844e3209d38151acd5d8d579 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-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 Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Douglas Gregor2def4832008-11-17 20:34:05 +000030Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000032 DeclContext *DC = 0;
33 if (SS) {
34 if (SS->isInvalid())
35 return 0;
36 DC = static_cast<DeclContext*>(SS->getScopeRep());
37 }
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000039
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
42 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000044 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000045}
46
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000047DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000049 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000050 if (MD->isOutOfLineDefinition())
51 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052
53 // A C++ inline method is parsed *after* the topmost class it was declared in
54 // is fully parsed (it's "complete").
55 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000056 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000057 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
58 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000060 DC = RD;
61
62 // Return the declaration context of the topmost class the inline method is
63 // declared in.
64 return DC;
65 }
66
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000067 if (isa<ObjCMethodDecl>(DC))
68 return Context.getTranslationUnitDecl();
69
70 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
71 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000072
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000073 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000074}
75
Chris Lattner9fdf9c62008-04-22 18:39:57 +000076void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000078 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000079 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000080}
81
Chris Lattnerb048c982008-04-06 04:47:34 +000082void Sema::PopDeclContext() {
83 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000084 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000085}
86
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000087/// Add this decl to the scope shadowed decl chains.
88void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000089 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000090
91 // C++ [basic.scope]p4:
92 // -- exactly one declaration shall declare a class name or
93 // enumeration name that is not a typedef name and the other
94 // declarations shall all refer to the same object or
95 // enumerator, or all refer to functions and function templates;
96 // in this case the class name or enumeration name is hidden.
97 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
98 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000099 IdentifierResolver::iterator
100 I = IdResolver.begin(TD->getIdentifier(),
101 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000102 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000103 // There is already a declaration with the same name in the same
104 // scope. It must be found before we find the new declaration,
105 // so swap the order on the shadowed declaration chain.
106
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000107 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000108 return;
109 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000110 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
111 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 // We are pushing the name of a function, which might be an
113 // overloaded name.
114 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000115 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 FD->getDeclContext(), false/*LookInParentCtx*/);
117 if (I != IdResolver.end() &&
118 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
119 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
120 // There is already a declaration with the same name in the same
121 // scope. It must be a function or an overloaded function.
122 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
123 if (!Ovl) {
124 // We haven't yet overloaded this function. Take the existing
125 // FunctionDecl and put it into an OverloadedFunctionDecl.
126 Ovl = OverloadedFunctionDecl::Create(Context,
127 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000128 FD->getDeclName());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000129 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
130
131 // Remove the name binding to the existing FunctionDecl...
132 IdResolver.RemoveDecl(*I);
133
134 // ... and put the OverloadedFunctionDecl in its place.
135 IdResolver.AddDecl(Ovl);
136 }
137
138 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
139 // to its list of overloads.
140 Ovl->addOverload(FD);
141
142 return;
143 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000144 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000147}
148
Steve Naroffb216c882007-10-09 22:01:59 +0000149void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000150 if (S->decl_empty()) return;
151 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
154 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000155 Decl *TmpD = static_cast<Decl*>(*I);
156 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000157
158 if (isa<CXXFieldDecl>(TmpD)) continue;
159
160 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
161 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 IdentifierInfo *II = D->getIdentifier();
164 if (!II) continue;
165
Ted Kremeneka89d1972008-09-03 18:03:35 +0000166 // We only want to remove the decls from the identifier decl chains for
167 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000168 if (S->getFnParent() != 0)
169 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000170
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000171 // Chain this decl to the containing DeclContext.
172 D->setNext(CurContext->getDeclChain());
173 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 }
175}
176
Steve Naroffe8043c32008-04-01 23:04:06 +0000177/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
178/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000179ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000180 // The third "scope" argument is 0 since we aren't enabling lazy built-in
181 // creation from this context.
182 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000183
Steve Naroffb327ce02008-04-02 14:35:35 +0000184 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000185}
186
Steve Naroffe8043c32008-04-01 23:04:06 +0000187/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000189Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000190 const DeclContext *LookupCtx,
191 bool enableLazyBuiltinCreation) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000192 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000193 unsigned NS = NSI;
194 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
195 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000196
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000197 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000198 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
199 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 // Scan up the scope chain looking for a decl that matches this identifier
201 // that is in the appropriate namespace. This search should not take long, as
202 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000203 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000204 if ((*I)->getIdentifierNamespace() & NS)
205 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 // If we didn't find a use of this identifier, and if the identifier
208 // corresponds to a compiler builtin, create the decl object for the builtin
209 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000210 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000211 IdentifierInfo *II = Name.getAsIdentifierInfo();
212 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000214 // If this is a builtin on this (or all) targets, create the decl.
215 if (unsigned BuiltinID = II->getBuiltinID())
216 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000218 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000219 // @interface and @compatibility_alias introduce typedef-like names.
220 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000221 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000222 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224 if (IDI != ObjCInterfaceDecls.end())
225 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227 if (I != ObjCAliasDecls.end())
228 return I->second->getClassInterface();
229 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 }
231 return 0;
232}
233
Chris Lattner95e2c712008-05-05 22:18:14 +0000234void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000235 if (!Context.getBuiltinVaListType().isNull())
236 return;
237
238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 Builtin::ID BID = (Builtin::ID)bid;
249
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000250 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000251 InitBuiltinVaListType();
252
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000254 FunctionDecl *New = FunctionDecl::Create(Context,
255 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000256 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000257 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258
Chris Lattner95e2c712008-05-05 22:18:14 +0000259 // Create Decl objects for each parameter, adding them to the
260 // FunctionDecl.
261 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262 llvm::SmallVector<ParmVarDecl*, 16> Params;
263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265 FT->getArgType(i), VarDecl::None, 0,
266 0));
267 New->setParams(&Params[0], Params.size());
268 }
269
270
271
Chris Lattner7f925cc2008-04-11 07:00:53 +0000272 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000273 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 return New;
275}
276
Sebastian Redlc42e1182008-11-11 11:37:55 +0000277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000281 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000282 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000283 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000284 0, Global, /*enableLazyBuiltinCreation=*/false);
285 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
286 }
287 return StdNamespace;
288}
289
Reid Spencer5f016e22007-07-11 17:01:13 +0000290/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
291/// and scope as a previous declaration 'Old'. Figure out how to resolve this
292/// situation, merging decls or emitting diagnostics as appropriate.
293///
Steve Naroffe8043c32008-04-01 23:04:06 +0000294TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000295 // Allow multiple definitions for ObjC built-in typedefs.
296 // FIXME: Verify the underlying types are equivalent!
297 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000298 const IdentifierInfo *TypeID = New->getIdentifier();
299 switch (TypeID->getLength()) {
300 default: break;
301 case 2:
302 if (!TypeID->isStr("id"))
303 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000304 Context.setObjCIdType(New);
305 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000306 case 5:
307 if (!TypeID->isStr("Class"))
308 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000309 Context.setObjCClassType(New);
310 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000311 case 3:
312 if (!TypeID->isStr("SEL"))
313 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000314 Context.setObjCSelType(New);
315 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000316 case 8:
317 if (!TypeID->isStr("Protocol"))
318 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000319 Context.setObjCProtoType(New->getUnderlyingType());
320 return New;
321 }
322 // Fall through - the typedef name was not a builtin type.
323 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // Verify the old decl was also a typedef.
325 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
326 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000327 Diag(New->getLocation(), diag::err_redefinition_different_kind)
328 << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 Diag(OldD->getLocation(), diag::err_previous_definition);
330 return New;
331 }
332
Chris Lattner99cb9972008-07-25 18:44:27 +0000333 // If the typedef types are not identical, reject them in all languages and
334 // with any extensions enabled.
335 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
336 Context.getCanonicalType(Old->getUnderlyingType()) !=
337 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000338 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
339 << New->getUnderlyingType().getAsString()
340 << Old->getUnderlyingType().getAsString();
Chris Lattner99cb9972008-07-25 18:44:27 +0000341 Diag(Old->getLocation(), diag::err_previous_definition);
342 return Old;
343 }
344
Eli Friedman54ecfce2008-06-11 06:20:39 +0000345 if (getLangOptions().Microsoft) return New;
346
Douglas Gregorbbe27432008-11-21 16:29:06 +0000347 // C++ [dcl.typedef]p2:
348 // In a given non-class scope, a typedef specifier can be used to
349 // redefine the name of any type declared in that scope to refer
350 // to the type to which it already refers.
351 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
352 return New;
353
354 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000355 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
356 // *either* declaration is in a system header. The code below implements
357 // this adhoc compatibility rule. FIXME: The following code will not
358 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000359 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
360 SourceManager &SrcMgr = Context.getSourceManager();
361 if (SrcMgr.isInSystemHeader(Old->getLocation()))
362 return New;
363 if (SrcMgr.isInSystemHeader(New->getLocation()))
364 return New;
365 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000366
Chris Lattner5dc266a2008-11-20 06:13:02 +0000367 Diag(New->getLocation(), diag::err_redefinition) << New->getName();
Ted Kremenek2d05c082008-05-23 21:28:18 +0000368 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 return New;
370}
371
Chris Lattner6b6b5372008-06-26 18:38:35 +0000372/// DeclhasAttr - returns true if decl Declaration already has the target
373/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000374static bool DeclHasAttr(const Decl *decl, const Attr *target) {
375 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
376 if (attr->getKind() == target->getKind())
377 return true;
378
379 return false;
380}
381
382/// MergeAttributes - append attributes from the Old decl to the New one.
383static void MergeAttributes(Decl *New, Decl *Old) {
384 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
385
Chris Lattnerddee4232008-03-03 03:28:21 +0000386 while (attr) {
387 tmp = attr;
388 attr = attr->getNext();
389
390 if (!DeclHasAttr(New, tmp)) {
391 New->addAttr(tmp);
392 } else {
393 tmp->setNext(0);
394 delete(tmp);
395 }
396 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000397
398 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000399}
400
Chris Lattner04421082008-04-08 04:40:51 +0000401/// MergeFunctionDecl - We just parsed a function 'New' from
402/// declarator D which has the same name and scope as a previous
403/// declaration 'Old'. Figure out how to resolve this situation,
404/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000405/// Redeclaration will be set true if this New is a redeclaration OldD.
406///
407/// In C++, New and Old must be declarations that are not
408/// overloaded. Use IsOverload to determine whether New and Old are
409/// overloaded, and to select the Old declaration that New should be
410/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000411FunctionDecl *
412Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413 assert(!isa<OverloadedFunctionDecl>(OldD) &&
414 "Cannot merge with an overloaded function declaration");
415
Douglas Gregorf0097952008-04-21 02:02:58 +0000416 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 // Verify the old decl was also a function.
418 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
419 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000420 Diag(New->getLocation(), diag::err_redefinition_different_kind)
421 << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 Diag(OldD->getLocation(), diag::err_previous_definition);
423 return New;
424 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000425
426 // Determine whether the previous declaration was a definition,
427 // implicit declaration, or a declaration.
428 diag::kind PrevDiag;
429 if (Old->isThisDeclarationADefinition())
430 PrevDiag = diag::err_previous_definition;
431 else if (Old->isImplicit())
432 PrevDiag = diag::err_previous_implicit_declaration;
433 else
434 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000435
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000436 QualType OldQType = Context.getCanonicalType(Old->getType());
437 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000438
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000439 if (getLangOptions().CPlusPlus) {
440 // (C++98 13.1p2):
441 // Certain function declarations cannot be overloaded:
442 // -- Function declarations that differ only in the return type
443 // cannot be overloaded.
444 QualType OldReturnType
445 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
446 QualType NewReturnType
447 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
448 if (OldReturnType != NewReturnType) {
449 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
450 Diag(Old->getLocation(), PrevDiag);
451 return New;
452 }
453
454 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
455 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
456 if (OldMethod && NewMethod) {
457 // -- Member function declarations with the same name and the
458 // same parameter types cannot be overloaded if any of them
459 // is a static member function declaration.
460 if (OldMethod->isStatic() || NewMethod->isStatic()) {
461 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
462 Diag(Old->getLocation(), PrevDiag);
463 return New;
464 }
465 }
466
467 // (C++98 8.3.5p3):
468 // All declarations for a function shall agree exactly in both the
469 // return type and the parameter-type-list.
470 if (OldQType == NewQType) {
471 // We have a redeclaration.
472 MergeAttributes(New, Old);
473 Redeclaration = true;
474 return MergeCXXFunctionDecl(New, Old);
475 }
476
477 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000478 }
Chris Lattner04421082008-04-08 04:40:51 +0000479
480 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000481 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000482 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000483 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000484 MergeAttributes(New, Old);
485 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000486 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000487 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000488
Steve Naroff837618c2008-01-16 15:01:34 +0000489 // A function that has already been declared has been redeclared or defined
490 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
493 // TODO: This is totally simplistic. It should handle merging functions
494 // together etc, merging extern int X; int X; ...
Chris Lattner5dc266a2008-11-20 06:13:02 +0000495 Diag(New->getLocation(), diag::err_conflicting_types) << New->getName();
Steve Naroff837618c2008-01-16 15:01:34 +0000496 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 return New;
498}
499
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000500/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000501static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000502 if (VD->isFileVarDecl())
503 return (!VD->getInit() &&
504 (VD->getStorageClass() == VarDecl::None ||
505 VD->getStorageClass() == VarDecl::Static));
506 return false;
507}
508
509/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
510/// when dealing with C "tentative" external object definitions (C99 6.9.2).
511void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
512 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000513 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000514
515 for (IdentifierResolver::iterator
516 I = IdResolver.begin(VD->getIdentifier(),
517 VD->getDeclContext(), false/*LookInParentCtx*/),
518 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000519 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000520 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
521
Steve Narofff855e6f2008-08-10 15:20:13 +0000522 // Handle the following case:
523 // int a[10];
524 // int a[]; - the code below makes sure we set the correct type.
525 // int a[11]; - this is an error, size isn't 10.
526 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
527 OldDecl->getType()->isConstantArrayType())
528 VD->setType(OldDecl->getType());
529
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000530 // Check for "tentative" definitions. We can't accomplish this in
531 // MergeVarDecl since the initializer hasn't been attached.
532 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
533 continue;
534
535 // Handle __private_extern__ just like extern.
536 if (OldDecl->getStorageClass() != VarDecl::Extern &&
537 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
538 VD->getStorageClass() != VarDecl::Extern &&
539 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000540 Diag(VD->getLocation(), diag::err_redefinition) << VD->getName();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000541 Diag(OldDecl->getLocation(), diag::err_previous_definition);
542 }
543 }
544 }
545}
546
Reid Spencer5f016e22007-07-11 17:01:13 +0000547/// MergeVarDecl - We just parsed a variable 'New' which has the same name
548/// and scope as a previous declaration 'Old'. Figure out how to resolve this
549/// situation, merging decls or emitting diagnostics as appropriate.
550///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000551/// Tentative definition rules (C99 6.9.2p2) are checked by
552/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
553/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000554///
Steve Naroffe8043c32008-04-01 23:04:06 +0000555VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 // Verify the old decl was also a variable.
557 VarDecl *Old = dyn_cast<VarDecl>(OldD);
558 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000559 Diag(New->getLocation(), diag::err_redefinition_different_kind)
560 << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 Diag(OldD->getLocation(), diag::err_previous_definition);
562 return New;
563 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000564
565 MergeAttributes(New, Old);
566
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000568 QualType OldCType = Context.getCanonicalType(Old->getType());
569 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000570 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000571 Diag(New->getLocation(), diag::err_redefinition) << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 Diag(Old->getLocation(), diag::err_previous_definition);
573 return New;
574 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000575 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
576 if (New->getStorageClass() == VarDecl::Static &&
577 (Old->getStorageClass() == VarDecl::None ||
578 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000579 Diag(New->getLocation(), diag::err_static_non_static) << New->getName();
Steve Naroffb7b032e2008-01-30 00:44:01 +0000580 Diag(Old->getLocation(), diag::err_previous_definition);
581 return New;
582 }
583 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
584 if (New->getStorageClass() != VarDecl::Static &&
585 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000586 Diag(New->getLocation(), diag::err_non_static_static) << New->getName();
Steve Naroffb7b032e2008-01-30 00:44:01 +0000587 Diag(Old->getLocation(), diag::err_previous_definition);
588 return New;
589 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000590 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
591 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000592 Diag(New->getLocation(), diag::err_redefinition) << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000593 Diag(Old->getLocation(), diag::err_previous_definition);
594 }
595 return New;
596}
597
Chris Lattner04421082008-04-08 04:40:51 +0000598/// CheckParmsForFunctionDef - Check that the parameters of the given
599/// function are appropriate for the definition of a function. This
600/// takes care of any checks that cannot be performed on the
601/// declaration itself, e.g., that the types of each of the function
602/// parameters are complete.
603bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
604 bool HasInvalidParm = false;
605 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
606 ParmVarDecl *Param = FD->getParamDecl(p);
607
608 // C99 6.7.5.3p4: the parameters in a parameter type list in a
609 // function declarator that is part of a function definition of
610 // that function shall not have incomplete type.
611 if (Param->getType()->isIncompleteType() &&
612 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000613 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
614 << Param->getType().getAsString();
Chris Lattner04421082008-04-08 04:40:51 +0000615 Param->setInvalidDecl();
616 HasInvalidParm = true;
617 }
618 }
619
620 return HasInvalidParm;
621}
622
Reid Spencer5f016e22007-07-11 17:01:13 +0000623/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
624/// no declarator (e.g. "struct foo;") is parsed.
625Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
626 // TODO: emit error on 'int;' or 'const enum foo;'.
627 // TODO: emit error on 'typedef int;'
628 // if (!DS.isMissingDeclaratorOk()) Diag(...);
629
Steve Naroff92199282007-11-17 21:37:36 +0000630 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000631}
632
Steve Naroffd0091aa2008-01-10 22:15:12 +0000633bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000634 // Get the type before calling CheckSingleAssignmentConstraints(), since
635 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000636 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000637
Chris Lattner5cf216b2008-01-04 18:04:52 +0000638 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
639 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
640 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000641}
642
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000643bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000644 const ArrayType *AT = Context.getAsArrayType(DeclT);
645
646 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000647 // C99 6.7.8p14. We have an array of character type with unknown size
648 // being initialized to a string literal.
649 llvm::APSInt ConstVal(32);
650 ConstVal = strLiteral->getByteLength() + 1;
651 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000652 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000653 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000654 } else {
655 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000656 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000657 // FIXME: Avoid truncation for 64-bit length strings.
658 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000659 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000660 diag::warn_initializer_string_for_char_array_too_long)
661 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000662 }
663 // Set type from "char *" to "constant array of char".
664 strLiteral->setType(DeclT);
665 // For now, we always return false (meaning success).
666 return false;
667}
668
669StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000670 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000671 if (AT && AT->getElementType()->isCharType()) {
672 return dyn_cast<StringLiteral>(Init);
673 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000674 return 0;
675}
676
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000677bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
678 SourceLocation InitLoc,
679 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000680 // C++ [dcl.init.ref]p1:
681 // A variable declared to be a T&, that is “reference to type T”
682 // (8.3.2), shall be initialized by an object, or function, of
683 // type T or by an object that can be converted into a T.
684 if (DeclType->isReferenceType())
685 return CheckReferenceInit(Init, DeclType);
686
Steve Naroffca107302008-01-21 23:53:58 +0000687 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
688 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000689 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000690 return Diag(InitLoc, diag::err_variable_object_no_init)
691 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000692
Steve Naroff2fdc3742007-12-10 22:44:33 +0000693 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
694 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000695 // FIXME: Handle wide strings
696 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
697 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000698
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000699 // C++ [dcl.init]p14:
700 // -- If the destination type is a (possibly cv-qualified) class
701 // type:
702 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
703 QualType DeclTypeC = Context.getCanonicalType(DeclType);
704 QualType InitTypeC = Context.getCanonicalType(Init->getType());
705
706 // -- If the initialization is direct-initialization, or if it is
707 // copy-initialization where the cv-unqualified version of the
708 // source type is the same class as, or a derived class of, the
709 // class of the destination, constructors are considered.
710 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
711 IsDerivedFrom(InitTypeC, DeclTypeC)) {
712 CXXConstructorDecl *Constructor
713 = PerformInitializationByConstructor(DeclType, &Init, 1,
714 InitLoc, Init->getSourceRange(),
715 InitEntity, IK_Copy);
716 return Constructor == 0;
717 }
718
719 // -- Otherwise (i.e., for the remaining copy-initialization
720 // cases), user-defined conversion sequences that can
721 // convert from the source type to the destination type or
722 // (when a conversion function is used) to a derived class
723 // thereof are enumerated as described in 13.3.1.4, and the
724 // best one is chosen through overload resolution
725 // (13.3). If the conversion cannot be done or is
726 // ambiguous, the initialization is ill-formed. The
727 // function selected is called with the initializer
728 // expression as its argument; if the function is a
729 // constructor, the call initializes a temporary of the
730 // destination type.
731 // FIXME: We're pretending to do copy elision here; return to
732 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000733 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000734 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000735
736 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
737 << DeclType.getAsString() << InitEntity << "initializing"
738 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000739 }
740
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000741 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000742 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000743 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
744 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000745
Steve Naroffd0091aa2008-01-10 22:15:12 +0000746 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000747 } else if (getLangOptions().CPlusPlus) {
748 // C++ [dcl.init]p14:
749 // [...] If the class is an aggregate (8.5.1), and the initializer
750 // is a brace-enclosed list, see 8.5.1.
751 //
752 // Note: 8.5.1 is handled below; here, we diagnose the case where
753 // we have an initializer list and a destination type that is not
754 // an aggregate.
755 // FIXME: In C++0x, this is yet another form of initialization.
756 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
757 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
758 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000759 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
760 << DeclType.getAsString() << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000761 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000762 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000763
Steve Naroff0cca7492008-05-01 22:18:59 +0000764 InitListChecker CheckInitList(this, InitList, DeclType);
765 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000766}
767
Douglas Gregor10bd3682008-11-17 22:58:34 +0000768/// GetNameForDeclarator - Determine the full declaration name for the
769/// given Declarator.
770DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
771 switch (D.getKind()) {
772 case Declarator::DK_Abstract:
773 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
774 return DeclarationName();
775
776 case Declarator::DK_Normal:
777 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
778 return DeclarationName(D.getIdentifier());
779
780 case Declarator::DK_Constructor: {
781 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
782 Ty = Context.getCanonicalType(Ty);
783 return Context.DeclarationNames.getCXXConstructorName(Ty);
784 }
785
786 case Declarator::DK_Destructor: {
787 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
788 Ty = Context.getCanonicalType(Ty);
789 return Context.DeclarationNames.getCXXDestructorName(Ty);
790 }
791
792 case Declarator::DK_Conversion: {
793 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
794 Ty = Context.getCanonicalType(Ty);
795 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
796 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000797
798 case Declarator::DK_Operator:
799 assert(D.getIdentifier() == 0 && "operator names have no identifier");
800 return Context.DeclarationNames.getCXXOperatorName(
801 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000802 }
803
804 assert(false && "Unknown name kind");
805 return DeclarationName();
806}
807
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000808Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000809Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000810 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000811 DeclarationName Name = GetNameForDeclarator(D);
812
Chris Lattnere80a59c2007-07-25 00:24:17 +0000813 // All of these full declarators require an identifier. If it doesn't have
814 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000815 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000816 if (!D.getInvalidType()) // Reject this if we think it is valid.
817 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000818 diag::err_declarator_need_ident)
819 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000820 return 0;
821 }
822
Chris Lattner31e05722007-08-26 06:24:45 +0000823 // The scope passed in may not be a decl scope. Zip up the scope tree until
824 // we find one that is.
825 while ((S->getFlags() & Scope::DeclScope) == 0)
826 S = S->getParent();
827
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000828 DeclContext *DC;
829 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000830 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000831 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000832
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000833 // See if this is a redefinition of a variable in the same scope.
834 if (!D.getCXXScopeSpec().isSet()) {
835 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000836 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000837 } else { // Something like "int foo::x;"
838 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000839 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000840
841 // C++ 7.3.1.2p2:
842 // Members (including explicit specializations of templates) of a named
843 // namespace can also be defined outside that namespace by explicit
844 // qualification of the name being defined, provided that the entity being
845 // defined was already declared in the namespace and the definition appears
846 // after the point of declaration in a namespace that encloses the
847 // declarations namespace.
848 //
849 if (PrevDecl == 0) {
850 // No previous declaration in the qualifying scope.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000851 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
852 << Name.getAsString() << D.getCXXScopeSpec().getRange();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000853 } else if (!CurContext->Encloses(DC)) {
854 // The qualifying scope doesn't enclose the original declaration.
855 // Emit diagnostic based on current scope.
856 SourceLocation L = D.getIdentifierLoc();
857 SourceRange R = D.getCXXScopeSpec().getRange();
858 if (isa<FunctionDecl>(CurContext)) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000859 Diag(L, diag::err_invalid_declarator_in_function)
860 << Name.getAsString() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000861 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000862 Diag(L, diag::err_invalid_declarator_scope)
863 << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000864 }
865 }
866 }
867
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000868 // In C++, the previous declaration we find might be a tag type
869 // (class or enum). In this case, the new declaration will hide the
870 // tag type.
871 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
872 PrevDecl = 0;
873
Chris Lattner41af0932007-11-14 06:34:38 +0000874 QualType R = GetTypeForDeclarator(D, S);
875 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
876
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000878 // Check that there are no default arguments (C++ only).
879 if (getLangOptions().CPlusPlus)
880 CheckExtraCXXDefaultArguments(D);
881
Chris Lattner41af0932007-11-14 06:34:38 +0000882 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 if (!NewTD) return 0;
884
885 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000886 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000887 // Merge the decl with the existing one if appropriate. If the decl is
888 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000889 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
891 if (NewTD == 0) return 0;
892 }
893 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000894 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 // C99 6.7.7p2: If a typedef name specifies a variably modified type
896 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000897 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
898 // FIXME: Diagnostic needs to be fixed.
899 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000900 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 }
902 }
Chris Lattner41af0932007-11-14 06:34:38 +0000903 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000904 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 switch (D.getDeclSpec().getStorageClassSpec()) {
906 default: assert(0 && "Unknown storage class!");
907 case DeclSpec::SCS_auto:
908 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +0000909 case DeclSpec::SCS_mutable:
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000910 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func)
911 << R.getAsString();
Steve Naroff5912a352007-08-28 20:14:24 +0000912 InvalidDecl = true;
913 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
915 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
916 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000917 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 }
919
Chris Lattnera98e58d2008-03-15 21:24:04 +0000920 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000921 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000922 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
923
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000924 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000925 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000926 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000927 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000928 "Constructors can only be declared in a member context");
929
Douglas Gregor42a552f2008-11-05 20:51:48 +0000930 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000931
932 // Create the new declaration
933 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000934 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000935 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +0000936 isExplicit, isInline,
937 /*isImplicitlyDeclared=*/false);
938
Douglas Gregor42a552f2008-11-05 20:51:48 +0000939 if (isInvalidDecl)
940 NewFD->setInvalidDecl();
941 } else if (D.getKind() == Declarator::DK_Destructor) {
942 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000943 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000944 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000945
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000946 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000947 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000948 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000949 isInline,
950 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000951
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000952 if (isInvalidDecl)
953 NewFD->setInvalidDecl();
954 } else {
955 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
956 // Create a FunctionDecl to satisfy the function definition parsing
957 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000958 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000959 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000960 // FIXME: Move to DeclGroup...
961 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000962 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000963 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000964 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000965 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000966 Diag(D.getIdentifierLoc(),
967 diag::err_conv_function_not_member);
968 return 0;
969 } else {
970 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
971
972 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000973 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000974 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000975 isInline, isExplicit);
976
977 if (isInvalidDecl)
978 NewFD->setInvalidDecl();
979 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000980 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000981 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000982 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000983 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000984 (SC == FunctionDecl::Static), isInline,
985 LastDeclarator);
986 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000987 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000988 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000989 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000990 // FIXME: Move to DeclGroup...
991 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000992 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000993 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000994 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000995
Daniel Dunbara80f8742008-08-05 01:35:17 +0000996 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000997 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000998 // The parser guarantees this is a string.
999 StringLiteral *SE = cast<StringLiteral>(E);
1000 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1001 SE->getByteLength())));
1002 }
1003
Chris Lattner04421082008-04-08 04:40:51 +00001004 // Copy the parameter declarations from the declarator D to
1005 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001006 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001007 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1008
1009 // Create Decl objects for each parameter, adding them to the
1010 // FunctionDecl.
1011 llvm::SmallVector<ParmVarDecl*, 16> Params;
1012
1013 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1014 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001015 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001016 // We let through "const void" here because Sema::GetTypeForDeclarator
1017 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001018 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1019 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001020 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1021 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001022 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1023
Chris Lattnerdef026a2008-04-10 02:26:16 +00001024 // In C++, the empty parameter-type-list must be spelled "void"; a
1025 // typedef of void is not permitted.
1026 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001027 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001028 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1029 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001030 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001031 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1032 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1033 }
1034
1035 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001036 } else if (R->getAsTypedefType()) {
1037 // When we're declaring a function with a typedef, as in the
1038 // following example, we'll need to synthesize (unnamed)
1039 // parameters for use in the declaration.
1040 //
1041 // @code
1042 // typedef void fn(int);
1043 // fn f;
1044 // @endcode
1045 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1046 if (!FT) {
1047 // This is a typedef of a function with no prototype, so we
1048 // don't need to do anything.
1049 } else if ((FT->getNumArgs() == 0) ||
1050 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1051 FT->getArgType(0)->isVoidType())) {
1052 // This is a zero-argument function. We don't need to do anything.
1053 } else {
1054 // Synthesize a parameter for each argument type.
1055 llvm::SmallVector<ParmVarDecl*, 16> Params;
1056 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1057 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001058 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001059 SourceLocation(), 0,
1060 *ArgType, VarDecl::None,
1061 0, 0));
1062 }
1063
1064 NewFD->setParams(&Params[0], Params.size());
1065 }
Chris Lattner04421082008-04-08 04:40:51 +00001066 }
1067
Douglas Gregor42a552f2008-11-05 20:51:48 +00001068 // C++ constructors and destructors are handled by separate
1069 // routines, since they don't require any declaration merging (C++
1070 // [class.mfct]p2) and they aren't ever pushed into scope, because
1071 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1072 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1073 return ActOnConstructorDeclarator(Constructor);
1074 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1075 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001076
1077 // Extra checking for conversion functions, including recording
1078 // the conversion function in its class.
1079 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1080 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001081
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001082 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1083 if (NewFD->isOverloadedOperator() &&
1084 CheckOverloadedOperatorDeclaration(NewFD))
1085 NewFD->setInvalidDecl();
1086
Steve Naroffffce4d52008-01-09 23:34:55 +00001087 // Merge the decl with the existing one if appropriate. Since C functions
1088 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001089 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001090 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001091 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092
1093 // If C++, determine whether NewFD is an overload of PrevDecl or
1094 // a declaration that requires merging. If it's an overload,
1095 // there's no more work to do here; we'll just add the new
1096 // function to the scope.
1097 OverloadedFunctionDecl::function_iterator MatchedDecl;
1098 if (!getLangOptions().CPlusPlus ||
1099 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1100 Decl *OldDecl = PrevDecl;
1101
1102 // If PrevDecl was an overloaded function, extract the
1103 // FunctionDecl that matched.
1104 if (isa<OverloadedFunctionDecl>(PrevDecl))
1105 OldDecl = *MatchedDecl;
1106
1107 // NewFD and PrevDecl represent declarations that need to be
1108 // merged.
1109 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1110
1111 if (NewFD == 0) return 0;
1112 if (Redeclaration) {
1113 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1114
1115 if (OldDecl == PrevDecl) {
1116 // Remove the name binding for the previous
1117 // declaration. We'll add the binding back later, but then
1118 // it will refer to the new declaration (which will
1119 // contain more information).
1120 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1121 } else {
1122 // We need to update the OverloadedFunctionDecl with the
1123 // latest declaration of this function, so that name
1124 // lookup will always refer to the latest declaration of
1125 // this function.
1126 *MatchedDecl = NewFD;
1127
1128 // Add the redeclaration to the current scope, since we'll
1129 // be skipping PushOnScopeChains.
1130 S->AddDecl(NewFD);
1131
1132 return NewFD;
1133 }
1134 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001135 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 }
1137 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001138
1139 // In C++, check default arguments now that we have merged decls.
1140 if (getLangOptions().CPlusPlus)
1141 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001142 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001143 // Check that there are no default arguments (C++ only).
1144 if (getLangOptions().CPlusPlus)
1145 CheckExtraCXXDefaultArguments(D);
1146
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001147 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001148 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1149 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001150 InvalidDecl = true;
1151 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001152
1153 VarDecl *NewVD;
1154 VarDecl::StorageClass SC;
1155 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001156 default: assert(0 && "Unknown storage class!");
1157 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1158 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1159 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1160 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1161 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1162 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001163 case DeclSpec::SCS_mutable:
1164 // mutable can only appear on non-static class members, so it's always
1165 // an error here
1166 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1167 InvalidDecl = true;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001168 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001169 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001170
1171 IdentifierInfo *II = Name.getAsIdentifierInfo();
1172 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001173 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1174 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001175 return 0;
1176 }
1177
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001178 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001179 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1180 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001181 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001182 D.getIdentifierLoc(), II,
1183 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001184 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001185 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001186 if (S->getFnParent() == 0) {
1187 // C99 6.9p2: The storage-class specifiers auto and register shall not
1188 // appear in the declaration specifiers in an external declaration.
1189 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001190 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope)
1191 << R.getAsString();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001192 InvalidDecl = true;
1193 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001194 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001195 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1196 II, R, SC, LastDeclarator,
1197 // FIXME: Move to DeclGroup...
1198 D.getDeclSpec().getSourceRange().getBegin());
1199 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001200 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001202 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001203
Daniel Dunbara735ad82008-08-06 00:03:29 +00001204 // Handle GNU asm-label extension (encoded as an attribute).
1205 if (Expr *E = (Expr*) D.getAsmLabel()) {
1206 // The parser guarantees this is a string.
1207 StringLiteral *SE = cast<StringLiteral>(E);
1208 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1209 SE->getByteLength())));
1210 }
1211
Nate Begemanc8e89a82008-03-14 18:07:10 +00001212 // Emit an error if an address space was applied to decl with local storage.
1213 // This includes arrays of objects with address space qualifiers, but not
1214 // automatic variables that point to other address spaces.
1215 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001216 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1217 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1218 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001219 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001220 // Merge the decl with the existing one if appropriate. If the decl is
1221 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001222 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 NewVD = MergeVarDecl(NewVD, PrevDecl);
1224 if (NewVD == 0) return 0;
1225 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 New = NewVD;
1227 }
1228
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001229 // Set the lexical context. If the declarator has a C++ scope specifier, the
1230 // lexical context will be different from the semantic context.
1231 New->setLexicalDeclContext(CurContext);
1232
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001234 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001235 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001236 // If any semantic error occurred, mark the decl as invalid.
1237 if (D.getInvalidType() || InvalidDecl)
1238 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001239
1240 return New;
1241}
1242
Steve Naroff6594a702008-10-27 11:34:16 +00001243void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001244 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1245 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001246}
1247
Eli Friedmanc594b322008-05-20 13:48:25 +00001248bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1249 switch (Init->getStmtClass()) {
1250 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001251 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001252 return true;
1253 case Expr::ParenExprClass: {
1254 const ParenExpr* PE = cast<ParenExpr>(Init);
1255 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1256 }
1257 case Expr::CompoundLiteralExprClass:
1258 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1259 case Expr::DeclRefExprClass: {
1260 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001261 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1262 if (VD->hasGlobalStorage())
1263 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001264 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001265 return true;
1266 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001267 if (isa<FunctionDecl>(D))
1268 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001269 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001270 return true;
1271 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001272 case Expr::MemberExprClass: {
1273 const MemberExpr *M = cast<MemberExpr>(Init);
1274 if (M->isArrow())
1275 return CheckAddressConstantExpression(M->getBase());
1276 return CheckAddressConstantExpressionLValue(M->getBase());
1277 }
1278 case Expr::ArraySubscriptExprClass: {
1279 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1280 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1281 return CheckAddressConstantExpression(ASE->getBase()) ||
1282 CheckArithmeticConstantExpression(ASE->getIdx());
1283 }
1284 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001285 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001286 return false;
1287 case Expr::UnaryOperatorClass: {
1288 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1289
1290 // C99 6.6p9
1291 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001292 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001293
Steve Naroff6594a702008-10-27 11:34:16 +00001294 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001295 return true;
1296 }
1297 }
1298}
1299
1300bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1301 switch (Init->getStmtClass()) {
1302 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001303 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001304 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001305 case Expr::ParenExprClass:
1306 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001307 case Expr::StringLiteralClass:
1308 case Expr::ObjCStringLiteralClass:
1309 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001310 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001311 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001312 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1313 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1314 Builtin::BI__builtin___CFStringMakeConstantString)
1315 return false;
1316
Steve Naroff6594a702008-10-27 11:34:16 +00001317 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001318 return true;
1319
Eli Friedmanc594b322008-05-20 13:48:25 +00001320 case Expr::UnaryOperatorClass: {
1321 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1322
1323 // C99 6.6p9
1324 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1325 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1326
1327 if (Exp->getOpcode() == UnaryOperator::Extension)
1328 return CheckAddressConstantExpression(Exp->getSubExpr());
1329
Steve Naroff6594a702008-10-27 11:34:16 +00001330 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001331 return true;
1332 }
1333 case Expr::BinaryOperatorClass: {
1334 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1335 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1336
1337 Expr *PExp = Exp->getLHS();
1338 Expr *IExp = Exp->getRHS();
1339 if (IExp->getType()->isPointerType())
1340 std::swap(PExp, IExp);
1341
1342 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1343 return CheckAddressConstantExpression(PExp) ||
1344 CheckArithmeticConstantExpression(IExp);
1345 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001346 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001347 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001348 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001349 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1350 // Check for implicit promotion
1351 if (SubExpr->getType()->isFunctionType() ||
1352 SubExpr->getType()->isArrayType())
1353 return CheckAddressConstantExpressionLValue(SubExpr);
1354 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001355
1356 // Check for pointer->pointer cast
1357 if (SubExpr->getType()->isPointerType())
1358 return CheckAddressConstantExpression(SubExpr);
1359
Eli Friedmanc3f07642008-08-25 20:46:57 +00001360 if (SubExpr->getType()->isIntegralType()) {
1361 // Check for the special-case of a pointer->int->pointer cast;
1362 // this isn't standard, but some code requires it. See
1363 // PR2720 for an example.
1364 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1365 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1366 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1367 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1368 if (IntWidth >= PointerWidth) {
1369 return CheckAddressConstantExpression(SubCast->getSubExpr());
1370 }
1371 }
1372 }
1373 }
1374 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001375 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001376 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001377
Steve Naroff6594a702008-10-27 11:34:16 +00001378 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001379 return true;
1380 }
1381 case Expr::ConditionalOperatorClass: {
1382 // FIXME: Should we pedwarn here?
1383 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1384 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001385 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001386 return true;
1387 }
1388 if (CheckArithmeticConstantExpression(Exp->getCond()))
1389 return true;
1390 if (Exp->getLHS() &&
1391 CheckAddressConstantExpression(Exp->getLHS()))
1392 return true;
1393 return CheckAddressConstantExpression(Exp->getRHS());
1394 }
1395 case Expr::AddrLabelExprClass:
1396 return false;
1397 }
1398}
1399
Eli Friedman4caf0552008-06-09 05:05:07 +00001400static const Expr* FindExpressionBaseAddress(const Expr* E);
1401
1402static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1403 switch (E->getStmtClass()) {
1404 default:
1405 return E;
1406 case Expr::ParenExprClass: {
1407 const ParenExpr* PE = cast<ParenExpr>(E);
1408 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1409 }
1410 case Expr::MemberExprClass: {
1411 const MemberExpr *M = cast<MemberExpr>(E);
1412 if (M->isArrow())
1413 return FindExpressionBaseAddress(M->getBase());
1414 return FindExpressionBaseAddressLValue(M->getBase());
1415 }
1416 case Expr::ArraySubscriptExprClass: {
1417 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1418 return FindExpressionBaseAddress(ASE->getBase());
1419 }
1420 case Expr::UnaryOperatorClass: {
1421 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1422
1423 if (Exp->getOpcode() == UnaryOperator::Deref)
1424 return FindExpressionBaseAddress(Exp->getSubExpr());
1425
1426 return E;
1427 }
1428 }
1429}
1430
1431static const Expr* FindExpressionBaseAddress(const Expr* E) {
1432 switch (E->getStmtClass()) {
1433 default:
1434 return E;
1435 case Expr::ParenExprClass: {
1436 const ParenExpr* PE = cast<ParenExpr>(E);
1437 return FindExpressionBaseAddress(PE->getSubExpr());
1438 }
1439 case Expr::UnaryOperatorClass: {
1440 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1441
1442 // C99 6.6p9
1443 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1444 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1445
1446 if (Exp->getOpcode() == UnaryOperator::Extension)
1447 return FindExpressionBaseAddress(Exp->getSubExpr());
1448
1449 return E;
1450 }
1451 case Expr::BinaryOperatorClass: {
1452 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1453
1454 Expr *PExp = Exp->getLHS();
1455 Expr *IExp = Exp->getRHS();
1456 if (IExp->getType()->isPointerType())
1457 std::swap(PExp, IExp);
1458
1459 return FindExpressionBaseAddress(PExp);
1460 }
1461 case Expr::ImplicitCastExprClass: {
1462 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1463
1464 // Check for implicit promotion
1465 if (SubExpr->getType()->isFunctionType() ||
1466 SubExpr->getType()->isArrayType())
1467 return FindExpressionBaseAddressLValue(SubExpr);
1468
1469 // Check for pointer->pointer cast
1470 if (SubExpr->getType()->isPointerType())
1471 return FindExpressionBaseAddress(SubExpr);
1472
1473 // We assume that we have an arithmetic expression here;
1474 // if we don't, we'll figure it out later
1475 return 0;
1476 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001477 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001478 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1479
1480 // Check for pointer->pointer cast
1481 if (SubExpr->getType()->isPointerType())
1482 return FindExpressionBaseAddress(SubExpr);
1483
1484 // We assume that we have an arithmetic expression here;
1485 // if we don't, we'll figure it out later
1486 return 0;
1487 }
1488 }
1489}
1490
Eli Friedmanc594b322008-05-20 13:48:25 +00001491bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1492 switch (Init->getStmtClass()) {
1493 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001494 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001495 return true;
1496 case Expr::ParenExprClass: {
1497 const ParenExpr* PE = cast<ParenExpr>(Init);
1498 return CheckArithmeticConstantExpression(PE->getSubExpr());
1499 }
1500 case Expr::FloatingLiteralClass:
1501 case Expr::IntegerLiteralClass:
1502 case Expr::CharacterLiteralClass:
1503 case Expr::ImaginaryLiteralClass:
1504 case Expr::TypesCompatibleExprClass:
1505 case Expr::CXXBoolLiteralExprClass:
1506 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001507 case Expr::CallExprClass:
1508 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001509 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001510
1511 // Allow any constant foldable calls to builtins.
1512 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001513 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001514
Steve Naroff6594a702008-10-27 11:34:16 +00001515 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001516 return true;
1517 }
1518 case Expr::DeclRefExprClass: {
1519 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1520 if (isa<EnumConstantDecl>(D))
1521 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001522 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001523 return true;
1524 }
1525 case Expr::CompoundLiteralExprClass:
1526 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1527 // but vectors are allowed to be magic.
1528 if (Init->getType()->isVectorType())
1529 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001530 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001531 return true;
1532 case Expr::UnaryOperatorClass: {
1533 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1534
1535 switch (Exp->getOpcode()) {
1536 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1537 // See C99 6.6p3.
1538 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001539 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001540 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001541 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001542 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1543 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001544 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001545 return true;
1546 case UnaryOperator::Extension:
1547 case UnaryOperator::LNot:
1548 case UnaryOperator::Plus:
1549 case UnaryOperator::Minus:
1550 case UnaryOperator::Not:
1551 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1552 }
1553 }
Sebastian Redl05189992008-11-11 17:56:53 +00001554 case Expr::SizeOfAlignOfExprClass: {
1555 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001556 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001557 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001558 return false;
1559 // alignof always evaluates to a constant.
1560 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001561 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001562 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001563 return true;
1564 }
1565 return false;
1566 }
1567 case Expr::BinaryOperatorClass: {
1568 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1569
1570 if (Exp->getLHS()->getType()->isArithmeticType() &&
1571 Exp->getRHS()->getType()->isArithmeticType()) {
1572 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1573 CheckArithmeticConstantExpression(Exp->getRHS());
1574 }
1575
Eli Friedman4caf0552008-06-09 05:05:07 +00001576 if (Exp->getLHS()->getType()->isPointerType() &&
1577 Exp->getRHS()->getType()->isPointerType()) {
1578 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1579 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1580
1581 // Only allow a null (constant integer) base; we could
1582 // allow some additional cases if necessary, but this
1583 // is sufficient to cover offsetof-like constructs.
1584 if (!LHSBase && !RHSBase) {
1585 return CheckAddressConstantExpression(Exp->getLHS()) ||
1586 CheckAddressConstantExpression(Exp->getRHS());
1587 }
1588 }
1589
Steve Naroff6594a702008-10-27 11:34:16 +00001590 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001591 return true;
1592 }
1593 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001594 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001595 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001596 if (SubExpr->getType()->isArithmeticType())
1597 return CheckArithmeticConstantExpression(SubExpr);
1598
Eli Friedmanb529d832008-09-02 09:37:00 +00001599 if (SubExpr->getType()->isPointerType()) {
1600 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1601 // If the pointer has a null base, this is an offsetof-like construct
1602 if (!Base)
1603 return CheckAddressConstantExpression(SubExpr);
1604 }
1605
Steve Naroff6594a702008-10-27 11:34:16 +00001606 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001607 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001608 }
1609 case Expr::ConditionalOperatorClass: {
1610 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001611
1612 // If GNU extensions are disabled, we require all operands to be arithmetic
1613 // constant expressions.
1614 if (getLangOptions().NoExtensions) {
1615 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1616 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1617 CheckArithmeticConstantExpression(Exp->getRHS());
1618 }
1619
1620 // Otherwise, we have to emulate some of the behavior of fold here.
1621 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1622 // because it can constant fold things away. To retain compatibility with
1623 // GCC code, we see if we can fold the condition to a constant (which we
1624 // should always be able to do in theory). If so, we only require the
1625 // specified arm of the conditional to be a constant. This is a horrible
1626 // hack, but is require by real world code that uses __builtin_constant_p.
1627 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001628 if (!Exp->getCond()->Evaluate(Val, Context)) {
1629 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001630 // won't be able to either. Use it to emit the diagnostic though.
1631 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001632 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001633 return Res;
1634 }
1635
1636 // Verify that the side following the condition is also a constant.
1637 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1638 if (Val.getInt() == 0)
1639 std::swap(TrueSide, FalseSide);
1640
1641 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001642 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001643
1644 // Okay, the evaluated side evaluates to a constant, so we accept this.
1645 // Check to see if the other side is obviously not a constant. If so,
1646 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001647 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001648 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001649 diag::ext_typecheck_expression_not_constant_but_accepted)
1650 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001651 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001652 }
1653 }
1654}
1655
1656bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001657 Init = Init->IgnoreParens();
1658
Eli Friedmanc594b322008-05-20 13:48:25 +00001659 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1660 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1661 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1662
Nuno Lopes9a979c32008-07-07 16:46:50 +00001663 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1664 return CheckForConstantInitializer(e->getInitializer(), DclT);
1665
Eli Friedmanc594b322008-05-20 13:48:25 +00001666 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1667 unsigned numInits = Exp->getNumInits();
1668 for (unsigned i = 0; i < numInits; i++) {
1669 // FIXME: Need to get the type of the declaration for C++,
1670 // because it could be a reference?
1671 if (CheckForConstantInitializer(Exp->getInit(i),
1672 Exp->getInit(i)->getType()))
1673 return true;
1674 }
1675 return false;
1676 }
1677
1678 if (Init->isNullPointerConstant(Context))
1679 return false;
1680 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001681 QualType InitTy = Context.getCanonicalType(Init->getType())
1682 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001683 if (InitTy == Context.BoolTy) {
1684 // Special handling for pointers implicitly cast to bool;
1685 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1686 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1687 Expr* SubE = ICE->getSubExpr();
1688 if (SubE->getType()->isPointerType() ||
1689 SubE->getType()->isArrayType() ||
1690 SubE->getType()->isFunctionType()) {
1691 return CheckAddressConstantExpression(Init);
1692 }
1693 }
1694 } else if (InitTy->isIntegralType()) {
1695 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001696 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001697 SubE = CE->getSubExpr();
1698 // Special check for pointer cast to int; we allow as an extension
1699 // an address constant cast to an integer if the integer
1700 // is of an appropriate width (this sort of code is apparently used
1701 // in some places).
1702 // FIXME: Add pedwarn?
1703 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1704 if (SubE && (SubE->getType()->isPointerType() ||
1705 SubE->getType()->isArrayType() ||
1706 SubE->getType()->isFunctionType())) {
1707 unsigned IntWidth = Context.getTypeSize(Init->getType());
1708 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1709 if (IntWidth >= PointerWidth)
1710 return CheckAddressConstantExpression(Init);
1711 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001712 }
1713
1714 return CheckArithmeticConstantExpression(Init);
1715 }
1716
1717 if (Init->getType()->isPointerType())
1718 return CheckAddressConstantExpression(Init);
1719
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001720 // An array type at the top level that isn't an init-list must
1721 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001722 if (Init->getType()->isArrayType())
1723 return false;
1724
Nuno Lopes73419bf2008-09-01 18:42:41 +00001725 if (Init->getType()->isFunctionType())
1726 return false;
1727
Steve Naroff8af6a452008-10-02 17:12:56 +00001728 // Allow block exprs at top level.
1729 if (Init->getType()->isBlockPointerType())
1730 return false;
1731
Steve Naroff6594a702008-10-27 11:34:16 +00001732 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001733 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001734}
1735
Steve Naroffbb204692007-09-12 14:07:44 +00001736void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001737 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001738 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001739 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001740
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001741 // If there is no declaration, there was an error parsing it. Just ignore
1742 // the initializer.
1743 if (RealDecl == 0) {
1744 delete Init;
1745 return;
1746 }
Steve Naroffbb204692007-09-12 14:07:44 +00001747
Steve Naroff410e3e22007-09-12 20:13:48 +00001748 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1749 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001750 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1751 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001752 RealDecl->setInvalidDecl();
1753 return;
1754 }
Steve Naroffbb204692007-09-12 14:07:44 +00001755 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001756 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001757 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001758 if (VDecl->isBlockVarDecl()) {
1759 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001760 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001761 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001762 VDecl->setInvalidDecl();
1763 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001764 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1765 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001766 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001767
1768 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1769 if (!getLangOptions().CPlusPlus) {
1770 if (SC == VarDecl::Static) // C99 6.7.8p4.
1771 CheckForConstantInitializer(Init, DclT);
1772 }
Steve Naroffbb204692007-09-12 14:07:44 +00001773 }
Steve Naroff248a7532008-04-15 22:42:06 +00001774 } else if (VDecl->isFileVarDecl()) {
1775 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001776 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001777 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001778 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1779 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001780 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001781
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001782 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1783 if (!getLangOptions().CPlusPlus) {
1784 // C99 6.7.8p4. All file scoped initializers need to be constant.
1785 CheckForConstantInitializer(Init, DclT);
1786 }
Steve Naroffbb204692007-09-12 14:07:44 +00001787 }
1788 // If the type changed, it means we had an incomplete type that was
1789 // completed by the initializer. For example:
1790 // int ary[] = { 1, 3, 5 };
1791 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001792 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001793 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001794 Init->setType(DclT);
1795 }
Steve Naroffbb204692007-09-12 14:07:44 +00001796
1797 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001798 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001799 return;
1800}
1801
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001802void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1803 Decl *RealDecl = static_cast<Decl *>(dcl);
1804
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001805 // If there is no declaration, there was an error parsing it. Just ignore it.
1806 if (RealDecl == 0)
1807 return;
1808
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001809 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1810 QualType Type = Var->getType();
1811 // C++ [dcl.init.ref]p3:
1812 // The initializer can be omitted for a reference only in a
1813 // parameter declaration (8.3.5), in the declaration of a
1814 // function return type, in the declaration of a class member
1815 // within its class declaration (9.2), and where the extern
1816 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001817 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001818 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
1819 << Var->getName() << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00001820 Var->setInvalidDecl();
1821 return;
1822 }
1823
1824 // C++ [dcl.init]p9:
1825 //
1826 // If no initializer is specified for an object, and the object
1827 // is of (possibly cv-qualified) non-POD class type (or array
1828 // thereof), the object shall be default-initialized; if the
1829 // object is of const-qualified type, the underlying class type
1830 // shall have a user-declared default constructor.
1831 if (getLangOptions().CPlusPlus) {
1832 QualType InitType = Type;
1833 if (const ArrayType *Array = Context.getAsArrayType(Type))
1834 InitType = Array->getElementType();
1835 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001836 const CXXConstructorDecl *Constructor
1837 = PerformInitializationByConstructor(InitType, 0, 0,
1838 Var->getLocation(),
1839 SourceRange(Var->getLocation(),
1840 Var->getLocation()),
1841 Var->getName(),
1842 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001843 if (!Constructor)
1844 Var->setInvalidDecl();
1845 }
1846 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001847
Douglas Gregor818ce482008-10-29 13:50:18 +00001848#if 0
1849 // FIXME: Temporarily disabled because we are not properly parsing
1850 // linkage specifications on declarations, e.g.,
1851 //
1852 // extern "C" const CGPoint CGPointerZero;
1853 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001854 // C++ [dcl.init]p9:
1855 //
1856 // If no initializer is specified for an object, and the
1857 // object is of (possibly cv-qualified) non-POD class type (or
1858 // array thereof), the object shall be default-initialized; if
1859 // the object is of const-qualified type, the underlying class
1860 // type shall have a user-declared default
1861 // constructor. Otherwise, if no initializer is specified for
1862 // an object, the object and its subobjects, if any, have an
1863 // indeterminate initial value; if the object or any of its
1864 // subobjects are of const-qualified type, the program is
1865 // ill-formed.
1866 //
1867 // This isn't technically an error in C, so we don't diagnose it.
1868 //
1869 // FIXME: Actually perform the POD/user-defined default
1870 // constructor check.
1871 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001872 Context.getCanonicalType(Type).isConstQualified() &&
1873 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001874 Diag(Var->getLocation(), diag::err_const_var_requires_init)
1875 << Var->getName()
1876 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00001877#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001878 }
1879}
1880
Reid Spencer5f016e22007-07-11 17:01:13 +00001881/// The declarators are chained together backwards, reverse the list.
1882Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1883 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001884 Decl *GroupDecl = static_cast<Decl*>(group);
1885 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001886 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001887
1888 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1889 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001890 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001892 else { // reverse the list.
1893 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001894 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001895 Group->setNextDeclarator(NewGroup);
1896 NewGroup = Group;
1897 Group = Next;
1898 }
1899 }
1900 // Perform semantic analysis that depends on having fully processed both
1901 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001902 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001903 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1904 if (!IDecl)
1905 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001906 QualType T = IDecl->getType();
1907
1908 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1909 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001910 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1911 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001912 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001913 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1914 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001915 }
1916 }
1917 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1918 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001919 if (IDecl->isBlockVarDecl() &&
1920 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001921 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001922 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
1923 << T.getAsString();
Steve Naroffbb204692007-09-12 14:07:44 +00001924 IDecl->setInvalidDecl();
1925 }
1926 }
1927 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1928 // object that has file scope without an initializer, and without a
1929 // storage-class specifier or with the storage-class specifier "static",
1930 // constitutes a tentative definition. Note: A tentative definition with
1931 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001932 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001933 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001934 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1935 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001936 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001937 // C99 6.9.2p3: If the declaration of an identifier for an object is
1938 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1939 // declared type shall not be an incomplete type.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001940 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)
1941 << T.getAsString();
Steve Naroffbb204692007-09-12 14:07:44 +00001942 IDecl->setInvalidDecl();
1943 }
1944 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001945 if (IDecl->isFileVarDecl())
1946 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 }
1948 return NewGroup;
1949}
Steve Naroffe1223f72007-08-28 03:03:08 +00001950
Chris Lattner04421082008-04-08 04:40:51 +00001951/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1952/// to introduce parameters into function prototype scope.
1953Sema::DeclTy *
1954Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001955 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001956 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001957
1958 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001959 VarDecl::StorageClass StorageClass = VarDecl::None;
1960 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1961 StorageClass = VarDecl::Register;
1962 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001963 Diag(DS.getStorageClassSpecLoc(),
1964 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001965 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001966 }
1967 if (DS.isThreadSpecified()) {
1968 Diag(DS.getThreadSpecLoc(),
1969 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001970 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001971 }
1972
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001973 // Check that there are no default arguments inside the type of this
1974 // parameter (C++ only).
1975 if (getLangOptions().CPlusPlus)
1976 CheckExtraCXXDefaultArguments(D);
1977
Chris Lattner04421082008-04-08 04:40:51 +00001978 // In this context, we *do not* check D.getInvalidType(). If the declarator
1979 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1980 // though it will not reflect the user specified type.
1981 QualType parmDeclType = GetTypeForDeclarator(D, S);
1982
1983 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1986 // Can this happen for params? We already checked that they don't conflict
1987 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001988 IdentifierInfo *II = D.getIdentifier();
1989 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1990 if (S->isDeclScope(PrevDecl)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001991 Diag(D.getIdentifierLoc(), diag::err_param_redefinition)
1992 << cast<NamedDecl>(PrevDecl)->getName();
Chris Lattner04421082008-04-08 04:40:51 +00001993
1994 // Recover by removing the name
1995 II = 0;
1996 D.SetIdentifier(0, D.getIdentifierLoc());
1997 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001999
2000 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2001 // Doing the promotion here has a win and a loss. The win is the type for
2002 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2003 // code generator). The loss is the orginal type isn't preserved. For example:
2004 //
2005 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2006 // int blockvardecl[5];
2007 // sizeof(parmvardecl); // size == 4
2008 // sizeof(blockvardecl); // size == 20
2009 // }
2010 //
2011 // For expressions, all implicit conversions are captured using the
2012 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2013 //
2014 // FIXME: If a source translation tool needs to see the original type, then
2015 // we need to consider storing both types (in ParmVarDecl)...
2016 //
Chris Lattnere6327742008-04-02 05:18:44 +00002017 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002018 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002019 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002020 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002021 parmDeclType = Context.getPointerType(parmDeclType);
2022
Chris Lattner04421082008-04-08 04:40:51 +00002023 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2024 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002025 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002026 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002027
Chris Lattner04421082008-04-08 04:40:51 +00002028 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002029 New->setInvalidDecl();
2030
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002031 if (II)
2032 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00002033
Chris Lattner3ff30c82008-06-29 00:02:00 +00002034 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002036
Reid Spencer5f016e22007-07-11 17:01:13 +00002037}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002038
Chris Lattnerb652cea2007-10-09 17:14:05 +00002039Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002040 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2042 "Not a function declarator!");
2043 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002044
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2046 // for a K&R function.
2047 if (!FTI.hasPrototype) {
2048 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002049 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002050 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2051 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 // Implicitly declare the argument as type 'int' for lack of a better
2053 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002054 DeclSpec DS;
2055 const char* PrevSpec; // unused
2056 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2057 PrevSpec);
2058 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2059 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2060 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002061 }
2062 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002064 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002065 }
2066
2067 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002068
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002069 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002070 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002071}
2072
2073Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2074 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002075 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002076
2077 // See if this is a redefinition.
2078 const FunctionDecl *Definition;
2079 if (FD->getBody(Definition)) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002080 Diag(FD->getLocation(), diag::err_redefinition) << FD->getName();
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002081 Diag(Definition->getLocation(), diag::err_previous_definition);
2082 }
2083
Chris Lattnerb048c982008-04-06 04:47:34 +00002084 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002085
2086 // Check the validity of our function parameters
2087 CheckParmsForFunctionDef(FD);
2088
2089 // Introduce our parameters into the function scope
2090 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2091 ParmVarDecl *Param = FD->getParamDecl(p);
2092 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002093 if (Param->getIdentifier())
2094 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 }
Chris Lattner04421082008-04-08 04:40:51 +00002096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 return FD;
2098}
2099
Steve Naroffd6d054d2007-11-11 23:20:51 +00002100Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2101 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002102 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002103 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002104 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002105 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002106 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002107 } else
2108 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002109 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002110 // Verify and clean out per-function state.
2111
2112 // Check goto/label use.
2113 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2114 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2115 // Verify that we have no forward references left. If so, there was a goto
2116 // or address of a label taken, but no definition of it. Label fwd
2117 // definitions are indicated with a null substmt.
2118 if (I->second->getSubStmt() == 0) {
2119 LabelStmt *L = I->second;
2120 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002121 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002122
2123 // At this point, we have gotos that use the bogus label. Stitch it into
2124 // the function body so that they aren't leaked and that the AST is well
2125 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002126 if (Body) {
2127 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2128 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2129 } else {
2130 // The whole function wasn't parsed correctly, just delete this.
2131 delete L;
2132 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
2134 }
2135 LabelMap.clear();
2136
Steve Naroffd6d054d2007-11-11 23:20:51 +00002137 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002138}
2139
Reid Spencer5f016e22007-07-11 17:01:13 +00002140/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2141/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002142ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2143 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002144 // Extension in C99. Legal in C90, but warn about it.
2145 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002146 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002147 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002148 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002149
2150 // FIXME: handle stuff like:
2151 // void foo() { extern float X(); }
2152 // void bar() { X(); } <-- implicit decl for X in another scope.
2153
2154 // Set a Declarator for the implicit definition: int foo();
2155 const char *Dummy;
2156 DeclSpec DS;
2157 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2158 Error = Error; // Silence warning.
2159 assert(!Error && "Error setting up implicit decl!");
2160 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002161 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 D.SetIdentifier(&II, Loc);
2163
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002164 // Insert this function into translation-unit scope.
2165
2166 DeclContext *PrevDC = CurContext;
2167 CurContext = Context.getTranslationUnitDecl();
2168
Steve Naroffe2ef8152008-04-04 14:32:09 +00002169 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002170 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002171 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002172
2173 CurContext = PrevDC;
2174
Steve Naroffe2ef8152008-04-04 14:32:09 +00002175 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002176}
2177
2178
Chris Lattner41af0932007-11-14 06:34:38 +00002179TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002180 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002182 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002183
2184 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002185 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2186 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002187 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002188 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002189 if (D.getInvalidType())
2190 NewTD->setInvalidDecl();
2191 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002192}
2193
Steve Naroff08d92e42007-09-15 18:49:24 +00002194/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002195/// former case, Name will be non-null. In the later case, Name will be null.
2196/// TagType indicates what kind of tag this is. TK indicates whether this is a
2197/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002198Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002199 SourceLocation KWLoc, const CXXScopeSpec &SS,
2200 IdentifierInfo *Name, SourceLocation NameLoc,
2201 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 // If this is a use of an existing tag, it must have a name.
2203 assert((Name != 0 || TK == TK_Definition) &&
2204 "Nameless record must be a definition!");
2205
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002206 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 switch (TagType) {
2208 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002209 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2210 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2211 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2212 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002213 }
2214
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002215 // Two code paths: a new one for structs/unions/classes where we create
2216 // separate decls for forward declarations, and an old (eventually to
2217 // be removed) code path for enums.
2218 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002219 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002220
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002221 DeclContext *DC = CurContext;
2222 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002223
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002224 if (Name && SS.isNotEmpty()) {
2225 // We have a nested-name tag ('struct foo::bar').
2226
2227 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002228 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002229 Name = 0;
2230 goto CreateNewDecl;
2231 }
2232
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002233 DC = static_cast<DeclContext*>(SS.getScopeRep());
2234 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002235 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2236
2237 // A tag 'foo::bar' must already exist.
2238 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002239 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002240 Name = 0;
2241 goto CreateNewDecl;
2242 }
2243 } else {
2244 // If this is a named struct, check to see if there was a previous forward
2245 // declaration or definition.
2246 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2247 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2248 }
2249
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002250 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002251 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2252 "unexpected Decl type");
2253 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002254 // If this is a use of a previous tag, or if the tag is already declared
2255 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002256 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002257 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002258 // Make sure that this wasn't declared as an enum and now used as a
2259 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002260 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002261 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002262 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002263 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002264 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002265 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002266 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002267 // If this is a use or a forward declaration, we're good.
2268 if (TK != TK_Definition)
2269 return PrevDecl;
2270
2271 // Diagnose attempts to redefine a tag.
2272 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002273 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner14943b92008-07-03 03:30:58 +00002274 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2275 // If this is a redefinition, recover by making this struct be
2276 // anonymous, which will make any later references get the previous
2277 // definition.
2278 Name = 0;
2279 } else {
2280 // Okay, this is definition of a previously declared or referenced
2281 // tag. Move the location of the decl to be the definition site.
2282 PrevDecl->setLocation(NameLoc);
2283 return PrevDecl;
2284 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002285 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002286 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002287 // If we get here, this is a definition of a new struct type in a nested
2288 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2289 // type.
2290 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002291 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002292 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002293 // The tag name clashes with a namespace name, issue an error and
2294 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002295 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002296 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2297 Name = 0;
2298 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002299 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002301
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002302 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002303
2304 // If there is an identifier, use the location of the identifier as the
2305 // location of the decl, otherwise use the location of the struct/union
2306 // keyword.
2307 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2308
2309 // Otherwise, if this is the first time we've seen this tag, create the decl.
2310 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002311 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2313 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002314 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 // If this is an undefined enum, warn.
2316 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002317 } else {
2318 // struct/union/class
2319
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2321 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002322 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002323 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002324 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002325 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002326 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002327 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002328
2329 // If this has an identifier, add it to the scope stack.
2330 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002331 // The scope passed in may not be a decl scope. Zip up the scope tree until
2332 // we find one that is.
2333 while ((S->getFlags() & Scope::DeclScope) == 0)
2334 S = S->getParent();
2335
2336 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002337 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002339
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002340 if (Attr)
2341 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002342
2343 // Set the lexical context. If the tag has a C++ scope specifier, the
2344 // lexical context will be different from the semantic context.
2345 New->setLexicalDeclContext(CurContext);
2346
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 return New;
2348}
2349
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002350/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2351/// the logic for enums, we create separate decls for forward declarations.
2352/// This is called by ActOnTag, but eventually will replace its logic.
2353Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002354 SourceLocation KWLoc, const CXXScopeSpec &SS,
2355 IdentifierInfo *Name, SourceLocation NameLoc,
2356 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002357 DeclContext *DC = CurContext;
2358 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002359
2360 if (Name && SS.isNotEmpty()) {
2361 // We have a nested-name tag ('struct foo::bar').
2362
2363 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002364 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002365 Name = 0;
2366 goto CreateNewDecl;
2367 }
2368
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002369 DC = static_cast<DeclContext*>(SS.getScopeRep());
2370 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002371 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2372
2373 // A tag 'foo::bar' must already exist.
2374 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002375 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002376 Name = 0;
2377 goto CreateNewDecl;
2378 }
2379 } else {
2380 // If this is a named struct, check to see if there was a previous forward
2381 // declaration or definition.
2382 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2383 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2384 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002385
2386 if (PrevDecl) {
2387 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2388 "unexpected Decl type");
2389
2390 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2391 // If this is a use of a previous tag, or if the tag is already declared
2392 // in the same scope (so that the definition/declaration completes or
2393 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002394 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002395 // Make sure that this wasn't declared as an enum and now used as a
2396 // struct or something similar.
2397 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002398 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002399 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2400 // Recover by making this an anonymous redefinition.
2401 Name = 0;
2402 PrevDecl = 0;
2403 } else {
2404 // If this is a use, return the original decl.
2405
2406 // FIXME: In the future, return a variant or some other clue
2407 // for the consumer of this Decl to know it doesn't own it.
2408 // For our current ASTs this shouldn't be a problem, but will
2409 // need to be changed with DeclGroups.
2410 if (TK == TK_Reference)
2411 return PrevDecl;
2412
2413 // The new decl is a definition?
2414 if (TK == TK_Definition) {
2415 // Diagnose attempts to redefine a tag.
2416 if (RecordDecl* DefRecord =
2417 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002418 Diag(NameLoc, diag::err_redefinition) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002419 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2420 // If this is a redefinition, recover by making this struct be
2421 // anonymous, which will make any later references get the previous
2422 // definition.
2423 Name = 0;
2424 PrevDecl = 0;
2425 }
2426 // Okay, this is definition of a previously declared or referenced
2427 // tag. We're going to create a new Decl.
2428 }
2429 }
2430 // If we get here we have (another) forward declaration. Just create
2431 // a new decl.
2432 }
2433 else {
2434 // If we get here, this is a definition of a new struct type in a nested
2435 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2436 // new decl/type. We set PrevDecl to NULL so that the Records
2437 // have distinct types.
2438 PrevDecl = 0;
2439 }
2440 } else {
2441 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002442 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002443 // The tag name clashes with a namespace name, issue an error and
2444 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002445 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002446 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2447 Name = 0;
2448 }
2449 }
2450 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002451
2452 CreateNewDecl:
2453
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002454 // If there is an identifier, use the location of the identifier as the
2455 // location of the decl, otherwise use the location of the struct/union
2456 // keyword.
2457 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2458
2459 // Otherwise, if this is the first time we've seen this tag, create the decl.
2460 TagDecl *New;
2461
2462 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2463 // struct X { int A; } D; D should chain to X.
2464 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002465 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002466 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002467 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2468 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002469 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002470 dyn_cast_or_null<RecordDecl>(PrevDecl));
2471
2472 // If this has an identifier, add it to the scope stack.
2473 if ((TK == TK_Definition || !PrevDecl) && Name) {
2474 // The scope passed in may not be a decl scope. Zip up the scope tree until
2475 // we find one that is.
2476 while ((S->getFlags() & Scope::DeclScope) == 0)
2477 S = S->getParent();
2478
2479 // Add it to the decl chain.
2480 PushOnScopeChains(New, S);
2481 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002482
2483 // Handle #pragma pack: if the #pragma pack stack has non-default
2484 // alignment, make up a packed attribute for this decl. These
2485 // attributes are checked when the ASTContext lays out the
2486 // structure.
2487 //
2488 // It is important for implementing the correct semantics that this
2489 // happen here (in act on tag decl). The #pragma pack stack is
2490 // maintained as a result of parser callbacks which can occur at
2491 // many points during the parsing of a struct declaration (because
2492 // the #pragma tokens are effectively skipped over during the
2493 // parsing of the struct).
2494 if (unsigned Alignment = PackContext.getAlignment())
2495 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002496
2497 if (Attr)
2498 ProcessDeclAttributeList(New, Attr);
2499
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002500 // Set the lexical context. If the tag has a C++ scope specifier, the
2501 // lexical context will be different from the semantic context.
2502 New->setLexicalDeclContext(CurContext);
2503
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002504 return New;
2505}
2506
2507
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002508/// Collect the instance variables declared in an Objective-C object. Used in
2509/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002510static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002511 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002512 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002513 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2514
2515 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002516 for (ObjCInterfaceDecl::ivar_iterator
2517 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2518
Ted Kremenek01e67792008-08-20 03:26:33 +00002519 ObjCIvarDecl* ID = *I;
2520 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2521 ID->getIdentifier(),
2522 ID->getType(),
2523 ID->getBitWidth()));
2524 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002525}
2526
2527/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2528/// instance variables of ClassName into Decls.
2529void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2530 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002531 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002532 // Check that ClassName is a valid class
2533 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2534 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002535 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002536 return;
2537 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002538 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002539 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002540}
2541
Chris Lattner1d353ba2008-11-12 21:17:48 +00002542/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2543/// types into constant array types in certain situations which would otherwise
2544/// be errors (for GCC compatibility).
2545static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2546 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002547 // This method tries to turn a variable array into a constant
2548 // array even when the size isn't an ICE. This is necessary
2549 // for compatibility with code that depends on gcc's buggy
2550 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002551 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2552 if (!VLATy) return QualType();
2553
2554 APValue Result;
2555 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002556 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002557 return QualType();
2558
2559 assert(Result.isInt() && "Size expressions must be integers!");
2560 llvm::APSInt &Res = Result.getInt();
2561 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2562 return Context.getConstantArrayType(VLATy->getElementType(),
2563 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002564 return QualType();
2565}
2566
Steve Naroff08d92e42007-09-15 18:49:24 +00002567/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002568/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002569Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 SourceLocation DeclStart,
2571 Declarator &D, ExprTy *BitfieldWidth) {
2572 IdentifierInfo *II = D.getIdentifier();
2573 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 SourceLocation Loc = DeclStart;
2575 if (II) Loc = D.getIdentifierLoc();
2576
2577 // FIXME: Unnamed fields can be handled in various different ways, for
2578 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002579
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 if (BitWidth) {
2581 // TODO: Validate.
2582 //printf("WARNING: BITFIELDS IGNORED!\n");
2583
2584 // 6.7.2.1p3
2585 // 6.7.2.1p4
2586
2587 } else {
2588 // Not a bitfield.
2589
2590 // validate II.
2591
2592 }
2593
2594 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002595 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2596 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002597
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2599 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002600 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002601 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002602 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002603 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002604 T = FixedTy;
2605 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002606 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002607 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002608 InvalidDecl = true;
2609 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002611 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002612 FieldDecl *NewFD;
2613
2614 if (getLangOptions().CPlusPlus) {
2615 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2616 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
Sebastian Redla11f42f2008-11-17 23:24:37 +00002617 Loc, II, T,
2618 D.getDeclSpec().getStorageClassSpec() ==
2619 DeclSpec::SCS_mutable, BitWidth);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002620 if (II)
2621 PushOnScopeChains(NewFD, S);
2622 }
2623 else
2624 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002625
Chris Lattner3ff30c82008-06-29 00:02:00 +00002626 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002627
Steve Naroff5912a352007-08-28 20:14:24 +00002628 if (D.getInvalidType() || InvalidDecl)
2629 NewFD->setInvalidDecl();
2630 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002631}
2632
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002633/// TranslateIvarVisibility - Translate visibility from a token ID to an
2634/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002635static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002636TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002637 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002638 default: assert(0 && "Unknown visitibility kind");
2639 case tok::objc_private: return ObjCIvarDecl::Private;
2640 case tok::objc_public: return ObjCIvarDecl::Public;
2641 case tok::objc_protected: return ObjCIvarDecl::Protected;
2642 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002643 }
2644}
2645
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002646/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2647/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002648Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002649 SourceLocation DeclStart,
2650 Declarator &D, ExprTy *BitfieldWidth,
2651 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002652 IdentifierInfo *II = D.getIdentifier();
2653 Expr *BitWidth = (Expr*)BitfieldWidth;
2654 SourceLocation Loc = DeclStart;
2655 if (II) Loc = D.getIdentifierLoc();
2656
2657 // FIXME: Unnamed fields can be handled in various different ways, for
2658 // example, unnamed unions inject all members into the struct namespace!
2659
2660
2661 if (BitWidth) {
2662 // TODO: Validate.
2663 //printf("WARNING: BITFIELDS IGNORED!\n");
2664
2665 // 6.7.2.1p3
2666 // 6.7.2.1p4
2667
2668 } else {
2669 // Not a bitfield.
2670
2671 // validate II.
2672
2673 }
2674
2675 QualType T = GetTypeForDeclarator(D, S);
2676 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2677 bool InvalidDecl = false;
2678
2679 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2680 // than a variably modified type.
2681 if (T->isVariablyModifiedType()) {
2682 // FIXME: This diagnostic needs work
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002683 Diag(Loc, diag::err_typecheck_illegal_vla) << SourceRange(Loc);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002684 InvalidDecl = true;
2685 }
2686
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002687 // Get the visibility (access control) for this ivar.
2688 ObjCIvarDecl::AccessControl ac =
2689 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2690 : ObjCIvarDecl::None;
2691
2692 // Construct the decl.
2693 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002694 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002695
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002696 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002697 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002698
2699 if (D.getInvalidType() || InvalidDecl)
2700 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002701
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002702 return NewID;
2703}
2704
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002705void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002706 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002707 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002708 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002709 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002710 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2711 assert(EnclosingDecl && "missing record or interface decl");
2712 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2713
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002714 if (Record)
2715 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2716 // Diagnose code like:
2717 // struct S { struct S {} X; };
2718 // We discover this when we complete the outer S. Reject and ignore the
2719 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002720 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
2721 << DefRecord->getKindName();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002722 Diag(RecLoc, diag::err_previous_definition);
2723 Record->setInvalidDecl();
2724 return;
2725 }
2726
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 // Verify that all the fields are okay.
2728 unsigned NumNamedMembers = 0;
2729 llvm::SmallVector<FieldDecl*, 32> RecFields;
2730 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002731
Reid Spencer5f016e22007-07-11 17:01:13 +00002732 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002733
Steve Naroff74216642007-09-14 22:20:54 +00002734 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2735 assert(FD && "missing field decl");
2736
2737 // Remember all fields.
2738 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002739
2740 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002741 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002742
Reid Spencer5f016e22007-07-11 17:01:13 +00002743 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002744 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002745 Diag(FD->getLocation(), diag::err_field_declared_as_function)
2746 << FD->getName();
Steve Naroff74216642007-09-14 22:20:54 +00002747 FD->setInvalidDecl();
2748 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002749 continue;
2750 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2752 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002753 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002754 Diag(FD->getLocation(), diag::err_field_incomplete) << FD->getName();
Steve Naroff74216642007-09-14 22:20:54 +00002755 FD->setInvalidDecl();
2756 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002757 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002758 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002759 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002760 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002761 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002762 Diag(FD->getLocation(), diag::err_field_incomplete) << FD->getName();
Steve Naroff74216642007-09-14 22:20:54 +00002763 FD->setInvalidDecl();
2764 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 continue;
2766 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002767 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002768 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
2769 << FD->getName();
Steve Naroff74216642007-09-14 22:20:54 +00002770 FD->setInvalidDecl();
2771 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 continue;
2773 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002775 if (Record)
2776 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002778 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2779 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002780 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2782 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002783 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 Record->setHasFlexibleArrayMember(true);
2785 } else {
2786 // If this is a struct/class and this is not the last element, reject
2787 // it. Note that GCC supports variable sized arrays in the middle of
2788 // structures.
2789 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002790 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
2791 << FD->getName();
Steve Naroff74216642007-09-14 22:20:54 +00002792 FD->setInvalidDecl();
2793 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002794 continue;
2795 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 // We support flexible arrays at the end of structs in other structs
2797 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002798 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
2799 << FD->getName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002800 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002801 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002802 }
2803 }
2804 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002805 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002806 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002807 Diag(FD->getLocation(), diag::err_statically_allocated_object)
2808 << FD->getName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002809 FD->setInvalidDecl();
2810 EnclosingDecl->setInvalidDecl();
2811 continue;
2812 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Keep track of the number of named members.
2814 if (IdentifierInfo *II = FD->getIdentifier()) {
2815 // Detect duplicate member names.
2816 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002817 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002818 // Find the previous decl.
2819 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002820 for (unsigned i = 0; ; ++i) {
2821 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002822 if (RecFields[i]->getIdentifier() == II) {
2823 PrevLoc = RecFields[i]->getLocation();
2824 break;
2825 }
2826 }
2827 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002828 FD->setInvalidDecl();
2829 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 continue;
2831 }
2832 ++NumNamedMembers;
2833 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002834 }
2835
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002837 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002838 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002839 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2840 // Sema::ActOnFinishCXXClassDef.
2841 if (!isa<CXXRecordDecl>(Record))
2842 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002843 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002844 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2845 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2846 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2847 else if (ObjCImplementationDecl *IMPDecl =
2848 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002849 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2850 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002851 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002852 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002853 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002854
2855 if (Attr)
2856 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002857}
2858
Steve Naroff08d92e42007-09-15 18:49:24 +00002859Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 DeclTy *lastEnumConst,
2861 SourceLocation IdLoc, IdentifierInfo *Id,
2862 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002863 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002864 EnumConstantDecl *LastEnumConst =
2865 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2866 Expr *Val = static_cast<Expr*>(val);
2867
Chris Lattner31e05722007-08-26 06:24:45 +00002868 // The scope passed in may not be a decl scope. Zip up the scope tree until
2869 // we find one that is.
2870 while ((S->getFlags() & Scope::DeclScope) == 0)
2871 S = S->getParent();
2872
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 // Verify that there isn't already something declared with this name in this
2874 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002875 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002876 // When in C++, we may get a TagDecl with the same name; in this case the
2877 // enum constant will 'hide' the tag.
2878 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2879 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002880 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002881 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00002882 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002883 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002884 Diag(IdLoc, diag::err_redefinition) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002885 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002886 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002887 return 0;
2888 }
2889 }
2890
2891 llvm::APSInt EnumVal(32);
2892 QualType EltTy;
2893 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002894 // Make sure to promote the operand type to int.
2895 UsualUnaryConversions(Val);
2896
Reid Spencer5f016e22007-07-11 17:01:13 +00002897 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2898 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002899 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002900 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr) << Id;
Chris Lattnera73349d2008-02-26 00:33:57 +00002901 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002902 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002903 } else {
2904 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002905 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002906 }
2907
2908 if (!Val) {
2909 if (LastEnumConst) {
2910 // Assign the last value + 1.
2911 EnumVal = LastEnumConst->getInitVal();
2912 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002913
2914 // Check for overflow on increment.
2915 if (EnumVal < LastEnumConst->getInitVal())
2916 Diag(IdLoc, diag::warn_enum_value_overflow);
2917
Chris Lattnerb7416f92007-08-27 17:37:24 +00002918 EltTy = LastEnumConst->getType();
2919 } else {
2920 // First value, set to zero.
2921 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002922 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002923 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002924 }
2925
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002926 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002927 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2928 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002929 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002930
2931 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002932 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002933 return New;
2934}
2935
Steve Naroff02408c62008-08-07 14:08:16 +00002936// FIXME: For consistency with ActOnFields(), we should have the parser
2937// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002938void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002939 DeclTy **Elements, unsigned NumElements) {
2940 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002941
Steve Naroff02408c62008-08-07 14:08:16 +00002942 if (Enum && Enum->isDefinition()) {
2943 // Diagnose code like:
2944 // enum e0 {
2945 // E0 = sizeof(enum e0 { E1 })
2946 // };
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002947 Diag(Enum->getLocation(), diag::err_nested_redefinition) << Enum->getName();
Steve Naroff02408c62008-08-07 14:08:16 +00002948 Diag(EnumLoc, diag::err_previous_definition);
2949 Enum->setInvalidDecl();
2950 return;
2951 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002952 // TODO: If the result value doesn't fit in an int, it must be a long or long
2953 // long value. ISO C does not support this, but GCC does as an extension,
2954 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002955 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002956
Chris Lattnerac609682007-08-28 06:15:15 +00002957 // Verify that all the values are okay, compute the size of the values, and
2958 // reverse the list.
2959 unsigned NumNegativeBits = 0;
2960 unsigned NumPositiveBits = 0;
2961
2962 // Keep track of whether all elements have type int.
2963 bool AllElementsInt = true;
2964
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 EnumConstantDecl *EltList = 0;
2966 for (unsigned i = 0; i != NumElements; ++i) {
2967 EnumConstantDecl *ECD =
2968 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2969 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002970
2971 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002972 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002973 assert(InitVal.getBitWidth() >= IntWidth &&
2974 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002975 if (InitVal.getBitWidth() > IntWidth) {
2976 llvm::APSInt V(InitVal);
2977 V.trunc(IntWidth);
2978 V.extend(InitVal.getBitWidth());
2979 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002980 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
2981 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00002982 }
Chris Lattnerac609682007-08-28 06:15:15 +00002983
2984 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002985 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002986 NumPositiveBits = std::max(NumPositiveBits,
2987 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002988 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002989 NumNegativeBits = std::max(NumNegativeBits,
2990 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002991
Chris Lattnerac609682007-08-28 06:15:15 +00002992 // Keep track of whether every enum element has type int (very commmon).
2993 if (AllElementsInt)
2994 AllElementsInt = ECD->getType() == Context.IntTy;
2995
Reid Spencer5f016e22007-07-11 17:01:13 +00002996 ECD->setNextDeclarator(EltList);
2997 EltList = ECD;
2998 }
2999
Chris Lattnerac609682007-08-28 06:15:15 +00003000 // Figure out the type that should be used for this enum.
3001 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3002 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003003 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003004
3005 if (NumNegativeBits) {
3006 // If there is a negative value, figure out the smallest integer type (of
3007 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003008 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003009 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003010 BestWidth = IntWidth;
3011 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003012 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003013
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003014 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003015 BestType = Context.LongTy;
3016 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003017 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003018
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003019 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003020 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3021 BestType = Context.LongLongTy;
3022 }
3023 }
3024 } else {
3025 // If there is no negative value, figure out which of uint, ulong, ulonglong
3026 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003027 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003028 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003029 BestWidth = IntWidth;
3030 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003031 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003032 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003033 } else {
3034 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003035 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003036 "How could an initializer get larger than ULL?");
3037 BestType = Context.UnsignedLongLongTy;
3038 }
3039 }
3040
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003041 // Loop over all of the enumerator constants, changing their types to match
3042 // the type of the enum if needed.
3043 for (unsigned i = 0; i != NumElements; ++i) {
3044 EnumConstantDecl *ECD =
3045 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3046 if (!ECD) continue; // Already issued a diagnostic.
3047
3048 // Standard C says the enumerators have int type, but we allow, as an
3049 // extension, the enumerators to be larger than int size. If each
3050 // enumerator value fits in an int, type it as an int, otherwise type it the
3051 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3052 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003053 if (ECD->getType() == Context.IntTy) {
3054 // Make sure the init value is signed.
3055 llvm::APSInt IV = ECD->getInitVal();
3056 IV.setIsSigned(true);
3057 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003058 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003059 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003060
3061 // Determine whether the value fits into an int.
3062 llvm::APSInt InitVal = ECD->getInitVal();
3063 bool FitsInInt;
3064 if (InitVal.isUnsigned() || !InitVal.isNegative())
3065 FitsInInt = InitVal.getActiveBits() < IntWidth;
3066 else
3067 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3068
3069 // If it fits into an integer type, force it. Otherwise force it to match
3070 // the enum decl type.
3071 QualType NewTy;
3072 unsigned NewWidth;
3073 bool NewSign;
3074 if (FitsInInt) {
3075 NewTy = Context.IntTy;
3076 NewWidth = IntWidth;
3077 NewSign = true;
3078 } else if (ECD->getType() == BestType) {
3079 // Already the right type!
3080 continue;
3081 } else {
3082 NewTy = BestType;
3083 NewWidth = BestWidth;
3084 NewSign = BestType->isSignedIntegerType();
3085 }
3086
3087 // Adjust the APSInt value.
3088 InitVal.extOrTrunc(NewWidth);
3089 InitVal.setIsSigned(NewSign);
3090 ECD->setInitVal(InitVal);
3091
3092 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003093 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3094 /*isLvalue=*/false));
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003095 ECD->setType(NewTy);
3096 }
Chris Lattnerac609682007-08-28 06:15:15 +00003097
Chris Lattnere00b18c2007-08-28 18:24:31 +00003098 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003099 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003100}
3101
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003102Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3103 ExprTy *expr) {
3104 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3105
Chris Lattner8e25d862008-03-16 00:16:02 +00003106 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003107}
3108
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003109Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003110 SourceLocation LBrace,
3111 SourceLocation RBrace,
3112 const char *Lang,
3113 unsigned StrSize,
3114 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003115 LinkageSpecDecl::LanguageIDs Language;
3116 Decl *dcl = static_cast<Decl *>(D);
3117 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3118 Language = LinkageSpecDecl::lang_c;
3119 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3120 Language = LinkageSpecDecl::lang_cxx;
3121 else {
3122 Diag(Loc, diag::err_bad_language);
3123 return 0;
3124 }
3125
3126 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003127 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003128}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003129
3130void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3131 ExprTy *alignment, SourceLocation PragmaLoc,
3132 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3133 Expr *Alignment = static_cast<Expr *>(alignment);
3134
3135 // If specified then alignment must be a "small" power of two.
3136 unsigned AlignmentVal = 0;
3137 if (Alignment) {
3138 llvm::APSInt Val;
3139 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3140 !Val.isPowerOf2() ||
3141 Val.getZExtValue() > 16) {
3142 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3143 delete Alignment;
3144 return; // Ignore
3145 }
3146
3147 AlignmentVal = (unsigned) Val.getZExtValue();
3148 }
3149
3150 switch (Kind) {
3151 case Action::PPK_Default: // pack([n])
3152 PackContext.setAlignment(AlignmentVal);
3153 break;
3154
3155 case Action::PPK_Show: // pack(show)
3156 // Show the current alignment, making sure to show the right value
3157 // for the default.
3158 AlignmentVal = PackContext.getAlignment();
3159 // FIXME: This should come from the target.
3160 if (AlignmentVal == 0)
3161 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003162 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003163 break;
3164
3165 case Action::PPK_Push: // pack(push [, id] [, [n])
3166 PackContext.push(Name);
3167 // Set the new alignment if specified.
3168 if (Alignment)
3169 PackContext.setAlignment(AlignmentVal);
3170 break;
3171
3172 case Action::PPK_Pop: // pack(pop [, id] [, n])
3173 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3174 // "#pragma pack(pop, identifier, n) is undefined"
3175 if (Alignment && Name)
3176 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3177
3178 // Do the pop.
3179 if (!PackContext.pop(Name)) {
3180 // If a name was specified then failure indicates the name
3181 // wasn't found. Otherwise failure indicates the stack was
3182 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003183 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3184 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003185
3186 // FIXME: Warn about popping named records as MSVC does.
3187 } else {
3188 // Pop succeeded, set the new alignment if specified.
3189 if (Alignment)
3190 PackContext.setAlignment(AlignmentVal);
3191 }
3192 break;
3193
3194 default:
3195 assert(0 && "Invalid #pragma pack kind.");
3196 }
3197}
3198
3199bool PragmaPackStack::pop(IdentifierInfo *Name) {
3200 if (Stack.empty())
3201 return false;
3202
3203 // If name is empty just pop top.
3204 if (!Name) {
3205 Alignment = Stack.back().first;
3206 Stack.pop_back();
3207 return true;
3208 }
3209
3210 // Otherwise, find the named record.
3211 for (unsigned i = Stack.size(); i != 0; ) {
3212 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003213 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003214 // Found it, pop up to and including this record.
3215 Alignment = Stack[i].first;
3216 Stack.erase(Stack.begin() + i, Stack.end());
3217 return true;
3218 }
3219 }
3220
3221 return false;
3222}