blob: 18d77c4a18c751c436e9e9f48832e5272fd4e9a9 [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"
Daniel Dunbar4cde9272008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000032 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
33
Douglas Gregor2ce52f32008-04-13 21:07:44 +000034 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
35 isa<ObjCInterfaceDecl>(IIDecl) ||
36 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000037 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000038 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000039}
40
Douglas Gregor2f1bc522008-11-07 20:08:42 +000041std::string Sema::getTypeAsString(TypeTy *Type) {
42 QualType Ty = QualType::getFromOpaquePtr(Type);
43 return Ty.getAsString();
44}
45
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000046DeclContext *Sema::getDCParent(DeclContext *DC) {
47 // If CurContext is a ObjC method, getParent() will return NULL.
48 if (isa<ObjCMethodDecl>(DC))
49 return Context.getTranslationUnitDecl();
50
51 // A C++ inline method is parsed *after* the topmost class it was declared in
52 // is fully parsed (it's "complete").
53 // The parsing of a C++ inline method happens at the declaration context of
54 // the topmost (non-nested) class it is declared in.
55 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
56 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
57 DC = MD->getParent();
58 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
59 DC = RD;
60
61 // Return the declaration context of the topmost class the inline method is
62 // declared in.
63 return DC;
64 }
65
66 return DC->getParent();
67}
68
Chris Lattner9fdf9c62008-04-22 18:39:57 +000069void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000070 assert(getDCParent(DC) == CurContext &&
71 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000072 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000073}
74
Chris Lattnerb048c982008-04-06 04:47:34 +000075void Sema::PopDeclContext() {
76 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000077 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000078}
79
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000080/// Add this decl to the scope shadowed decl chains.
81void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000082 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000083
84 // C++ [basic.scope]p4:
85 // -- exactly one declaration shall declare a class name or
86 // enumeration name that is not a typedef name and the other
87 // declarations shall all refer to the same object or
88 // enumerator, or all refer to functions and function templates;
89 // in this case the class name or enumeration name is hidden.
90 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
91 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000092 IdentifierResolver::iterator
93 I = IdResolver.begin(TD->getIdentifier(),
94 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000095 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000096 // There is already a declaration with the same name in the same
97 // scope. It must be found before we find the new declaration,
98 // so swap the order on the shadowed declaration chain.
99
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000100 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000101 return;
102 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000103 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
104 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 // We are pushing the name of a function, which might be an
106 // overloaded name.
107 IdentifierResolver::iterator
108 I = IdResolver.begin(FD->getIdentifier(),
109 FD->getDeclContext(), false/*LookInParentCtx*/);
110 if (I != IdResolver.end() &&
111 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
112 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
113 // There is already a declaration with the same name in the same
114 // scope. It must be a function or an overloaded function.
115 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
116 if (!Ovl) {
117 // We haven't yet overloaded this function. Take the existing
118 // FunctionDecl and put it into an OverloadedFunctionDecl.
119 Ovl = OverloadedFunctionDecl::Create(Context,
120 FD->getDeclContext(),
121 FD->getIdentifier());
122 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
123
124 // Remove the name binding to the existing FunctionDecl...
125 IdResolver.RemoveDecl(*I);
126
127 // ... and put the OverloadedFunctionDecl in its place.
128 IdResolver.AddDecl(Ovl);
129 }
130
131 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
132 // to its list of overloads.
133 Ovl->addOverload(FD);
134
135 return;
136 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000137 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000138
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000139 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000140}
141
Steve Naroffb216c882007-10-09 22:01:59 +0000142void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000143 if (S->decl_empty()) return;
144 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000145
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
147 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000148 Decl *TmpD = static_cast<Decl*>(*I);
149 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000150
151 if (isa<CXXFieldDecl>(TmpD)) continue;
152
153 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
154 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000155
Reid Spencer5f016e22007-07-11 17:01:13 +0000156 IdentifierInfo *II = D->getIdentifier();
157 if (!II) continue;
158
Ted Kremeneka89d1972008-09-03 18:03:35 +0000159 // We only want to remove the decls from the identifier decl chains for
160 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000161 if (S->getFnParent() != 0)
162 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000163
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000164 // Chain this decl to the containing DeclContext.
165 D->setNext(CurContext->getDeclChain());
166 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 }
168}
169
Steve Naroffe8043c32008-04-01 23:04:06 +0000170/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
171/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000172ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000173 // The third "scope" argument is 0 since we aren't enabling lazy built-in
174 // creation from this context.
175 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000176
Steve Naroffb327ce02008-04-02 14:35:35 +0000177 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000178}
179
Steve Naroffe8043c32008-04-01 23:04:06 +0000180/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000181/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000182Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
183 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000185 unsigned NS = NSI;
186 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
187 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000188
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 // Scan up the scope chain looking for a decl that matches this identifier
190 // that is in the appropriate namespace. This search should not take long, as
191 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000192 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000193 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000194 if ((*I)->getIdentifierNamespace() & NS)
195 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000196
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 // If we didn't find a use of this identifier, and if the identifier
198 // corresponds to a compiler builtin, create the decl object for the builtin
199 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000200 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000201 if (enableLazyBuiltinCreation) {
202 // If this is a builtin on this (or all) targets, create the decl.
203 if (unsigned BuiltinID = II->getBuiltinID())
204 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
205 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000206 if (getLangOptions().ObjC1) {
207 // @interface and @compatibility_alias introduce typedef-like names.
208 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000209 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000210 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000211 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
212 if (IDI != ObjCInterfaceDecls.end())
213 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000214 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
215 if (I != ObjCAliasDecls.end())
216 return I->second->getClassInterface();
217 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 }
219 return 0;
220}
221
Chris Lattner95e2c712008-05-05 22:18:14 +0000222void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000223 if (!Context.getBuiltinVaListType().isNull())
224 return;
225
226 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000227 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000228 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000229 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
230}
231
Reid Spencer5f016e22007-07-11 17:01:13 +0000232/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
233/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000234ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
235 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 Builtin::ID BID = (Builtin::ID)bid;
237
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000238 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000239 InitBuiltinVaListType();
240
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000241 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000242 FunctionDecl *New = FunctionDecl::Create(Context,
243 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000244 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000245 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000246
Chris Lattner95e2c712008-05-05 22:18:14 +0000247 // Create Decl objects for each parameter, adding them to the
248 // FunctionDecl.
249 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
250 llvm::SmallVector<ParmVarDecl*, 16> Params;
251 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
252 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
253 FT->getArgType(i), VarDecl::None, 0,
254 0));
255 New->setParams(&Params[0], Params.size());
256 }
257
258
259
Chris Lattner7f925cc2008-04-11 07:00:53 +0000260 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000261 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 return New;
263}
264
265/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
266/// and scope as a previous declaration 'Old'. Figure out how to resolve this
267/// situation, merging decls or emitting diagnostics as appropriate.
268///
Steve Naroffe8043c32008-04-01 23:04:06 +0000269TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000270 // Allow multiple definitions for ObjC built-in typedefs.
271 // FIXME: Verify the underlying types are equivalent!
272 if (getLangOptions().ObjC1) {
273 const IdentifierInfo *typeIdent = New->getIdentifier();
274 if (typeIdent == Ident_id) {
275 Context.setObjCIdType(New);
276 return New;
277 } else if (typeIdent == Ident_Class) {
278 Context.setObjCClassType(New);
279 return New;
280 } else if (typeIdent == Ident_SEL) {
281 Context.setObjCSelType(New);
282 return New;
283 } else if (typeIdent == Ident_Protocol) {
284 Context.setObjCProtoType(New->getUnderlyingType());
285 return New;
286 }
287 // Fall through - the typedef name was not a builtin type.
288 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // Verify the old decl was also a typedef.
290 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
291 if (!Old) {
292 Diag(New->getLocation(), diag::err_redefinition_different_kind,
293 New->getName());
294 Diag(OldD->getLocation(), diag::err_previous_definition);
295 return New;
296 }
297
Chris Lattner99cb9972008-07-25 18:44:27 +0000298 // If the typedef types are not identical, reject them in all languages and
299 // with any extensions enabled.
300 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
301 Context.getCanonicalType(Old->getUnderlyingType()) !=
302 Context.getCanonicalType(New->getUnderlyingType())) {
303 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
304 New->getUnderlyingType().getAsString(),
305 Old->getUnderlyingType().getAsString());
306 Diag(Old->getLocation(), diag::err_previous_definition);
307 return Old;
308 }
309
Eli Friedman54ecfce2008-06-11 06:20:39 +0000310 if (getLangOptions().Microsoft) return New;
311
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000312 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
313 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
314 // *either* declaration is in a system header. The code below implements
315 // this adhoc compatibility rule. FIXME: The following code will not
316 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000317 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
318 SourceManager &SrcMgr = Context.getSourceManager();
319 if (SrcMgr.isInSystemHeader(Old->getLocation()))
320 return New;
321 if (SrcMgr.isInSystemHeader(New->getLocation()))
322 return New;
323 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000324
Ted Kremenek2d05c082008-05-23 21:28:18 +0000325 Diag(New->getLocation(), diag::err_redefinition, New->getName());
326 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 return New;
328}
329
Chris Lattner6b6b5372008-06-26 18:38:35 +0000330/// DeclhasAttr - returns true if decl Declaration already has the target
331/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000332static bool DeclHasAttr(const Decl *decl, const Attr *target) {
333 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
334 if (attr->getKind() == target->getKind())
335 return true;
336
337 return false;
338}
339
340/// MergeAttributes - append attributes from the Old decl to the New one.
341static void MergeAttributes(Decl *New, Decl *Old) {
342 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
343
Chris Lattnerddee4232008-03-03 03:28:21 +0000344 while (attr) {
345 tmp = attr;
346 attr = attr->getNext();
347
348 if (!DeclHasAttr(New, tmp)) {
349 New->addAttr(tmp);
350 } else {
351 tmp->setNext(0);
352 delete(tmp);
353 }
354 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000355
356 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000357}
358
Chris Lattner04421082008-04-08 04:40:51 +0000359/// MergeFunctionDecl - We just parsed a function 'New' from
360/// declarator D which has the same name and scope as a previous
361/// declaration 'Old'. Figure out how to resolve this situation,
362/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000363/// Redeclaration will be set true if this New is a redeclaration OldD.
364///
365/// In C++, New and Old must be declarations that are not
366/// overloaded. Use IsOverload to determine whether New and Old are
367/// overloaded, and to select the Old declaration that New should be
368/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000369FunctionDecl *
370Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000371 assert(!isa<OverloadedFunctionDecl>(OldD) &&
372 "Cannot merge with an overloaded function declaration");
373
Douglas Gregorf0097952008-04-21 02:02:58 +0000374 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // Verify the old decl was also a function.
376 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
377 if (!Old) {
378 Diag(New->getLocation(), diag::err_redefinition_different_kind,
379 New->getName());
380 Diag(OldD->getLocation(), diag::err_previous_definition);
381 return New;
382 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000383
384 // Determine whether the previous declaration was a definition,
385 // implicit declaration, or a declaration.
386 diag::kind PrevDiag;
387 if (Old->isThisDeclarationADefinition())
388 PrevDiag = diag::err_previous_definition;
389 else if (Old->isImplicit())
390 PrevDiag = diag::err_previous_implicit_declaration;
391 else
392 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000393
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000394 QualType OldQType = Context.getCanonicalType(Old->getType());
395 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000396
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000397 if (getLangOptions().CPlusPlus) {
398 // (C++98 13.1p2):
399 // Certain function declarations cannot be overloaded:
400 // -- Function declarations that differ only in the return type
401 // cannot be overloaded.
402 QualType OldReturnType
403 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
404 QualType NewReturnType
405 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
406 if (OldReturnType != NewReturnType) {
407 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
408 Diag(Old->getLocation(), PrevDiag);
409 return New;
410 }
411
412 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
413 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
414 if (OldMethod && NewMethod) {
415 // -- Member function declarations with the same name and the
416 // same parameter types cannot be overloaded if any of them
417 // is a static member function declaration.
418 if (OldMethod->isStatic() || NewMethod->isStatic()) {
419 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
420 Diag(Old->getLocation(), PrevDiag);
421 return New;
422 }
423 }
424
425 // (C++98 8.3.5p3):
426 // All declarations for a function shall agree exactly in both the
427 // return type and the parameter-type-list.
428 if (OldQType == NewQType) {
429 // We have a redeclaration.
430 MergeAttributes(New, Old);
431 Redeclaration = true;
432 return MergeCXXFunctionDecl(New, Old);
433 }
434
435 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000436 }
Chris Lattner04421082008-04-08 04:40:51 +0000437
438 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000439 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000440 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000441 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000442 MergeAttributes(New, Old);
443 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000444 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000445 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000446
Steve Naroff837618c2008-01-16 15:01:34 +0000447 // A function that has already been declared has been redeclared or defined
448 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000449
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
451 // TODO: This is totally simplistic. It should handle merging functions
452 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000453 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
454 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 return New;
456}
457
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000458/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000459static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000460 if (VD->isFileVarDecl())
461 return (!VD->getInit() &&
462 (VD->getStorageClass() == VarDecl::None ||
463 VD->getStorageClass() == VarDecl::Static));
464 return false;
465}
466
467/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
468/// when dealing with C "tentative" external object definitions (C99 6.9.2).
469void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
470 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000471 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000472
473 for (IdentifierResolver::iterator
474 I = IdResolver.begin(VD->getIdentifier(),
475 VD->getDeclContext(), false/*LookInParentCtx*/),
476 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000477 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000478 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
479
Steve Narofff855e6f2008-08-10 15:20:13 +0000480 // Handle the following case:
481 // int a[10];
482 // int a[]; - the code below makes sure we set the correct type.
483 // int a[11]; - this is an error, size isn't 10.
484 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
485 OldDecl->getType()->isConstantArrayType())
486 VD->setType(OldDecl->getType());
487
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000488 // Check for "tentative" definitions. We can't accomplish this in
489 // MergeVarDecl since the initializer hasn't been attached.
490 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
491 continue;
492
493 // Handle __private_extern__ just like extern.
494 if (OldDecl->getStorageClass() != VarDecl::Extern &&
495 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
496 VD->getStorageClass() != VarDecl::Extern &&
497 VD->getStorageClass() != VarDecl::PrivateExtern) {
498 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
499 Diag(OldDecl->getLocation(), diag::err_previous_definition);
500 }
501 }
502 }
503}
504
Reid Spencer5f016e22007-07-11 17:01:13 +0000505/// MergeVarDecl - We just parsed a variable 'New' which has the same name
506/// and scope as a previous declaration 'Old'. Figure out how to resolve this
507/// situation, merging decls or emitting diagnostics as appropriate.
508///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000509/// Tentative definition rules (C99 6.9.2p2) are checked by
510/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
511/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000512///
Steve Naroffe8043c32008-04-01 23:04:06 +0000513VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 // Verify the old decl was also a variable.
515 VarDecl *Old = dyn_cast<VarDecl>(OldD);
516 if (!Old) {
517 Diag(New->getLocation(), diag::err_redefinition_different_kind,
518 New->getName());
519 Diag(OldD->getLocation(), diag::err_previous_definition);
520 return New;
521 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000522
523 MergeAttributes(New, Old);
524
Reid Spencer5f016e22007-07-11 17:01:13 +0000525 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000526 QualType OldCType = Context.getCanonicalType(Old->getType());
527 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000528 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 Diag(New->getLocation(), diag::err_redefinition, New->getName());
530 Diag(Old->getLocation(), diag::err_previous_definition);
531 return New;
532 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000533 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
534 if (New->getStorageClass() == VarDecl::Static &&
535 (Old->getStorageClass() == VarDecl::None ||
536 Old->getStorageClass() == VarDecl::Extern)) {
537 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
538 Diag(Old->getLocation(), diag::err_previous_definition);
539 return New;
540 }
541 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
542 if (New->getStorageClass() != VarDecl::Static &&
543 Old->getStorageClass() == VarDecl::Static) {
544 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
545 Diag(Old->getLocation(), diag::err_previous_definition);
546 return New;
547 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000548 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
549 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 Diag(New->getLocation(), diag::err_redefinition, New->getName());
551 Diag(Old->getLocation(), diag::err_previous_definition);
552 }
553 return New;
554}
555
Chris Lattner04421082008-04-08 04:40:51 +0000556/// CheckParmsForFunctionDef - Check that the parameters of the given
557/// function are appropriate for the definition of a function. This
558/// takes care of any checks that cannot be performed on the
559/// declaration itself, e.g., that the types of each of the function
560/// parameters are complete.
561bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
562 bool HasInvalidParm = false;
563 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
564 ParmVarDecl *Param = FD->getParamDecl(p);
565
566 // C99 6.7.5.3p4: the parameters in a parameter type list in a
567 // function declarator that is part of a function definition of
568 // that function shall not have incomplete type.
569 if (Param->getType()->isIncompleteType() &&
570 !Param->isInvalidDecl()) {
571 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
572 Param->getType().getAsString());
573 Param->setInvalidDecl();
574 HasInvalidParm = true;
575 }
576 }
577
578 return HasInvalidParm;
579}
580
Reid Spencer5f016e22007-07-11 17:01:13 +0000581/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
582/// no declarator (e.g. "struct foo;") is parsed.
583Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
584 // TODO: emit error on 'int;' or 'const enum foo;'.
585 // TODO: emit error on 'typedef int;'
586 // if (!DS.isMissingDeclaratorOk()) Diag(...);
587
Steve Naroff92199282007-11-17 21:37:36 +0000588 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000589}
590
Steve Naroffd0091aa2008-01-10 22:15:12 +0000591bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000592 // Get the type before calling CheckSingleAssignmentConstraints(), since
593 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000594 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000595
Chris Lattner5cf216b2008-01-04 18:04:52 +0000596 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
597 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
598 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000599}
600
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000601bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000602 const ArrayType *AT = Context.getAsArrayType(DeclT);
603
604 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000605 // C99 6.7.8p14. We have an array of character type with unknown size
606 // being initialized to a string literal.
607 llvm::APSInt ConstVal(32);
608 ConstVal = strLiteral->getByteLength() + 1;
609 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000610 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000611 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000612 } else {
613 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000614 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000615 // FIXME: Avoid truncation for 64-bit length strings.
616 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000617 Diag(strLiteral->getSourceRange().getBegin(),
618 diag::warn_initializer_string_for_char_array_too_long,
619 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000620 }
621 // Set type from "char *" to "constant array of char".
622 strLiteral->setType(DeclT);
623 // For now, we always return false (meaning success).
624 return false;
625}
626
627StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000628 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000629 if (AT && AT->getElementType()->isCharType()) {
630 return dyn_cast<StringLiteral>(Init);
631 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000632 return 0;
633}
634
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000635bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
636 SourceLocation InitLoc,
637 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000638 // C++ [dcl.init.ref]p1:
639 // A variable declared to be a T&, that is “reference to type T”
640 // (8.3.2), shall be initialized by an object, or function, of
641 // type T or by an object that can be converted into a T.
642 if (DeclType->isReferenceType())
643 return CheckReferenceInit(Init, DeclType);
644
Steve Naroffca107302008-01-21 23:53:58 +0000645 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
646 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000647 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000648 return Diag(InitLoc,
Steve Naroffca107302008-01-21 23:53:58 +0000649 diag::err_variable_object_no_init,
650 VAT->getSizeExpr()->getSourceRange());
651
Steve Naroff2fdc3742007-12-10 22:44:33 +0000652 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
653 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000654 // FIXME: Handle wide strings
655 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
656 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000657
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000658 // C++ [dcl.init]p14:
659 // -- If the destination type is a (possibly cv-qualified) class
660 // type:
661 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
662 QualType DeclTypeC = Context.getCanonicalType(DeclType);
663 QualType InitTypeC = Context.getCanonicalType(Init->getType());
664
665 // -- If the initialization is direct-initialization, or if it is
666 // copy-initialization where the cv-unqualified version of the
667 // source type is the same class as, or a derived class of, the
668 // class of the destination, constructors are considered.
669 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
670 IsDerivedFrom(InitTypeC, DeclTypeC)) {
671 CXXConstructorDecl *Constructor
672 = PerformInitializationByConstructor(DeclType, &Init, 1,
673 InitLoc, Init->getSourceRange(),
674 InitEntity, IK_Copy);
675 return Constructor == 0;
676 }
677
678 // -- Otherwise (i.e., for the remaining copy-initialization
679 // cases), user-defined conversion sequences that can
680 // convert from the source type to the destination type or
681 // (when a conversion function is used) to a derived class
682 // thereof are enumerated as described in 13.3.1.4, and the
683 // best one is chosen through overload resolution
684 // (13.3). If the conversion cannot be done or is
685 // ambiguous, the initialization is ill-formed. The
686 // function selected is called with the initializer
687 // expression as its argument; if the function is a
688 // constructor, the call initializes a temporary of the
689 // destination type.
690 // FIXME: We're pretending to do copy elision here; return to
691 // this when we have ASTs for such things.
692 if (PerformImplicitConversion(Init, DeclType))
693 return Diag(InitLoc,
694 diag::err_typecheck_convert_incompatible,
695 DeclType.getAsString(), InitEntity,
696 "initializing",
697 Init->getSourceRange());
698 else
699 return false;
700 }
701
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000702 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000703 if (DeclType->isArrayType())
704 return Diag(Init->getLocStart(),
705 diag::err_array_init_list_required,
706 Init->getSourceRange());
707
Steve Naroffd0091aa2008-01-10 22:15:12 +0000708 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000709 } else if (getLangOptions().CPlusPlus) {
710 // C++ [dcl.init]p14:
711 // [...] If the class is an aggregate (8.5.1), and the initializer
712 // is a brace-enclosed list, see 8.5.1.
713 //
714 // Note: 8.5.1 is handled below; here, we diagnose the case where
715 // we have an initializer list and a destination type that is not
716 // an aggregate.
717 // FIXME: In C++0x, this is yet another form of initialization.
718 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
719 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
720 if (!ClassDecl->isAggregate())
721 return Diag(InitLoc,
722 diag::err_init_non_aggr_init_list,
723 DeclType.getAsString(),
724 Init->getSourceRange());
725 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000726 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000727
Steve Naroff0cca7492008-05-01 22:18:59 +0000728 InitListChecker CheckInitList(this, InitList, DeclType);
729 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000730}
731
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000732Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000733Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000734 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 IdentifierInfo *II = D.getIdentifier();
736
Chris Lattnere80a59c2007-07-25 00:24:17 +0000737 // All of these full declarators require an identifier. If it doesn't have
738 // one, the ParsedFreeStandingDeclSpec action should be used.
739 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000740 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000741 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000742 D.getDeclSpec().getSourceRange(), D.getSourceRange());
743 return 0;
744 }
745
Chris Lattner31e05722007-08-26 06:24:45 +0000746 // The scope passed in may not be a decl scope. Zip up the scope tree until
747 // we find one that is.
748 while ((S->getFlags() & Scope::DeclScope) == 0)
749 S = S->getParent();
750
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000752 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000753 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000754 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000755
756 // In C++, the previous declaration we find might be a tag type
757 // (class or enum). In this case, the new declaration will hide the
758 // tag type.
759 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
760 PrevDecl = 0;
761
Chris Lattner41af0932007-11-14 06:34:38 +0000762 QualType R = GetTypeForDeclarator(D, S);
763 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
764
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000766 // Check that there are no default arguments (C++ only).
767 if (getLangOptions().CPlusPlus)
768 CheckExtraCXXDefaultArguments(D);
769
Chris Lattner41af0932007-11-14 06:34:38 +0000770 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000771 if (!NewTD) return 0;
772
773 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000774 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000775 // Merge the decl with the existing one if appropriate. If the decl is
776 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000777 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
779 if (NewTD == 0) return 0;
780 }
781 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000782 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 // C99 6.7.7p2: If a typedef name specifies a variably modified type
784 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000785 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
786 // FIXME: Diagnostic needs to be fixed.
787 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000788 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 }
790 }
Chris Lattner41af0932007-11-14 06:34:38 +0000791 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000792 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 switch (D.getDeclSpec().getStorageClassSpec()) {
794 default: assert(0 && "Unknown storage class!");
795 case DeclSpec::SCS_auto:
796 case DeclSpec::SCS_register:
797 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
798 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000799 InvalidDecl = true;
800 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
802 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
803 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000804 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 }
806
Chris Lattnera98e58d2008-03-15 21:24:04 +0000807 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000808 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000809 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
810
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000811 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000812 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000813 // This is a C++ constructor declaration.
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000814 assert(CurContext->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000815 "Constructors can only be declared in a member context");
816
Douglas Gregor42a552f2008-11-05 20:51:48 +0000817 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000818
819 // Create the new declaration
820 NewFD = CXXConstructorDecl::Create(Context,
821 cast<CXXRecordDecl>(CurContext),
822 D.getIdentifierLoc(), II, R,
823 isExplicit, isInline,
824 /*isImplicitlyDeclared=*/false);
825
Douglas Gregor42a552f2008-11-05 20:51:48 +0000826 if (isInvalidDecl)
827 NewFD->setInvalidDecl();
828 } else if (D.getKind() == Declarator::DK_Destructor) {
829 // This is a C++ destructor declaration.
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000830 if (CurContext->isCXXRecord()) {
831 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000832
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000833 NewFD = CXXDestructorDecl::Create(Context,
834 cast<CXXRecordDecl>(CurContext),
835 D.getIdentifierLoc(), II, R,
836 isInline,
837 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000838
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000839 if (isInvalidDecl)
840 NewFD->setInvalidDecl();
841 } else {
842 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
843 // Create a FunctionDecl to satisfy the function definition parsing
844 // code path.
845 NewFD = FunctionDecl::Create(Context, CurContext, D.getIdentifierLoc(),
846 II, R, SC, isInline, LastDeclarator,
847 // FIXME: Move to DeclGroup...
848 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000849 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000850 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000851 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000852 if (!CurContext->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000853 Diag(D.getIdentifierLoc(),
854 diag::err_conv_function_not_member);
855 return 0;
856 } else {
857 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
858
859 NewFD = CXXConversionDecl::Create(Context,
860 cast<CXXRecordDecl>(CurContext),
861 D.getIdentifierLoc(), II, R,
862 isInline, isExplicit);
863
864 if (isInvalidDecl)
865 NewFD->setInvalidDecl();
866 }
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000867 } else if (CurContext->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000868 // This is a C++ method declaration.
869 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
870 D.getIdentifierLoc(), II, R,
871 (SC == FunctionDecl::Static), isInline,
872 LastDeclarator);
873 } else {
874 NewFD = FunctionDecl::Create(Context, CurContext,
875 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000876 II, R, SC, isInline, LastDeclarator,
877 // FIXME: Move to DeclGroup...
878 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000879 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000880 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000881 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000882
Daniel Dunbara80f8742008-08-05 01:35:17 +0000883 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000884 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000885 // The parser guarantees this is a string.
886 StringLiteral *SE = cast<StringLiteral>(E);
887 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
888 SE->getByteLength())));
889 }
890
Chris Lattner04421082008-04-08 04:40:51 +0000891 // Copy the parameter declarations from the declarator D to
892 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000893 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000894 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
895
896 // Create Decl objects for each parameter, adding them to the
897 // FunctionDecl.
898 llvm::SmallVector<ParmVarDecl*, 16> Params;
899
900 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
901 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000902 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000903 // We let through "const void" here because Sema::GetTypeForDeclarator
904 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000905 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
906 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000907 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
908 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000909 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
910
Chris Lattnerdef026a2008-04-10 02:26:16 +0000911 // In C++, the empty parameter-type-list must be spelled "void"; a
912 // typedef of void is not permitted.
913 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000914 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000915 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
916 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000917 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000918 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
919 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
920 }
921
922 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000923 } else if (R->getAsTypedefType()) {
924 // When we're declaring a function with a typedef, as in the
925 // following example, we'll need to synthesize (unnamed)
926 // parameters for use in the declaration.
927 //
928 // @code
929 // typedef void fn(int);
930 // fn f;
931 // @endcode
932 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
933 if (!FT) {
934 // This is a typedef of a function with no prototype, so we
935 // don't need to do anything.
936 } else if ((FT->getNumArgs() == 0) ||
937 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
938 FT->getArgType(0)->isVoidType())) {
939 // This is a zero-argument function. We don't need to do anything.
940 } else {
941 // Synthesize a parameter for each argument type.
942 llvm::SmallVector<ParmVarDecl*, 16> Params;
943 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
944 ArgType != FT->arg_type_end(); ++ArgType) {
945 Params.push_back(ParmVarDecl::Create(Context, CurContext,
946 SourceLocation(), 0,
947 *ArgType, VarDecl::None,
948 0, 0));
949 }
950
951 NewFD->setParams(&Params[0], Params.size());
952 }
Chris Lattner04421082008-04-08 04:40:51 +0000953 }
954
Douglas Gregor42a552f2008-11-05 20:51:48 +0000955 // C++ constructors and destructors are handled by separate
956 // routines, since they don't require any declaration merging (C++
957 // [class.mfct]p2) and they aren't ever pushed into scope, because
958 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
959 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
960 return ActOnConstructorDeclarator(Constructor);
961 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
962 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000963 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
964 return ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000965
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000966 // Extra checking for C++ overloaded operators (C++ [over.oper]).
967 if (NewFD->isOverloadedOperator() &&
968 CheckOverloadedOperatorDeclaration(NewFD))
969 NewFD->setInvalidDecl();
970
Steve Naroffffce4d52008-01-09 23:34:55 +0000971 // Merge the decl with the existing one if appropriate. Since C functions
972 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000973 if (PrevDecl &&
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000974 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000975 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000976
977 // If C++, determine whether NewFD is an overload of PrevDecl or
978 // a declaration that requires merging. If it's an overload,
979 // there's no more work to do here; we'll just add the new
980 // function to the scope.
981 OverloadedFunctionDecl::function_iterator MatchedDecl;
982 if (!getLangOptions().CPlusPlus ||
983 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
984 Decl *OldDecl = PrevDecl;
985
986 // If PrevDecl was an overloaded function, extract the
987 // FunctionDecl that matched.
988 if (isa<OverloadedFunctionDecl>(PrevDecl))
989 OldDecl = *MatchedDecl;
990
991 // NewFD and PrevDecl represent declarations that need to be
992 // merged.
993 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
994
995 if (NewFD == 0) return 0;
996 if (Redeclaration) {
997 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
998
999 if (OldDecl == PrevDecl) {
1000 // Remove the name binding for the previous
1001 // declaration. We'll add the binding back later, but then
1002 // it will refer to the new declaration (which will
1003 // contain more information).
1004 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1005 } else {
1006 // We need to update the OverloadedFunctionDecl with the
1007 // latest declaration of this function, so that name
1008 // lookup will always refer to the latest declaration of
1009 // this function.
1010 *MatchedDecl = NewFD;
1011
1012 // Add the redeclaration to the current scope, since we'll
1013 // be skipping PushOnScopeChains.
1014 S->AddDecl(NewFD);
1015
1016 return NewFD;
1017 }
1018 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001019 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 }
1021 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001022
1023 // In C++, check default arguments now that we have merged decls.
1024 if (getLangOptions().CPlusPlus)
1025 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001027 // Check that there are no default arguments (C++ only).
1028 if (getLangOptions().CPlusPlus)
1029 CheckExtraCXXDefaultArguments(D);
1030
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001031 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001032 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1033 D.getIdentifier()->getName());
1034 InvalidDecl = true;
1035 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001036
1037 VarDecl *NewVD;
1038 VarDecl::StorageClass SC;
1039 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001040 default: assert(0 && "Unknown storage class!");
1041 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1042 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1043 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1044 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1045 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1046 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001047 }
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001048 if (CurContext->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001049 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1050 // This is a static data member for a C++ class.
1051 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1052 D.getIdentifierLoc(), II,
1053 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001054 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001055 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001056 if (S->getFnParent() == 0) {
1057 // C99 6.9p2: The storage-class specifiers auto and register shall not
1058 // appear in the declaration specifiers in an external declaration.
1059 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1060 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1061 R.getAsString());
1062 InvalidDecl = true;
1063 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001064 }
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001065 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001066 II, R, SC, LastDeclarator,
1067 // FIXME: Move to DeclGroup...
1068 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001069 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001072 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001073
Daniel Dunbara735ad82008-08-06 00:03:29 +00001074 // Handle GNU asm-label extension (encoded as an attribute).
1075 if (Expr *E = (Expr*) D.getAsmLabel()) {
1076 // The parser guarantees this is a string.
1077 StringLiteral *SE = cast<StringLiteral>(E);
1078 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1079 SE->getByteLength())));
1080 }
1081
Nate Begemanc8e89a82008-03-14 18:07:10 +00001082 // Emit an error if an address space was applied to decl with local storage.
1083 // This includes arrays of objects with address space qualifiers, but not
1084 // automatic variables that point to other address spaces.
1085 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001086 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1087 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1088 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001089 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001090 // Merge the decl with the existing one if appropriate. If the decl is
1091 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001092 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 NewVD = MergeVarDecl(NewVD, PrevDecl);
1094 if (NewVD == 0) return 0;
1095 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001096 New = NewVD;
1097 }
1098
1099 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001100 if (II)
1101 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001102 // If any semantic error occurred, mark the decl as invalid.
1103 if (D.getInvalidType() || InvalidDecl)
1104 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001105
1106 return New;
1107}
1108
Steve Naroff6594a702008-10-27 11:34:16 +00001109void Sema::InitializerElementNotConstant(const Expr *Init) {
1110 Diag(Init->getExprLoc(),
1111 diag::err_init_element_not_constant, Init->getSourceRange());
1112}
1113
Eli Friedmanc594b322008-05-20 13:48:25 +00001114bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1115 switch (Init->getStmtClass()) {
1116 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001117 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001118 return true;
1119 case Expr::ParenExprClass: {
1120 const ParenExpr* PE = cast<ParenExpr>(Init);
1121 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1122 }
1123 case Expr::CompoundLiteralExprClass:
1124 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1125 case Expr::DeclRefExprClass: {
1126 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001127 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1128 if (VD->hasGlobalStorage())
1129 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001130 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001131 return true;
1132 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001133 if (isa<FunctionDecl>(D))
1134 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001135 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001136 return true;
1137 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001138 case Expr::MemberExprClass: {
1139 const MemberExpr *M = cast<MemberExpr>(Init);
1140 if (M->isArrow())
1141 return CheckAddressConstantExpression(M->getBase());
1142 return CheckAddressConstantExpressionLValue(M->getBase());
1143 }
1144 case Expr::ArraySubscriptExprClass: {
1145 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1146 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1147 return CheckAddressConstantExpression(ASE->getBase()) ||
1148 CheckArithmeticConstantExpression(ASE->getIdx());
1149 }
1150 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001151 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001152 return false;
1153 case Expr::UnaryOperatorClass: {
1154 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1155
1156 // C99 6.6p9
1157 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001158 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001159
Steve Naroff6594a702008-10-27 11:34:16 +00001160 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001161 return true;
1162 }
1163 }
1164}
1165
1166bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1167 switch (Init->getStmtClass()) {
1168 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001169 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001170 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001171 case Expr::ParenExprClass:
1172 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001173 case Expr::StringLiteralClass:
1174 case Expr::ObjCStringLiteralClass:
1175 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001176 case Expr::CallExprClass:
1177 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1178 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1179 Builtin::BI__builtin___CFStringMakeConstantString)
1180 return false;
1181
Steve Naroff6594a702008-10-27 11:34:16 +00001182 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001183 return true;
1184
Eli Friedmanc594b322008-05-20 13:48:25 +00001185 case Expr::UnaryOperatorClass: {
1186 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1187
1188 // C99 6.6p9
1189 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1190 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1191
1192 if (Exp->getOpcode() == UnaryOperator::Extension)
1193 return CheckAddressConstantExpression(Exp->getSubExpr());
1194
Steve Naroff6594a702008-10-27 11:34:16 +00001195 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001196 return true;
1197 }
1198 case Expr::BinaryOperatorClass: {
1199 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1200 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1201
1202 Expr *PExp = Exp->getLHS();
1203 Expr *IExp = Exp->getRHS();
1204 if (IExp->getType()->isPointerType())
1205 std::swap(PExp, IExp);
1206
1207 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1208 return CheckAddressConstantExpression(PExp) ||
1209 CheckArithmeticConstantExpression(IExp);
1210 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001211 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001212 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001213 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001214 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1215 // Check for implicit promotion
1216 if (SubExpr->getType()->isFunctionType() ||
1217 SubExpr->getType()->isArrayType())
1218 return CheckAddressConstantExpressionLValue(SubExpr);
1219 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001220
1221 // Check for pointer->pointer cast
1222 if (SubExpr->getType()->isPointerType())
1223 return CheckAddressConstantExpression(SubExpr);
1224
Eli Friedmanc3f07642008-08-25 20:46:57 +00001225 if (SubExpr->getType()->isIntegralType()) {
1226 // Check for the special-case of a pointer->int->pointer cast;
1227 // this isn't standard, but some code requires it. See
1228 // PR2720 for an example.
1229 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1230 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1231 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1232 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1233 if (IntWidth >= PointerWidth) {
1234 return CheckAddressConstantExpression(SubCast->getSubExpr());
1235 }
1236 }
1237 }
1238 }
1239 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001240 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001241 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001242
Steve Naroff6594a702008-10-27 11:34:16 +00001243 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001244 return true;
1245 }
1246 case Expr::ConditionalOperatorClass: {
1247 // FIXME: Should we pedwarn here?
1248 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1249 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001250 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001251 return true;
1252 }
1253 if (CheckArithmeticConstantExpression(Exp->getCond()))
1254 return true;
1255 if (Exp->getLHS() &&
1256 CheckAddressConstantExpression(Exp->getLHS()))
1257 return true;
1258 return CheckAddressConstantExpression(Exp->getRHS());
1259 }
1260 case Expr::AddrLabelExprClass:
1261 return false;
1262 }
1263}
1264
Eli Friedman4caf0552008-06-09 05:05:07 +00001265static const Expr* FindExpressionBaseAddress(const Expr* E);
1266
1267static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1268 switch (E->getStmtClass()) {
1269 default:
1270 return E;
1271 case Expr::ParenExprClass: {
1272 const ParenExpr* PE = cast<ParenExpr>(E);
1273 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1274 }
1275 case Expr::MemberExprClass: {
1276 const MemberExpr *M = cast<MemberExpr>(E);
1277 if (M->isArrow())
1278 return FindExpressionBaseAddress(M->getBase());
1279 return FindExpressionBaseAddressLValue(M->getBase());
1280 }
1281 case Expr::ArraySubscriptExprClass: {
1282 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1283 return FindExpressionBaseAddress(ASE->getBase());
1284 }
1285 case Expr::UnaryOperatorClass: {
1286 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1287
1288 if (Exp->getOpcode() == UnaryOperator::Deref)
1289 return FindExpressionBaseAddress(Exp->getSubExpr());
1290
1291 return E;
1292 }
1293 }
1294}
1295
1296static const Expr* FindExpressionBaseAddress(const Expr* E) {
1297 switch (E->getStmtClass()) {
1298 default:
1299 return E;
1300 case Expr::ParenExprClass: {
1301 const ParenExpr* PE = cast<ParenExpr>(E);
1302 return FindExpressionBaseAddress(PE->getSubExpr());
1303 }
1304 case Expr::UnaryOperatorClass: {
1305 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1306
1307 // C99 6.6p9
1308 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1309 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1310
1311 if (Exp->getOpcode() == UnaryOperator::Extension)
1312 return FindExpressionBaseAddress(Exp->getSubExpr());
1313
1314 return E;
1315 }
1316 case Expr::BinaryOperatorClass: {
1317 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1318
1319 Expr *PExp = Exp->getLHS();
1320 Expr *IExp = Exp->getRHS();
1321 if (IExp->getType()->isPointerType())
1322 std::swap(PExp, IExp);
1323
1324 return FindExpressionBaseAddress(PExp);
1325 }
1326 case Expr::ImplicitCastExprClass: {
1327 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1328
1329 // Check for implicit promotion
1330 if (SubExpr->getType()->isFunctionType() ||
1331 SubExpr->getType()->isArrayType())
1332 return FindExpressionBaseAddressLValue(SubExpr);
1333
1334 // Check for pointer->pointer cast
1335 if (SubExpr->getType()->isPointerType())
1336 return FindExpressionBaseAddress(SubExpr);
1337
1338 // We assume that we have an arithmetic expression here;
1339 // if we don't, we'll figure it out later
1340 return 0;
1341 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001342 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001343 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1344
1345 // Check for pointer->pointer cast
1346 if (SubExpr->getType()->isPointerType())
1347 return FindExpressionBaseAddress(SubExpr);
1348
1349 // We assume that we have an arithmetic expression here;
1350 // if we don't, we'll figure it out later
1351 return 0;
1352 }
1353 }
1354}
1355
Eli Friedmanc594b322008-05-20 13:48:25 +00001356bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1357 switch (Init->getStmtClass()) {
1358 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001359 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001360 return true;
1361 case Expr::ParenExprClass: {
1362 const ParenExpr* PE = cast<ParenExpr>(Init);
1363 return CheckArithmeticConstantExpression(PE->getSubExpr());
1364 }
1365 case Expr::FloatingLiteralClass:
1366 case Expr::IntegerLiteralClass:
1367 case Expr::CharacterLiteralClass:
1368 case Expr::ImaginaryLiteralClass:
1369 case Expr::TypesCompatibleExprClass:
1370 case Expr::CXXBoolLiteralExprClass:
1371 return false;
1372 case Expr::CallExprClass: {
1373 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001374
1375 // Allow any constant foldable calls to builtins.
1376 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001377 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001378
Steve Naroff6594a702008-10-27 11:34:16 +00001379 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001380 return true;
1381 }
1382 case Expr::DeclRefExprClass: {
1383 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1384 if (isa<EnumConstantDecl>(D))
1385 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001386 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001387 return true;
1388 }
1389 case Expr::CompoundLiteralExprClass:
1390 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1391 // but vectors are allowed to be magic.
1392 if (Init->getType()->isVectorType())
1393 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001394 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001395 return true;
1396 case Expr::UnaryOperatorClass: {
1397 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1398
1399 switch (Exp->getOpcode()) {
1400 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1401 // See C99 6.6p3.
1402 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001403 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001404 return true;
1405 case UnaryOperator::SizeOf:
1406 case UnaryOperator::AlignOf:
1407 case UnaryOperator::OffsetOf:
1408 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1409 // See C99 6.5.3.4p2 and 6.6p3.
1410 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1411 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001412 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001413 return true;
1414 case UnaryOperator::Extension:
1415 case UnaryOperator::LNot:
1416 case UnaryOperator::Plus:
1417 case UnaryOperator::Minus:
1418 case UnaryOperator::Not:
1419 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1420 }
1421 }
1422 case Expr::SizeOfAlignOfTypeExprClass: {
1423 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1424 // Special check for void types, which are allowed as an extension
1425 if (Exp->getArgumentType()->isVoidType())
1426 return false;
1427 // alignof always evaluates to a constant.
1428 // FIXME: is sizeof(int[3.0]) a constant expression?
1429 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001430 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001431 return true;
1432 }
1433 return false;
1434 }
1435 case Expr::BinaryOperatorClass: {
1436 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1437
1438 if (Exp->getLHS()->getType()->isArithmeticType() &&
1439 Exp->getRHS()->getType()->isArithmeticType()) {
1440 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1441 CheckArithmeticConstantExpression(Exp->getRHS());
1442 }
1443
Eli Friedman4caf0552008-06-09 05:05:07 +00001444 if (Exp->getLHS()->getType()->isPointerType() &&
1445 Exp->getRHS()->getType()->isPointerType()) {
1446 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1447 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1448
1449 // Only allow a null (constant integer) base; we could
1450 // allow some additional cases if necessary, but this
1451 // is sufficient to cover offsetof-like constructs.
1452 if (!LHSBase && !RHSBase) {
1453 return CheckAddressConstantExpression(Exp->getLHS()) ||
1454 CheckAddressConstantExpression(Exp->getRHS());
1455 }
1456 }
1457
Steve Naroff6594a702008-10-27 11:34:16 +00001458 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001459 return true;
1460 }
1461 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001462 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001463 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001464 if (SubExpr->getType()->isArithmeticType())
1465 return CheckArithmeticConstantExpression(SubExpr);
1466
Eli Friedmanb529d832008-09-02 09:37:00 +00001467 if (SubExpr->getType()->isPointerType()) {
1468 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1469 // If the pointer has a null base, this is an offsetof-like construct
1470 if (!Base)
1471 return CheckAddressConstantExpression(SubExpr);
1472 }
1473
Steve Naroff6594a702008-10-27 11:34:16 +00001474 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001475 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001476 }
1477 case Expr::ConditionalOperatorClass: {
1478 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001479
1480 // If GNU extensions are disabled, we require all operands to be arithmetic
1481 // constant expressions.
1482 if (getLangOptions().NoExtensions) {
1483 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1484 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1485 CheckArithmeticConstantExpression(Exp->getRHS());
1486 }
1487
1488 // Otherwise, we have to emulate some of the behavior of fold here.
1489 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1490 // because it can constant fold things away. To retain compatibility with
1491 // GCC code, we see if we can fold the condition to a constant (which we
1492 // should always be able to do in theory). If so, we only require the
1493 // specified arm of the conditional to be a constant. This is a horrible
1494 // hack, but is require by real world code that uses __builtin_constant_p.
1495 APValue Val;
1496 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1497 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1498 // won't be able to either. Use it to emit the diagnostic though.
1499 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1500 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1501 return Res;
1502 }
1503
1504 // Verify that the side following the condition is also a constant.
1505 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1506 if (Val.getInt() == 0)
1507 std::swap(TrueSide, FalseSide);
1508
1509 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001510 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001511
1512 // Okay, the evaluated side evaluates to a constant, so we accept this.
1513 // Check to see if the other side is obviously not a constant. If so,
1514 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001515 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001516 Diag(Init->getExprLoc(),
1517 diag::ext_typecheck_expression_not_constant_but_accepted,
1518 FalseSide->getSourceRange());
1519 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001520 }
1521 }
1522}
1523
1524bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001525 Init = Init->IgnoreParens();
1526
Eli Friedmanc594b322008-05-20 13:48:25 +00001527 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1528 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1529 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1530
Nuno Lopes9a979c32008-07-07 16:46:50 +00001531 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1532 return CheckForConstantInitializer(e->getInitializer(), DclT);
1533
Eli Friedmanc594b322008-05-20 13:48:25 +00001534 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1535 unsigned numInits = Exp->getNumInits();
1536 for (unsigned i = 0; i < numInits; i++) {
1537 // FIXME: Need to get the type of the declaration for C++,
1538 // because it could be a reference?
1539 if (CheckForConstantInitializer(Exp->getInit(i),
1540 Exp->getInit(i)->getType()))
1541 return true;
1542 }
1543 return false;
1544 }
1545
1546 if (Init->isNullPointerConstant(Context))
1547 return false;
1548 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001549 QualType InitTy = Context.getCanonicalType(Init->getType())
1550 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001551 if (InitTy == Context.BoolTy) {
1552 // Special handling for pointers implicitly cast to bool;
1553 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1554 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1555 Expr* SubE = ICE->getSubExpr();
1556 if (SubE->getType()->isPointerType() ||
1557 SubE->getType()->isArrayType() ||
1558 SubE->getType()->isFunctionType()) {
1559 return CheckAddressConstantExpression(Init);
1560 }
1561 }
1562 } else if (InitTy->isIntegralType()) {
1563 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001564 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001565 SubE = CE->getSubExpr();
1566 // Special check for pointer cast to int; we allow as an extension
1567 // an address constant cast to an integer if the integer
1568 // is of an appropriate width (this sort of code is apparently used
1569 // in some places).
1570 // FIXME: Add pedwarn?
1571 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1572 if (SubE && (SubE->getType()->isPointerType() ||
1573 SubE->getType()->isArrayType() ||
1574 SubE->getType()->isFunctionType())) {
1575 unsigned IntWidth = Context.getTypeSize(Init->getType());
1576 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1577 if (IntWidth >= PointerWidth)
1578 return CheckAddressConstantExpression(Init);
1579 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001580 }
1581
1582 return CheckArithmeticConstantExpression(Init);
1583 }
1584
1585 if (Init->getType()->isPointerType())
1586 return CheckAddressConstantExpression(Init);
1587
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001588 // An array type at the top level that isn't an init-list must
1589 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001590 if (Init->getType()->isArrayType())
1591 return false;
1592
Nuno Lopes73419bf2008-09-01 18:42:41 +00001593 if (Init->getType()->isFunctionType())
1594 return false;
1595
Steve Naroff8af6a452008-10-02 17:12:56 +00001596 // Allow block exprs at top level.
1597 if (Init->getType()->isBlockPointerType())
1598 return false;
1599
Steve Naroff6594a702008-10-27 11:34:16 +00001600 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001601 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001602}
1603
Steve Naroffbb204692007-09-12 14:07:44 +00001604void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001605 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001606 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001607 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001608
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001609 // If there is no declaration, there was an error parsing it. Just ignore
1610 // the initializer.
1611 if (RealDecl == 0) {
1612 delete Init;
1613 return;
1614 }
Steve Naroffbb204692007-09-12 14:07:44 +00001615
Steve Naroff410e3e22007-09-12 20:13:48 +00001616 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1617 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001618 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1619 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001620 RealDecl->setInvalidDecl();
1621 return;
1622 }
Steve Naroffbb204692007-09-12 14:07:44 +00001623 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001624 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001625 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001626 if (VDecl->isBlockVarDecl()) {
1627 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001628 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001629 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001630 VDecl->setInvalidDecl();
1631 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001632 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1633 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001634 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001635
1636 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1637 if (!getLangOptions().CPlusPlus) {
1638 if (SC == VarDecl::Static) // C99 6.7.8p4.
1639 CheckForConstantInitializer(Init, DclT);
1640 }
Steve Naroffbb204692007-09-12 14:07:44 +00001641 }
Steve Naroff248a7532008-04-15 22:42:06 +00001642 } else if (VDecl->isFileVarDecl()) {
1643 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001644 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001645 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001646 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1647 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001648 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001649
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001650 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1651 if (!getLangOptions().CPlusPlus) {
1652 // C99 6.7.8p4. All file scoped initializers need to be constant.
1653 CheckForConstantInitializer(Init, DclT);
1654 }
Steve Naroffbb204692007-09-12 14:07:44 +00001655 }
1656 // If the type changed, it means we had an incomplete type that was
1657 // completed by the initializer. For example:
1658 // int ary[] = { 1, 3, 5 };
1659 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001660 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001661 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001662 Init->setType(DclT);
1663 }
Steve Naroffbb204692007-09-12 14:07:44 +00001664
1665 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001666 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001667 return;
1668}
1669
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001670void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1671 Decl *RealDecl = static_cast<Decl *>(dcl);
1672
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001673 // If there is no declaration, there was an error parsing it. Just ignore it.
1674 if (RealDecl == 0)
1675 return;
1676
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001677 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1678 QualType Type = Var->getType();
1679 // C++ [dcl.init.ref]p3:
1680 // The initializer can be omitted for a reference only in a
1681 // parameter declaration (8.3.5), in the declaration of a
1682 // function return type, in the declaration of a class member
1683 // within its class declaration (9.2), and where the extern
1684 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001685 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001686 Diag(Var->getLocation(),
1687 diag::err_reference_var_requires_init,
1688 Var->getName(),
1689 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001690 Var->setInvalidDecl();
1691 return;
1692 }
1693
1694 // C++ [dcl.init]p9:
1695 //
1696 // If no initializer is specified for an object, and the object
1697 // is of (possibly cv-qualified) non-POD class type (or array
1698 // thereof), the object shall be default-initialized; if the
1699 // object is of const-qualified type, the underlying class type
1700 // shall have a user-declared default constructor.
1701 if (getLangOptions().CPlusPlus) {
1702 QualType InitType = Type;
1703 if (const ArrayType *Array = Context.getAsArrayType(Type))
1704 InitType = Array->getElementType();
1705 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001706 const CXXConstructorDecl *Constructor
1707 = PerformInitializationByConstructor(InitType, 0, 0,
1708 Var->getLocation(),
1709 SourceRange(Var->getLocation(),
1710 Var->getLocation()),
1711 Var->getName(),
1712 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001713 if (!Constructor)
1714 Var->setInvalidDecl();
1715 }
1716 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001717
Douglas Gregor818ce482008-10-29 13:50:18 +00001718#if 0
1719 // FIXME: Temporarily disabled because we are not properly parsing
1720 // linkage specifications on declarations, e.g.,
1721 //
1722 // extern "C" const CGPoint CGPointerZero;
1723 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001724 // C++ [dcl.init]p9:
1725 //
1726 // If no initializer is specified for an object, and the
1727 // object is of (possibly cv-qualified) non-POD class type (or
1728 // array thereof), the object shall be default-initialized; if
1729 // the object is of const-qualified type, the underlying class
1730 // type shall have a user-declared default
1731 // constructor. Otherwise, if no initializer is specified for
1732 // an object, the object and its subobjects, if any, have an
1733 // indeterminate initial value; if the object or any of its
1734 // subobjects are of const-qualified type, the program is
1735 // ill-formed.
1736 //
1737 // This isn't technically an error in C, so we don't diagnose it.
1738 //
1739 // FIXME: Actually perform the POD/user-defined default
1740 // constructor check.
1741 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001742 Context.getCanonicalType(Type).isConstQualified() &&
1743 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001744 Diag(Var->getLocation(),
1745 diag::err_const_var_requires_init,
1746 Var->getName(),
1747 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001748#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001749 }
1750}
1751
Reid Spencer5f016e22007-07-11 17:01:13 +00001752/// The declarators are chained together backwards, reverse the list.
1753Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1754 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001755 Decl *GroupDecl = static_cast<Decl*>(group);
1756 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001757 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001758
1759 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1760 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001761 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001763 else { // reverse the list.
1764 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001765 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001766 Group->setNextDeclarator(NewGroup);
1767 NewGroup = Group;
1768 Group = Next;
1769 }
1770 }
1771 // Perform semantic analysis that depends on having fully processed both
1772 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001773 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001774 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1775 if (!IDecl)
1776 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001777 QualType T = IDecl->getType();
1778
1779 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1780 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001781 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1782 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001783 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001784 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1785 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001786 }
1787 }
1788 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1789 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001790 if (IDecl->isBlockVarDecl() &&
1791 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001792 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001793 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1794 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001795 IDecl->setInvalidDecl();
1796 }
1797 }
1798 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1799 // object that has file scope without an initializer, and without a
1800 // storage-class specifier or with the storage-class specifier "static",
1801 // constitutes a tentative definition. Note: A tentative definition with
1802 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001803 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001804 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001805 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1806 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001807 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001808 // C99 6.9.2p3: If the declaration of an identifier for an object is
1809 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1810 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001811 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1812 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001813 IDecl->setInvalidDecl();
1814 }
1815 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001816 if (IDecl->isFileVarDecl())
1817 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001818 }
1819 return NewGroup;
1820}
Steve Naroffe1223f72007-08-28 03:03:08 +00001821
Chris Lattner04421082008-04-08 04:40:51 +00001822/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1823/// to introduce parameters into function prototype scope.
1824Sema::DeclTy *
1825Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001826 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001827
1828 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001829 VarDecl::StorageClass StorageClass = VarDecl::None;
1830 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1831 StorageClass = VarDecl::Register;
1832 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001833 Diag(DS.getStorageClassSpecLoc(),
1834 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001835 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001836 }
1837 if (DS.isThreadSpecified()) {
1838 Diag(DS.getThreadSpecLoc(),
1839 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001840 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001841 }
1842
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001843 // Check that there are no default arguments inside the type of this
1844 // parameter (C++ only).
1845 if (getLangOptions().CPlusPlus)
1846 CheckExtraCXXDefaultArguments(D);
1847
Chris Lattner04421082008-04-08 04:40:51 +00001848 // In this context, we *do not* check D.getInvalidType(). If the declarator
1849 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1850 // though it will not reflect the user specified type.
1851 QualType parmDeclType = GetTypeForDeclarator(D, S);
1852
1853 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1854
Reid Spencer5f016e22007-07-11 17:01:13 +00001855 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1856 // Can this happen for params? We already checked that they don't conflict
1857 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001858 IdentifierInfo *II = D.getIdentifier();
1859 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1860 if (S->isDeclScope(PrevDecl)) {
1861 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1862 dyn_cast<NamedDecl>(PrevDecl)->getName());
1863
1864 // Recover by removing the name
1865 II = 0;
1866 D.SetIdentifier(0, D.getIdentifierLoc());
1867 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001869
1870 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1871 // Doing the promotion here has a win and a loss. The win is the type for
1872 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1873 // code generator). The loss is the orginal type isn't preserved. For example:
1874 //
1875 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1876 // int blockvardecl[5];
1877 // sizeof(parmvardecl); // size == 4
1878 // sizeof(blockvardecl); // size == 20
1879 // }
1880 //
1881 // For expressions, all implicit conversions are captured using the
1882 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1883 //
1884 // FIXME: If a source translation tool needs to see the original type, then
1885 // we need to consider storing both types (in ParmVarDecl)...
1886 //
Chris Lattnere6327742008-04-02 05:18:44 +00001887 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001888 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001889 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001890 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001891 parmDeclType = Context.getPointerType(parmDeclType);
1892
Chris Lattner04421082008-04-08 04:40:51 +00001893 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1894 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001895 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001896 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001897
Chris Lattner04421082008-04-08 04:40:51 +00001898 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001899 New->setInvalidDecl();
1900
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001901 if (II)
1902 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001903
Chris Lattner3ff30c82008-06-29 00:02:00 +00001904 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001905 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001906
Reid Spencer5f016e22007-07-11 17:01:13 +00001907}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001908
Chris Lattnerb652cea2007-10-09 17:14:05 +00001909Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001910 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001911 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1912 "Not a function declarator!");
1913 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001914
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1916 // for a K&R function.
1917 if (!FTI.hasPrototype) {
1918 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001919 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1921 FTI.ArgInfo[i].Ident->getName());
1922 // Implicitly declare the argument as type 'int' for lack of a better
1923 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001924 DeclSpec DS;
1925 const char* PrevSpec; // unused
1926 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1927 PrevSpec);
1928 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1929 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1930 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
1932 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001934 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001935 }
1936
1937 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001938
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001939 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001940 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001941}
1942
1943Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1944 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001945 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00001946
1947 // See if this is a redefinition.
1948 const FunctionDecl *Definition;
1949 if (FD->getBody(Definition)) {
1950 Diag(FD->getLocation(), diag::err_redefinition,
1951 FD->getName());
1952 Diag(Definition->getLocation(), diag::err_previous_definition);
1953 }
1954
Chris Lattnerb048c982008-04-06 04:47:34 +00001955 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001956
1957 // Check the validity of our function parameters
1958 CheckParmsForFunctionDef(FD);
1959
1960 // Introduce our parameters into the function scope
1961 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1962 ParmVarDecl *Param = FD->getParamDecl(p);
1963 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001964 if (Param->getIdentifier())
1965 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 }
Chris Lattner04421082008-04-08 04:40:51 +00001967
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 return FD;
1969}
1970
Steve Naroffd6d054d2007-11-11 23:20:51 +00001971Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1972 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001973 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001974 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001975 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001976 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001977 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001978 } else
1979 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001980 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 // Verify and clean out per-function state.
1982
1983 // Check goto/label use.
1984 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1985 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1986 // Verify that we have no forward references left. If so, there was a goto
1987 // or address of a label taken, but no definition of it. Label fwd
1988 // definitions are indicated with a null substmt.
1989 if (I->second->getSubStmt() == 0) {
1990 LabelStmt *L = I->second;
1991 // Emit error.
1992 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1993
1994 // At this point, we have gotos that use the bogus label. Stitch it into
1995 // the function body so that they aren't leaked and that the AST is well
1996 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001997 if (Body) {
1998 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1999 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2000 } else {
2001 // The whole function wasn't parsed correctly, just delete this.
2002 delete L;
2003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 }
2005 }
2006 LabelMap.clear();
2007
Steve Naroffd6d054d2007-11-11 23:20:51 +00002008 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002009}
2010
Reid Spencer5f016e22007-07-11 17:01:13 +00002011/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2012/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002013ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2014 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002015 // Extension in C99. Legal in C90, but warn about it.
2016 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00002018 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2020
2021 // FIXME: handle stuff like:
2022 // void foo() { extern float X(); }
2023 // void bar() { X(); } <-- implicit decl for X in another scope.
2024
2025 // Set a Declarator for the implicit definition: int foo();
2026 const char *Dummy;
2027 DeclSpec DS;
2028 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2029 Error = Error; // Silence warning.
2030 assert(!Error && "Error setting up implicit decl!");
2031 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002032 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 D.SetIdentifier(&II, Loc);
2034
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002035 // Insert this function into translation-unit scope.
2036
2037 DeclContext *PrevDC = CurContext;
2038 CurContext = Context.getTranslationUnitDecl();
2039
Steve Naroffe2ef8152008-04-04 14:32:09 +00002040 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002041 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002042 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002043
2044 CurContext = PrevDC;
2045
Steve Naroffe2ef8152008-04-04 14:32:09 +00002046 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002047}
2048
2049
Chris Lattner41af0932007-11-14 06:34:38 +00002050TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002051 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002053 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002054
2055 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002056 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2057 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002058 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002059 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002060 if (D.getInvalidType())
2061 NewTD->setInvalidDecl();
2062 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002063}
2064
Steve Naroff08d92e42007-09-15 18:49:24 +00002065/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002066/// former case, Name will be non-null. In the later case, Name will be null.
2067/// TagType indicates what kind of tag this is. TK indicates whether this is a
2068/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002069Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 SourceLocation KWLoc, IdentifierInfo *Name,
2071 SourceLocation NameLoc, AttributeList *Attr) {
2072 // If this is a use of an existing tag, it must have a name.
2073 assert((Name != 0 || TK == TK_Definition) &&
2074 "Nameless record must be a definition!");
2075
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002076 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 switch (TagType) {
2078 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002079 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2080 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2081 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2082 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 }
2084
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002085 // Two code paths: a new one for structs/unions/classes where we create
2086 // separate decls for forward declarations, and an old (eventually to
2087 // be removed) code path for enums.
2088 if (Kind != TagDecl::TK_enum)
2089 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
2090
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 // If this is a named struct, check to see if there was a previous forward
2092 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002093 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002094 ScopedDecl *PrevDecl =
2095 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2096
2097 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002098 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2099 "unexpected Decl type");
2100 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002101 // If this is a use of a previous tag, or if the tag is already declared
2102 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002103 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002104 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002105 // Make sure that this wasn't declared as an enum and now used as a
2106 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002107 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002108 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2109 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002110 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002111 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002112 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002113 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002114 // If this is a use or a forward declaration, we're good.
2115 if (TK != TK_Definition)
2116 return PrevDecl;
2117
2118 // Diagnose attempts to redefine a tag.
2119 if (PrevTagDecl->isDefinition()) {
2120 Diag(NameLoc, diag::err_redefinition, Name->getName());
2121 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2122 // If this is a redefinition, recover by making this struct be
2123 // anonymous, which will make any later references get the previous
2124 // definition.
2125 Name = 0;
2126 } else {
2127 // Okay, this is definition of a previously declared or referenced
2128 // tag. Move the location of the decl to be the definition site.
2129 PrevDecl->setLocation(NameLoc);
2130 return PrevDecl;
2131 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002132 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002133 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002134 // If we get here, this is a definition of a new struct type in a nested
2135 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2136 // type.
2137 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002138 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002139 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002140 // The tag name clashes with a namespace name, issue an error and
2141 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002142 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2143 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2144 Name = 0;
2145 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002147 }
2148
2149 // If there is an identifier, use the location of the identifier as the
2150 // location of the decl, otherwise use the location of the struct/union
2151 // keyword.
2152 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2153
2154 // Otherwise, if this is the first time we've seen this tag, create the decl.
2155 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002156 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2158 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002159 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 // If this is an undefined enum, warn.
2161 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002162 } else {
2163 // struct/union/class
2164
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2166 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002167 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002168 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenekdf042e62008-09-05 01:34:33 +00002169 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002170 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00002171 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002172 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002173
2174 // If this has an identifier, add it to the scope stack.
2175 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002176 // The scope passed in may not be a decl scope. Zip up the scope tree until
2177 // we find one that is.
2178 while ((S->getFlags() & Scope::DeclScope) == 0)
2179 S = S->getParent();
2180
2181 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002182 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002184
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002185 if (Attr)
2186 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002187 return New;
2188}
2189
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002190/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2191/// the logic for enums, we create separate decls for forward declarations.
2192/// This is called by ActOnTag, but eventually will replace its logic.
2193Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2194 SourceLocation KWLoc, IdentifierInfo *Name,
2195 SourceLocation NameLoc, AttributeList *Attr) {
2196
2197 // If this is a named struct, check to see if there was a previous forward
2198 // declaration or definition.
2199 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2200 ScopedDecl *PrevDecl =
2201 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2202
2203 if (PrevDecl) {
2204 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2205 "unexpected Decl type");
2206
2207 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2208 // If this is a use of a previous tag, or if the tag is already declared
2209 // in the same scope (so that the definition/declaration completes or
2210 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002211 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002212 // Make sure that this wasn't declared as an enum and now used as a
2213 // struct or something similar.
2214 if (PrevTagDecl->getTagKind() != Kind) {
2215 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2216 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2217 // Recover by making this an anonymous redefinition.
2218 Name = 0;
2219 PrevDecl = 0;
2220 } else {
2221 // If this is a use, return the original decl.
2222
2223 // FIXME: In the future, return a variant or some other clue
2224 // for the consumer of this Decl to know it doesn't own it.
2225 // For our current ASTs this shouldn't be a problem, but will
2226 // need to be changed with DeclGroups.
2227 if (TK == TK_Reference)
2228 return PrevDecl;
2229
2230 // The new decl is a definition?
2231 if (TK == TK_Definition) {
2232 // Diagnose attempts to redefine a tag.
2233 if (RecordDecl* DefRecord =
2234 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2235 Diag(NameLoc, diag::err_redefinition, Name->getName());
2236 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2237 // If this is a redefinition, recover by making this struct be
2238 // anonymous, which will make any later references get the previous
2239 // definition.
2240 Name = 0;
2241 PrevDecl = 0;
2242 }
2243 // Okay, this is definition of a previously declared or referenced
2244 // tag. We're going to create a new Decl.
2245 }
2246 }
2247 // If we get here we have (another) forward declaration. Just create
2248 // a new decl.
2249 }
2250 else {
2251 // If we get here, this is a definition of a new struct type in a nested
2252 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2253 // new decl/type. We set PrevDecl to NULL so that the Records
2254 // have distinct types.
2255 PrevDecl = 0;
2256 }
2257 } else {
2258 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002259 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002260 // The tag name clashes with a namespace name, issue an error and
2261 // recover by making this tag be anonymous.
2262 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2263 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2264 Name = 0;
2265 }
2266 }
2267 }
2268
2269 // If there is an identifier, use the location of the identifier as the
2270 // location of the decl, otherwise use the location of the struct/union
2271 // keyword.
2272 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2273
2274 // Otherwise, if this is the first time we've seen this tag, create the decl.
2275 TagDecl *New;
2276
2277 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2278 // struct X { int A; } D; D should chain to X.
2279 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002280 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002281 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2282 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2283 else
2284 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2285 dyn_cast_or_null<RecordDecl>(PrevDecl));
2286
2287 // If this has an identifier, add it to the scope stack.
2288 if ((TK == TK_Definition || !PrevDecl) && Name) {
2289 // The scope passed in may not be a decl scope. Zip up the scope tree until
2290 // we find one that is.
2291 while ((S->getFlags() & Scope::DeclScope) == 0)
2292 S = S->getParent();
2293
2294 // Add it to the decl chain.
2295 PushOnScopeChains(New, S);
2296 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002297
2298 // Handle #pragma pack: if the #pragma pack stack has non-default
2299 // alignment, make up a packed attribute for this decl. These
2300 // attributes are checked when the ASTContext lays out the
2301 // structure.
2302 //
2303 // It is important for implementing the correct semantics that this
2304 // happen here (in act on tag decl). The #pragma pack stack is
2305 // maintained as a result of parser callbacks which can occur at
2306 // many points during the parsing of a struct declaration (because
2307 // the #pragma tokens are effectively skipped over during the
2308 // parsing of the struct).
2309 if (unsigned Alignment = PackContext.getAlignment())
2310 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002311
2312 if (Attr)
2313 ProcessDeclAttributeList(New, Attr);
2314
2315 return New;
2316}
2317
2318
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002319/// Collect the instance variables declared in an Objective-C object. Used in
2320/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002321static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002322 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002323 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002324 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2325
2326 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002327 for (ObjCInterfaceDecl::ivar_iterator
2328 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2329
Ted Kremenek01e67792008-08-20 03:26:33 +00002330 ObjCIvarDecl* ID = *I;
2331 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2332 ID->getIdentifier(),
2333 ID->getType(),
2334 ID->getBitWidth()));
2335 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002336}
2337
2338/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2339/// instance variables of ClassName into Decls.
2340void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2341 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002342 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002343 // Check that ClassName is a valid class
2344 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2345 if (!Class) {
2346 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2347 return;
2348 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002349 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002350 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002351}
2352
Eli Friedman1b76ada2008-06-03 21:01:11 +00002353QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2354 // This method tries to turn a variable array into a constant
2355 // array even when the size isn't an ICE. This is necessary
2356 // for compatibility with code that depends on gcc's buggy
2357 // constant expression folding, like struct {char x[(int)(char*)2];}
2358 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00002359 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002360 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00002361 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2362 llvm::APSInt &Res = Result.getInt();
2363 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2364 return Context.getConstantArrayType(VLATy->getElementType(),
2365 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002366 }
2367 }
2368 return QualType();
2369}
2370
Steve Naroff08d92e42007-09-15 18:49:24 +00002371/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002372/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002373Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002374 SourceLocation DeclStart,
2375 Declarator &D, ExprTy *BitfieldWidth) {
2376 IdentifierInfo *II = D.getIdentifier();
2377 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 SourceLocation Loc = DeclStart;
2379 if (II) Loc = D.getIdentifierLoc();
2380
2381 // FIXME: Unnamed fields can be handled in various different ways, for
2382 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002383
Reid Spencer5f016e22007-07-11 17:01:13 +00002384 if (BitWidth) {
2385 // TODO: Validate.
2386 //printf("WARNING: BITFIELDS IGNORED!\n");
2387
2388 // 6.7.2.1p3
2389 // 6.7.2.1p4
2390
2391 } else {
2392 // Not a bitfield.
2393
2394 // validate II.
2395
2396 }
2397
2398 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002399 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2400 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002401
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2403 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002404 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002405 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2406 if (!FixedTy.isNull()) {
2407 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2408 T = FixedTy;
2409 } else {
2410 // FIXME: This diagnostic needs work
2411 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2412 InvalidDecl = true;
2413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002414 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002415 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002416 FieldDecl *NewFD;
2417
2418 if (getLangOptions().CPlusPlus) {
2419 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2420 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2421 Loc, II, T, BitWidth);
2422 if (II)
2423 PushOnScopeChains(NewFD, S);
2424 }
2425 else
2426 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002427
Chris Lattner3ff30c82008-06-29 00:02:00 +00002428 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002429
Steve Naroff5912a352007-08-28 20:14:24 +00002430 if (D.getInvalidType() || InvalidDecl)
2431 NewFD->setInvalidDecl();
2432 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002433}
2434
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002435/// TranslateIvarVisibility - Translate visibility from a token ID to an
2436/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002438TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002439 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002440 default: assert(0 && "Unknown visitibility kind");
2441 case tok::objc_private: return ObjCIvarDecl::Private;
2442 case tok::objc_public: return ObjCIvarDecl::Public;
2443 case tok::objc_protected: return ObjCIvarDecl::Protected;
2444 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002445 }
2446}
2447
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002448/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2449/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002450Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002451 SourceLocation DeclStart,
2452 Declarator &D, ExprTy *BitfieldWidth,
2453 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002454 IdentifierInfo *II = D.getIdentifier();
2455 Expr *BitWidth = (Expr*)BitfieldWidth;
2456 SourceLocation Loc = DeclStart;
2457 if (II) Loc = D.getIdentifierLoc();
2458
2459 // FIXME: Unnamed fields can be handled in various different ways, for
2460 // example, unnamed unions inject all members into the struct namespace!
2461
2462
2463 if (BitWidth) {
2464 // TODO: Validate.
2465 //printf("WARNING: BITFIELDS IGNORED!\n");
2466
2467 // 6.7.2.1p3
2468 // 6.7.2.1p4
2469
2470 } else {
2471 // Not a bitfield.
2472
2473 // validate II.
2474
2475 }
2476
2477 QualType T = GetTypeForDeclarator(D, S);
2478 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2479 bool InvalidDecl = false;
2480
2481 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2482 // than a variably modified type.
2483 if (T->isVariablyModifiedType()) {
2484 // FIXME: This diagnostic needs work
2485 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2486 InvalidDecl = true;
2487 }
2488
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002489 // Get the visibility (access control) for this ivar.
2490 ObjCIvarDecl::AccessControl ac =
2491 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2492 : ObjCIvarDecl::None;
2493
2494 // Construct the decl.
2495 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002496 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002497
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002498 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002499 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002500
2501 if (D.getInvalidType() || InvalidDecl)
2502 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002503
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002504 return NewID;
2505}
2506
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002507void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002508 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002509 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002510 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002511 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002512 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2513 assert(EnclosingDecl && "missing record or interface decl");
2514 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2515
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002516 if (Record)
2517 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2518 // Diagnose code like:
2519 // struct S { struct S {} X; };
2520 // We discover this when we complete the outer S. Reject and ignore the
2521 // outer S.
2522 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2523 DefRecord->getKindName());
2524 Diag(RecLoc, diag::err_previous_definition);
2525 Record->setInvalidDecl();
2526 return;
2527 }
2528
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 // Verify that all the fields are okay.
2530 unsigned NumNamedMembers = 0;
2531 llvm::SmallVector<FieldDecl*, 32> RecFields;
2532 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002533
Reid Spencer5f016e22007-07-11 17:01:13 +00002534 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002535
Steve Naroff74216642007-09-14 22:20:54 +00002536 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2537 assert(FD && "missing field decl");
2538
2539 // Remember all fields.
2540 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002541
2542 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002543 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002544
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002546 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002547 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002549 FD->setInvalidDecl();
2550 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 continue;
2552 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002553 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2554 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002555 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002556 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002557 FD->setInvalidDecl();
2558 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002559 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002560 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002562 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002563 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002565 FD->setInvalidDecl();
2566 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 continue;
2568 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002569 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002570 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2571 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002572 FD->setInvalidDecl();
2573 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 continue;
2575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002576 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002577 if (Record)
2578 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2581 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002582 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002583 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2584 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002585 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002586 Record->setHasFlexibleArrayMember(true);
2587 } else {
2588 // If this is a struct/class and this is not the last element, reject
2589 // it. Note that GCC supports variable sized arrays in the middle of
2590 // structures.
2591 if (i != NumFields-1) {
2592 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2593 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002594 FD->setInvalidDecl();
2595 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 continue;
2597 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 // We support flexible arrays at the end of structs in other structs
2599 // as an extension.
2600 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2601 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002602 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002603 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 }
2605 }
2606 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002607 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002608 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002609 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2610 FD->getName());
2611 FD->setInvalidDecl();
2612 EnclosingDecl->setInvalidDecl();
2613 continue;
2614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002615 // Keep track of the number of named members.
2616 if (IdentifierInfo *II = FD->getIdentifier()) {
2617 // Detect duplicate member names.
2618 if (!FieldIDs.insert(II)) {
2619 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2620 // Find the previous decl.
2621 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002622 for (unsigned i = 0; ; ++i) {
2623 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002624 if (RecFields[i]->getIdentifier() == II) {
2625 PrevLoc = RecFields[i]->getLocation();
2626 break;
2627 }
2628 }
2629 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002630 FD->setInvalidDecl();
2631 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 continue;
2633 }
2634 ++NumNamedMembers;
2635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 }
2637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002639 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002640 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002641 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2642 // Sema::ActOnFinishCXXClassDef.
2643 if (!isa<CXXRecordDecl>(Record))
2644 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002645 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002646 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2647 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2648 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2649 else if (ObjCImplementationDecl *IMPDecl =
2650 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2652 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002653 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002654 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002655 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002656
2657 if (Attr)
2658 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002659}
2660
Steve Naroff08d92e42007-09-15 18:49:24 +00002661Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 DeclTy *lastEnumConst,
2663 SourceLocation IdLoc, IdentifierInfo *Id,
2664 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002665 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 EnumConstantDecl *LastEnumConst =
2667 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2668 Expr *Val = static_cast<Expr*>(val);
2669
Chris Lattner31e05722007-08-26 06:24:45 +00002670 // The scope passed in may not be a decl scope. Zip up the scope tree until
2671 // we find one that is.
2672 while ((S->getFlags() & Scope::DeclScope) == 0)
2673 S = S->getParent();
2674
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 // Verify that there isn't already something declared with this name in this
2676 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002677 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002678 // When in C++, we may get a TagDecl with the same name; in this case the
2679 // enum constant will 'hide' the tag.
2680 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2681 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002682 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 if (isa<EnumConstantDecl>(PrevDecl))
2684 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2685 else
2686 Diag(IdLoc, diag::err_redefinition, Id->getName());
2687 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002688 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 return 0;
2690 }
2691 }
2692
2693 llvm::APSInt EnumVal(32);
2694 QualType EltTy;
2695 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002696 // Make sure to promote the operand type to int.
2697 UsualUnaryConversions(Val);
2698
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2700 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002701 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2703 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002704 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002705 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002706 } else {
2707 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002709 }
2710
2711 if (!Val) {
2712 if (LastEnumConst) {
2713 // Assign the last value + 1.
2714 EnumVal = LastEnumConst->getInitVal();
2715 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002716
2717 // Check for overflow on increment.
2718 if (EnumVal < LastEnumConst->getInitVal())
2719 Diag(IdLoc, diag::warn_enum_value_overflow);
2720
Chris Lattnerb7416f92007-08-27 17:37:24 +00002721 EltTy = LastEnumConst->getType();
2722 } else {
2723 // First value, set to zero.
2724 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002725 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002726 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 }
2728
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002729 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002730 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2731 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002732 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002733
2734 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002735 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002736 return New;
2737}
2738
Steve Naroff02408c62008-08-07 14:08:16 +00002739// FIXME: For consistency with ActOnFields(), we should have the parser
2740// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002741void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002742 DeclTy **Elements, unsigned NumElements) {
2743 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002744
Steve Naroff02408c62008-08-07 14:08:16 +00002745 if (Enum && Enum->isDefinition()) {
2746 // Diagnose code like:
2747 // enum e0 {
2748 // E0 = sizeof(enum e0 { E1 })
2749 // };
2750 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2751 Enum->getName());
2752 Diag(EnumLoc, diag::err_previous_definition);
2753 Enum->setInvalidDecl();
2754 return;
2755 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002756 // TODO: If the result value doesn't fit in an int, it must be a long or long
2757 // long value. ISO C does not support this, but GCC does as an extension,
2758 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002759 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002760
Chris Lattnerac609682007-08-28 06:15:15 +00002761 // Verify that all the values are okay, compute the size of the values, and
2762 // reverse the list.
2763 unsigned NumNegativeBits = 0;
2764 unsigned NumPositiveBits = 0;
2765
2766 // Keep track of whether all elements have type int.
2767 bool AllElementsInt = true;
2768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 EnumConstantDecl *EltList = 0;
2770 for (unsigned i = 0; i != NumElements; ++i) {
2771 EnumConstantDecl *ECD =
2772 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2773 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002774
2775 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002776 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002777 assert(InitVal.getBitWidth() >= IntWidth &&
2778 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002779 if (InitVal.getBitWidth() > IntWidth) {
2780 llvm::APSInt V(InitVal);
2781 V.trunc(IntWidth);
2782 V.extend(InitVal.getBitWidth());
2783 if (V != InitVal)
2784 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002785 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002786 }
Chris Lattnerac609682007-08-28 06:15:15 +00002787
2788 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002789 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002790 NumPositiveBits = std::max(NumPositiveBits,
2791 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002792 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002793 NumNegativeBits = std::max(NumNegativeBits,
2794 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002795
Chris Lattnerac609682007-08-28 06:15:15 +00002796 // Keep track of whether every enum element has type int (very commmon).
2797 if (AllElementsInt)
2798 AllElementsInt = ECD->getType() == Context.IntTy;
2799
Reid Spencer5f016e22007-07-11 17:01:13 +00002800 ECD->setNextDeclarator(EltList);
2801 EltList = ECD;
2802 }
2803
Chris Lattnerac609682007-08-28 06:15:15 +00002804 // Figure out the type that should be used for this enum.
2805 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2806 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002807 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002808
2809 if (NumNegativeBits) {
2810 // If there is a negative value, figure out the smallest integer type (of
2811 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002812 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002813 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002814 BestWidth = IntWidth;
2815 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002816 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002817
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002818 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002819 BestType = Context.LongTy;
2820 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002821 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002822
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002823 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002824 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2825 BestType = Context.LongLongTy;
2826 }
2827 }
2828 } else {
2829 // If there is no negative value, figure out which of uint, ulong, ulonglong
2830 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002831 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002832 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002833 BestWidth = IntWidth;
2834 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002835 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002836 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002837 } else {
2838 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002839 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002840 "How could an initializer get larger than ULL?");
2841 BestType = Context.UnsignedLongLongTy;
2842 }
2843 }
2844
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002845 // Loop over all of the enumerator constants, changing their types to match
2846 // the type of the enum if needed.
2847 for (unsigned i = 0; i != NumElements; ++i) {
2848 EnumConstantDecl *ECD =
2849 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2850 if (!ECD) continue; // Already issued a diagnostic.
2851
2852 // Standard C says the enumerators have int type, but we allow, as an
2853 // extension, the enumerators to be larger than int size. If each
2854 // enumerator value fits in an int, type it as an int, otherwise type it the
2855 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2856 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002857 if (ECD->getType() == Context.IntTy) {
2858 // Make sure the init value is signed.
2859 llvm::APSInt IV = ECD->getInitVal();
2860 IV.setIsSigned(true);
2861 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002862 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002863 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002864
2865 // Determine whether the value fits into an int.
2866 llvm::APSInt InitVal = ECD->getInitVal();
2867 bool FitsInInt;
2868 if (InitVal.isUnsigned() || !InitVal.isNegative())
2869 FitsInInt = InitVal.getActiveBits() < IntWidth;
2870 else
2871 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2872
2873 // If it fits into an integer type, force it. Otherwise force it to match
2874 // the enum decl type.
2875 QualType NewTy;
2876 unsigned NewWidth;
2877 bool NewSign;
2878 if (FitsInInt) {
2879 NewTy = Context.IntTy;
2880 NewWidth = IntWidth;
2881 NewSign = true;
2882 } else if (ECD->getType() == BestType) {
2883 // Already the right type!
2884 continue;
2885 } else {
2886 NewTy = BestType;
2887 NewWidth = BestWidth;
2888 NewSign = BestType->isSignedIntegerType();
2889 }
2890
2891 // Adjust the APSInt value.
2892 InitVal.extOrTrunc(NewWidth);
2893 InitVal.setIsSigned(NewSign);
2894 ECD->setInitVal(InitVal);
2895
2896 // Adjust the Expr initializer and type.
2897 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2898 ECD->setType(NewTy);
2899 }
Chris Lattnerac609682007-08-28 06:15:15 +00002900
Chris Lattnere00b18c2007-08-28 18:24:31 +00002901 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002902 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002903}
2904
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002905Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2906 ExprTy *expr) {
2907 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2908
Chris Lattner8e25d862008-03-16 00:16:02 +00002909 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002910}
2911
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002912Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002913 SourceLocation LBrace,
2914 SourceLocation RBrace,
2915 const char *Lang,
2916 unsigned StrSize,
2917 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002918 LinkageSpecDecl::LanguageIDs Language;
2919 Decl *dcl = static_cast<Decl *>(D);
2920 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2921 Language = LinkageSpecDecl::lang_c;
2922 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2923 Language = LinkageSpecDecl::lang_cxx;
2924 else {
2925 Diag(Loc, diag::err_bad_language);
2926 return 0;
2927 }
2928
2929 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002930 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002931}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00002932
2933void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2934 ExprTy *alignment, SourceLocation PragmaLoc,
2935 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2936 Expr *Alignment = static_cast<Expr *>(alignment);
2937
2938 // If specified then alignment must be a "small" power of two.
2939 unsigned AlignmentVal = 0;
2940 if (Alignment) {
2941 llvm::APSInt Val;
2942 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2943 !Val.isPowerOf2() ||
2944 Val.getZExtValue() > 16) {
2945 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2946 delete Alignment;
2947 return; // Ignore
2948 }
2949
2950 AlignmentVal = (unsigned) Val.getZExtValue();
2951 }
2952
2953 switch (Kind) {
2954 case Action::PPK_Default: // pack([n])
2955 PackContext.setAlignment(AlignmentVal);
2956 break;
2957
2958 case Action::PPK_Show: // pack(show)
2959 // Show the current alignment, making sure to show the right value
2960 // for the default.
2961 AlignmentVal = PackContext.getAlignment();
2962 // FIXME: This should come from the target.
2963 if (AlignmentVal == 0)
2964 AlignmentVal = 8;
2965 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2966 break;
2967
2968 case Action::PPK_Push: // pack(push [, id] [, [n])
2969 PackContext.push(Name);
2970 // Set the new alignment if specified.
2971 if (Alignment)
2972 PackContext.setAlignment(AlignmentVal);
2973 break;
2974
2975 case Action::PPK_Pop: // pack(pop [, id] [, n])
2976 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2977 // "#pragma pack(pop, identifier, n) is undefined"
2978 if (Alignment && Name)
2979 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2980
2981 // Do the pop.
2982 if (!PackContext.pop(Name)) {
2983 // If a name was specified then failure indicates the name
2984 // wasn't found. Otherwise failure indicates the stack was
2985 // empty.
2986 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2987 Name ? "no record matching name" : "stack empty");
2988
2989 // FIXME: Warn about popping named records as MSVC does.
2990 } else {
2991 // Pop succeeded, set the new alignment if specified.
2992 if (Alignment)
2993 PackContext.setAlignment(AlignmentVal);
2994 }
2995 break;
2996
2997 default:
2998 assert(0 && "Invalid #pragma pack kind.");
2999 }
3000}
3001
3002bool PragmaPackStack::pop(IdentifierInfo *Name) {
3003 if (Stack.empty())
3004 return false;
3005
3006 // If name is empty just pop top.
3007 if (!Name) {
3008 Alignment = Stack.back().first;
3009 Stack.pop_back();
3010 return true;
3011 }
3012
3013 // Otherwise, find the named record.
3014 for (unsigned i = Stack.size(); i != 0; ) {
3015 --i;
3016 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3017 // Found it, pop up to and including this record.
3018 Alignment = Stack[i].first;
3019 Stack.erase(Stack.begin() + i, Stack.end());
3020 return true;
3021 }
3022 }
3023
3024 return false;
3025}