blob: e32da244de9a28d16d63a8e72bbafca8e015c84b [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar81c7d472008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Argiris Kirtzidis46403632008-08-01 10:35:27 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff6384a012008-04-02 14:35:35 +000032 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
33
Douglas Gregor1d661552008-04-13 21:07:44 +000034 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
35 isa<ObjCInterfaceDecl>(IIDecl) ||
36 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000037 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000038 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000039}
40
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000041DeclContext *Sema::getDCParent(DeclContext *DC) {
42 // If CurContext is a ObjC method, getParent() will return NULL.
43 if (isa<ObjCMethodDecl>(DC))
44 return Context.getTranslationUnitDecl();
45
46 // A C++ inline method is parsed *after* the topmost class it was declared in
47 // is fully parsed (it's "complete").
48 // The parsing of a C++ inline method happens at the declaration context of
49 // the topmost (non-nested) class it is declared in.
50 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
51 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
52 DC = MD->getParent();
53 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
54 DC = RD;
55
56 // Return the declaration context of the topmost class the inline method is
57 // declared in.
58 return DC;
59 }
60
61 return DC->getParent();
62}
63
Chris Lattneref87a202008-04-22 18:39:57 +000064void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000065 assert(getDCParent(DC) == CurContext &&
66 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000067 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000068}
69
Chris Lattnerf3874bc2008-04-06 04:47:34 +000070void Sema::PopDeclContext() {
71 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000072 CurContext = getDCParent(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000073}
74
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000075/// Add this decl to the scope shadowed decl chains.
76void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000077 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000078
79 // C++ [basic.scope]p4:
80 // -- exactly one declaration shall declare a class name or
81 // enumeration name that is not a typedef name and the other
82 // declarations shall all refer to the same object or
83 // enumerator, or all refer to functions and function templates;
84 // in this case the class name or enumeration name is hidden.
85 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
86 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +000087 IdentifierResolver::iterator
88 I = IdResolver.begin(TD->getIdentifier(),
89 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +000090 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argiris Kirtzidis94805232008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096 return;
97 }
98 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000100}
101
Steve Naroff9637a9b2007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000105
Chris Lattner4b009652007-07-25 00:24:17 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000115
Chris Lattner4b009652007-07-25 00:24:17 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Ted Kremenek40e70e72008-09-03 18:03:35 +0000119 // We only want to remove the decls from the identifier decl chains for
120 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000123
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000127 }
128}
129
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000136
Steve Naroff6384a012008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000138}
139
Steve Naroffe57c21a2008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000141/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000148
Chris Lattner4b009652007-07-25 00:24:17 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179 return 0;
180}
181
Chris Lattnera9c87f22008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Chris Lattner4b009652007-07-25 00:24:17 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Chris Lattnerb23469f2008-09-28 05:54:29 +0000198 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000199 InitBuiltinVaListType();
200
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000201 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000202 FunctionDecl *New = FunctionDecl::Create(Context,
203 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000204 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000205 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000206
Chris Lattnera9c87f22008-05-05 22:18:14 +0000207 // Create Decl objects for each parameter, adding them to the
208 // FunctionDecl.
209 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
210 llvm::SmallVector<ParmVarDecl*, 16> Params;
211 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
212 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
213 FT->getArgType(i), VarDecl::None, 0,
214 0));
215 New->setParams(&Params[0], Params.size());
216 }
217
218
219
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000220 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000221 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000222 return New;
223}
224
225/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
226/// and scope as a previous declaration 'Old'. Figure out how to resolve this
227/// situation, merging decls or emitting diagnostics as appropriate.
228///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000229TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000230 // Allow multiple definitions for ObjC built-in typedefs.
231 // FIXME: Verify the underlying types are equivalent!
232 if (getLangOptions().ObjC1) {
233 const IdentifierInfo *typeIdent = New->getIdentifier();
234 if (typeIdent == Ident_id) {
235 Context.setObjCIdType(New);
236 return New;
237 } else if (typeIdent == Ident_Class) {
238 Context.setObjCClassType(New);
239 return New;
240 } else if (typeIdent == Ident_SEL) {
241 Context.setObjCSelType(New);
242 return New;
243 } else if (typeIdent == Ident_Protocol) {
244 Context.setObjCProtoType(New->getUnderlyingType());
245 return New;
246 }
247 // Fall through - the typedef name was not a builtin type.
248 }
Chris Lattner4b009652007-07-25 00:24:17 +0000249 // Verify the old decl was also a typedef.
250 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
251 if (!Old) {
252 Diag(New->getLocation(), diag::err_redefinition_different_kind,
253 New->getName());
254 Diag(OldD->getLocation(), diag::err_previous_definition);
255 return New;
256 }
257
Chris Lattnerbef8d622008-07-25 18:44:27 +0000258 // If the typedef types are not identical, reject them in all languages and
259 // with any extensions enabled.
260 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
261 Context.getCanonicalType(Old->getUnderlyingType()) !=
262 Context.getCanonicalType(New->getUnderlyingType())) {
263 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
264 New->getUnderlyingType().getAsString(),
265 Old->getUnderlyingType().getAsString());
266 Diag(Old->getLocation(), diag::err_previous_definition);
267 return Old;
268 }
269
Eli Friedman324d5032008-06-11 06:20:39 +0000270 if (getLangOptions().Microsoft) return New;
271
Steve Naroffa9eae582008-01-30 23:46:05 +0000272 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
273 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
274 // *either* declaration is in a system header. The code below implements
275 // this adhoc compatibility rule. FIXME: The following code will not
276 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000277 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
278 SourceManager &SrcMgr = Context.getSourceManager();
279 if (SrcMgr.isInSystemHeader(Old->getLocation()))
280 return New;
281 if (SrcMgr.isInSystemHeader(New->getLocation()))
282 return New;
283 }
Eli Friedman324d5032008-06-11 06:20:39 +0000284
Ted Kremenek64845ce2008-05-23 21:28:18 +0000285 Diag(New->getLocation(), diag::err_redefinition, New->getName());
286 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000287 return New;
288}
289
Chris Lattner6953a072008-06-26 18:38:35 +0000290/// DeclhasAttr - returns true if decl Declaration already has the target
291/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000292static bool DeclHasAttr(const Decl *decl, const Attr *target) {
293 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
294 if (attr->getKind() == target->getKind())
295 return true;
296
297 return false;
298}
299
300/// MergeAttributes - append attributes from the Old decl to the New one.
301static void MergeAttributes(Decl *New, Decl *Old) {
302 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
303
Chris Lattner402b3372008-03-03 03:28:21 +0000304 while (attr) {
305 tmp = attr;
306 attr = attr->getNext();
307
308 if (!DeclHasAttr(New, tmp)) {
309 New->addAttr(tmp);
310 } else {
311 tmp->setNext(0);
312 delete(tmp);
313 }
314 }
Nuno Lopes77654342008-06-01 22:53:53 +0000315
316 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000317}
318
Chris Lattner3e254fb2008-04-08 04:40:51 +0000319/// MergeFunctionDecl - We just parsed a function 'New' from
320/// declarator D which has the same name and scope as a previous
321/// declaration 'Old'. Figure out how to resolve this situation,
322/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000323/// Redeclaration will be set true if thisNew is a redeclaration OldD.
324FunctionDecl *
325Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
326 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000327 // Verify the old decl was also a function.
328 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
329 if (!Old) {
330 Diag(New->getLocation(), diag::err_redefinition_different_kind,
331 New->getName());
332 Diag(OldD->getLocation(), diag::err_previous_definition);
333 return New;
334 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000335
Chris Lattner42a21742008-04-06 23:10:54 +0000336 QualType OldQType = Context.getCanonicalType(Old->getType());
337 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000338
Chris Lattner3e254fb2008-04-08 04:40:51 +0000339 // C++ [dcl.fct]p3:
340 // All declarations for a function shall agree exactly in both the
341 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000342 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
343 MergeAttributes(New, Old);
344 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000345 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000346 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000347
348 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000349 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000350 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000351 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000352 MergeAttributes(New, Old);
353 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000354 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000355 }
Chris Lattner1470b072007-11-06 06:07:26 +0000356
Steve Naroff6c9e7922008-01-16 15:01:34 +0000357 // A function that has already been declared has been redeclared or defined
358 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000359 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000360 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000361 PrevDiag = diag::err_previous_definition;
362 else if (Old->isImplicit())
363 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000364 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000365 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000366
Chris Lattner4b009652007-07-25 00:24:17 +0000367 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
368 // TODO: This is totally simplistic. It should handle merging functions
369 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000370 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
371 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000372 return New;
373}
374
Steve Naroffb5e78152008-08-08 17:50:35 +0000375/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000376static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000377 if (VD->isFileVarDecl())
378 return (!VD->getInit() &&
379 (VD->getStorageClass() == VarDecl::None ||
380 VD->getStorageClass() == VarDecl::Static));
381 return false;
382}
383
384/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
385/// when dealing with C "tentative" external object definitions (C99 6.9.2).
386void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
387 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000388 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000389
390 for (IdentifierResolver::iterator
391 I = IdResolver.begin(VD->getIdentifier(),
392 VD->getDeclContext(), false/*LookInParentCtx*/),
393 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000394 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000395 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
396
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000397 // Handle the following case:
398 // int a[10];
399 // int a[]; - the code below makes sure we set the correct type.
400 // int a[11]; - this is an error, size isn't 10.
401 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
402 OldDecl->getType()->isConstantArrayType())
403 VD->setType(OldDecl->getType());
404
Steve Naroffb5e78152008-08-08 17:50:35 +0000405 // Check for "tentative" definitions. We can't accomplish this in
406 // MergeVarDecl since the initializer hasn't been attached.
407 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
408 continue;
409
410 // Handle __private_extern__ just like extern.
411 if (OldDecl->getStorageClass() != VarDecl::Extern &&
412 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
413 VD->getStorageClass() != VarDecl::Extern &&
414 VD->getStorageClass() != VarDecl::PrivateExtern) {
415 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
416 Diag(OldDecl->getLocation(), diag::err_previous_definition);
417 }
418 }
419 }
420}
421
Chris Lattner4b009652007-07-25 00:24:17 +0000422/// MergeVarDecl - We just parsed a variable 'New' which has the same name
423/// and scope as a previous declaration 'Old'. Figure out how to resolve this
424/// situation, merging decls or emitting diagnostics as appropriate.
425///
Steve Naroffb5e78152008-08-08 17:50:35 +0000426/// Tentative definition rules (C99 6.9.2p2) are checked by
427/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
428/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000429///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000430VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000431 // Verify the old decl was also a variable.
432 VarDecl *Old = dyn_cast<VarDecl>(OldD);
433 if (!Old) {
434 Diag(New->getLocation(), diag::err_redefinition_different_kind,
435 New->getName());
436 Diag(OldD->getLocation(), diag::err_previous_definition);
437 return New;
438 }
Chris Lattner402b3372008-03-03 03:28:21 +0000439
440 MergeAttributes(New, Old);
441
Chris Lattner4b009652007-07-25 00:24:17 +0000442 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000443 QualType OldCType = Context.getCanonicalType(Old->getType());
444 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000445 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000446 Diag(New->getLocation(), diag::err_redefinition, New->getName());
447 Diag(Old->getLocation(), diag::err_previous_definition);
448 return New;
449 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000450 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
451 if (New->getStorageClass() == VarDecl::Static &&
452 (Old->getStorageClass() == VarDecl::None ||
453 Old->getStorageClass() == VarDecl::Extern)) {
454 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
455 Diag(Old->getLocation(), diag::err_previous_definition);
456 return New;
457 }
458 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
459 if (New->getStorageClass() != VarDecl::Static &&
460 Old->getStorageClass() == VarDecl::Static) {
461 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
462 Diag(Old->getLocation(), diag::err_previous_definition);
463 return New;
464 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000465 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
466 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000467 Diag(New->getLocation(), diag::err_redefinition, New->getName());
468 Diag(Old->getLocation(), diag::err_previous_definition);
469 }
470 return New;
471}
472
Chris Lattner3e254fb2008-04-08 04:40:51 +0000473/// CheckParmsForFunctionDef - Check that the parameters of the given
474/// function are appropriate for the definition of a function. This
475/// takes care of any checks that cannot be performed on the
476/// declaration itself, e.g., that the types of each of the function
477/// parameters are complete.
478bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
479 bool HasInvalidParm = false;
480 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
481 ParmVarDecl *Param = FD->getParamDecl(p);
482
483 // C99 6.7.5.3p4: the parameters in a parameter type list in a
484 // function declarator that is part of a function definition of
485 // that function shall not have incomplete type.
486 if (Param->getType()->isIncompleteType() &&
487 !Param->isInvalidDecl()) {
488 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
489 Param->getType().getAsString());
490 Param->setInvalidDecl();
491 HasInvalidParm = true;
492 }
493 }
494
495 return HasInvalidParm;
496}
497
Chris Lattner4b009652007-07-25 00:24:17 +0000498/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
499/// no declarator (e.g. "struct foo;") is parsed.
500Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
501 // TODO: emit error on 'int;' or 'const enum foo;'.
502 // TODO: emit error on 'typedef int;'
503 // if (!DS.isMissingDeclaratorOk()) Diag(...);
504
Steve Naroffedafc0b2007-11-17 21:37:36 +0000505 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000506}
507
Steve Narofff0b23542008-01-10 22:15:12 +0000508bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000509 // Get the type before calling CheckSingleAssignmentConstraints(), since
510 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000511 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000512
Chris Lattner005ed752008-01-04 18:04:52 +0000513 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
514 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
515 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000516}
517
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000518bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000519 const ArrayType *AT = Context.getAsArrayType(DeclT);
520
521 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000522 // C99 6.7.8p14. We have an array of character type with unknown size
523 // being initialized to a string literal.
524 llvm::APSInt ConstVal(32);
525 ConstVal = strLiteral->getByteLength() + 1;
526 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000527 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000528 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000529 } else {
530 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000531 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000532 // FIXME: Avoid truncation for 64-bit length strings.
533 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000534 Diag(strLiteral->getSourceRange().getBegin(),
535 diag::warn_initializer_string_for_char_array_too_long,
536 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000537 }
538 // Set type from "char *" to "constant array of char".
539 strLiteral->setType(DeclT);
540 // For now, we always return false (meaning success).
541 return false;
542}
543
544StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000545 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000546 if (AT && AT->getElementType()->isCharType()) {
547 return dyn_cast<StringLiteral>(Init);
548 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000549 return 0;
550}
551
Steve Narofff3cb5142008-01-25 00:51:06 +0000552bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000553 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
554 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000555 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000556 return Diag(VAT->getSizeExpr()->getLocStart(),
557 diag::err_variable_object_no_init,
558 VAT->getSizeExpr()->getSourceRange());
559
Steve Naroffcb69fb72007-12-10 22:44:33 +0000560 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
561 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000562 // FIXME: Handle wide strings
563 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
564 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000565
Steve Naroffb2f72412008-09-29 20:07:05 +0000566 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000567 if (DeclType->isArrayType())
568 return Diag(Init->getLocStart(),
569 diag::err_array_init_list_required,
570 Init->getSourceRange());
571
Steve Narofff0b23542008-01-10 22:15:12 +0000572 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000573 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000574
Steve Naroffc4d4a482008-05-01 22:18:59 +0000575 InitListChecker CheckInitList(this, InitList, DeclType);
576 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000577}
578
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000579Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000580Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000581 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000582 IdentifierInfo *II = D.getIdentifier();
583
584 // All of these full declarators require an identifier. If it doesn't have
585 // one, the ParsedFreeStandingDeclSpec action should be used.
586 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000587 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000588 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000589 D.getDeclSpec().getSourceRange(), D.getSourceRange());
590 return 0;
591 }
592
Chris Lattnera7549902007-08-26 06:24:45 +0000593 // The scope passed in may not be a decl scope. Zip up the scope tree until
594 // we find one that is.
595 while ((S->getFlags() & Scope::DeclScope) == 0)
596 S = S->getParent();
597
Chris Lattner4b009652007-07-25 00:24:17 +0000598 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000599 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000600 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000601 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000602
603 // In C++, the previous declaration we find might be a tag type
604 // (class or enum). In this case, the new declaration will hide the
605 // tag type.
606 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
607 PrevDecl = 0;
608
Chris Lattner82bb4792007-11-14 06:34:38 +0000609 QualType R = GetTypeForDeclarator(D, S);
610 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
611
Chris Lattner4b009652007-07-25 00:24:17 +0000612 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000613 // Check that there are no default arguments (C++ only).
614 if (getLangOptions().CPlusPlus)
615 CheckExtraCXXDefaultArguments(D);
616
Chris Lattner82bb4792007-11-14 06:34:38 +0000617 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000618 if (!NewTD) return 0;
619
620 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000621 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000622 // Merge the decl with the existing one if appropriate. If the decl is
623 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000624 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000625 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
626 if (NewTD == 0) return 0;
627 }
628 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000629 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000630 // C99 6.7.7p2: If a typedef name specifies a variably modified type
631 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000632 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
633 // FIXME: Diagnostic needs to be fixed.
634 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000635 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000636 }
637 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000638 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000639 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000640 switch (D.getDeclSpec().getStorageClassSpec()) {
641 default: assert(0 && "Unknown storage class!");
642 case DeclSpec::SCS_auto:
643 case DeclSpec::SCS_register:
644 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
645 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000646 InvalidDecl = true;
647 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000648 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
649 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
650 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000651 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000652 }
653
Chris Lattner4c7802b2008-03-15 21:24:04 +0000654 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000655 FunctionDecl *NewFD;
656 if (D.getContext() == Declarator::MemberContext) {
657 // This is a C++ method declaration.
658 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
659 D.getIdentifierLoc(), II, R,
660 (SC == FunctionDecl::Static), isInline,
661 LastDeclarator);
662 } else {
663 NewFD = FunctionDecl::Create(Context, CurContext,
664 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000665 II, R, SC, isInline, LastDeclarator,
666 // FIXME: Move to DeclGroup...
667 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000668 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000669 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000670 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000671
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000672 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000673 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000674 // The parser guarantees this is a string.
675 StringLiteral *SE = cast<StringLiteral>(E);
676 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
677 SE->getByteLength())));
678 }
679
Chris Lattner3e254fb2008-04-08 04:40:51 +0000680 // Copy the parameter declarations from the declarator D to
681 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000682 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000683 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
684
685 // Create Decl objects for each parameter, adding them to the
686 // FunctionDecl.
687 llvm::SmallVector<ParmVarDecl*, 16> Params;
688
689 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
690 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000691 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000692 // We let through "const void" here because Sema::GetTypeForDeclarator
693 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000694 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
695 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000696 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
697 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000698 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
699
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000700 // In C++, the empty parameter-type-list must be spelled "void"; a
701 // typedef of void is not permitted.
702 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000703 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000704 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
705 }
706
Eli Friedman769e7302008-08-25 21:31:01 +0000707 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000708 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
709 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
710 }
711
712 NewFD->setParams(&Params[0], Params.size());
713 }
714
Steve Narofff8a09432008-01-09 23:34:55 +0000715 // Merge the decl with the existing one if appropriate. Since C functions
716 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000717 if (PrevDecl &&
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000718 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000719 bool Redeclaration = false;
720 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000721 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000722 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000723 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000724 }
Chris Lattner4b009652007-07-25 00:24:17 +0000725 }
726 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000727
728 // In C++, check default arguments now that we have merged decls.
729 if (getLangOptions().CPlusPlus)
730 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000731 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000732 // Check that there are no default arguments (C++ only).
733 if (getLangOptions().CPlusPlus)
734 CheckExtraCXXDefaultArguments(D);
735
Ted Kremenek42730c52008-01-07 19:49:32 +0000736 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000737 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
738 D.getIdentifier()->getName());
739 InvalidDecl = true;
740 }
Chris Lattner4b009652007-07-25 00:24:17 +0000741
742 VarDecl *NewVD;
743 VarDecl::StorageClass SC;
744 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000745 default: assert(0 && "Unknown storage class!");
746 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
747 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
748 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
749 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
750 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
751 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000752 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000753 if (D.getContext() == Declarator::MemberContext) {
754 assert(SC == VarDecl::Static && "Invalid storage class for member!");
755 // This is a static data member for a C++ class.
756 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
757 D.getIdentifierLoc(), II,
758 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000759 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000760 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000761 if (S->getFnParent() == 0) {
762 // C99 6.9p2: The storage-class specifiers auto and register shall not
763 // appear in the declaration specifiers in an external declaration.
764 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
765 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
766 R.getAsString());
767 InvalidDecl = true;
768 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000769 }
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000770 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000771 II, R, SC, LastDeclarator,
772 // FIXME: Move to DeclGroup...
773 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000774 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +0000775 }
Chris Lattner4b009652007-07-25 00:24:17 +0000776 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000777 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000778
Daniel Dunbarced89142008-08-06 00:03:29 +0000779 // Handle GNU asm-label extension (encoded as an attribute).
780 if (Expr *E = (Expr*) D.getAsmLabel()) {
781 // The parser guarantees this is a string.
782 StringLiteral *SE = cast<StringLiteral>(E);
783 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
784 SE->getByteLength())));
785 }
786
Nate Begemanea583262008-03-14 18:07:10 +0000787 // Emit an error if an address space was applied to decl with local storage.
788 // This includes arrays of objects with address space qualifiers, but not
789 // automatic variables that point to other address spaces.
790 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000791 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
792 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
793 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000794 }
Steve Narofff8a09432008-01-09 23:34:55 +0000795 // Merge the decl with the existing one if appropriate. If the decl is
796 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000797 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000798 NewVD = MergeVarDecl(NewVD, PrevDecl);
799 if (NewVD == 0) return 0;
800 }
Chris Lattner4b009652007-07-25 00:24:17 +0000801 New = NewVD;
802 }
803
804 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000805 if (II)
806 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000807 // If any semantic error occurred, mark the decl as invalid.
808 if (D.getInvalidType() || InvalidDecl)
809 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000810
811 return New;
812}
813
Eli Friedman02c22ce2008-05-20 13:48:25 +0000814bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
815 switch (Init->getStmtClass()) {
816 default:
817 Diag(Init->getExprLoc(),
818 diag::err_init_element_not_constant, Init->getSourceRange());
819 return true;
820 case Expr::ParenExprClass: {
821 const ParenExpr* PE = cast<ParenExpr>(Init);
822 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
823 }
824 case Expr::CompoundLiteralExprClass:
825 return cast<CompoundLiteralExpr>(Init)->isFileScope();
826 case Expr::DeclRefExprClass: {
827 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000828 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
829 if (VD->hasGlobalStorage())
830 return false;
831 Diag(Init->getExprLoc(),
832 diag::err_init_element_not_constant, Init->getSourceRange());
833 return true;
834 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000835 if (isa<FunctionDecl>(D))
836 return false;
837 Diag(Init->getExprLoc(),
838 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000839 return true;
840 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000841 case Expr::MemberExprClass: {
842 const MemberExpr *M = cast<MemberExpr>(Init);
843 if (M->isArrow())
844 return CheckAddressConstantExpression(M->getBase());
845 return CheckAddressConstantExpressionLValue(M->getBase());
846 }
847 case Expr::ArraySubscriptExprClass: {
848 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
849 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
850 return CheckAddressConstantExpression(ASE->getBase()) ||
851 CheckArithmeticConstantExpression(ASE->getIdx());
852 }
853 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000854 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000855 return false;
856 case Expr::UnaryOperatorClass: {
857 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
858
859 // C99 6.6p9
860 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000861 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000862
863 Diag(Init->getExprLoc(),
864 diag::err_init_element_not_constant, Init->getSourceRange());
865 return true;
866 }
867 }
868}
869
870bool Sema::CheckAddressConstantExpression(const Expr* Init) {
871 switch (Init->getStmtClass()) {
872 default:
873 Diag(Init->getExprLoc(),
874 diag::err_init_element_not_constant, Init->getSourceRange());
875 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +0000876 case Expr::ParenExprClass:
877 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000878 case Expr::StringLiteralClass:
879 case Expr::ObjCStringLiteralClass:
880 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +0000881 case Expr::CallExprClass:
882 // __builtin___CFStringMakeConstantString is a valid constant l-value.
883 if (cast<CallExpr>(Init)->isBuiltinCall() ==
884 Builtin::BI__builtin___CFStringMakeConstantString)
885 return false;
886
887 Diag(Init->getExprLoc(),
888 diag::err_init_element_not_constant, Init->getSourceRange());
889 return true;
890
Eli Friedman02c22ce2008-05-20 13:48:25 +0000891 case Expr::UnaryOperatorClass: {
892 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
893
894 // C99 6.6p9
895 if (Exp->getOpcode() == UnaryOperator::AddrOf)
896 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
897
898 if (Exp->getOpcode() == UnaryOperator::Extension)
899 return CheckAddressConstantExpression(Exp->getSubExpr());
900
901 Diag(Init->getExprLoc(),
902 diag::err_init_element_not_constant, Init->getSourceRange());
903 return true;
904 }
905 case Expr::BinaryOperatorClass: {
906 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
907 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
908
909 Expr *PExp = Exp->getLHS();
910 Expr *IExp = Exp->getRHS();
911 if (IExp->getType()->isPointerType())
912 std::swap(PExp, IExp);
913
914 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
915 return CheckAddressConstantExpression(PExp) ||
916 CheckArithmeticConstantExpression(IExp);
917 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000918 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000919 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000920 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000921 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
922 // Check for implicit promotion
923 if (SubExpr->getType()->isFunctionType() ||
924 SubExpr->getType()->isArrayType())
925 return CheckAddressConstantExpressionLValue(SubExpr);
926 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000927
928 // Check for pointer->pointer cast
929 if (SubExpr->getType()->isPointerType())
930 return CheckAddressConstantExpression(SubExpr);
931
Eli Friedman1fad3c62008-08-25 20:46:57 +0000932 if (SubExpr->getType()->isIntegralType()) {
933 // Check for the special-case of a pointer->int->pointer cast;
934 // this isn't standard, but some code requires it. See
935 // PR2720 for an example.
936 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
937 if (SubCast->getSubExpr()->getType()->isPointerType()) {
938 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
939 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
940 if (IntWidth >= PointerWidth) {
941 return CheckAddressConstantExpression(SubCast->getSubExpr());
942 }
943 }
944 }
945 }
946 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000947 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000948 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000949
950 Diag(Init->getExprLoc(),
951 diag::err_init_element_not_constant, Init->getSourceRange());
952 return true;
953 }
954 case Expr::ConditionalOperatorClass: {
955 // FIXME: Should we pedwarn here?
956 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
957 if (!Exp->getCond()->getType()->isArithmeticType()) {
958 Diag(Init->getExprLoc(),
959 diag::err_init_element_not_constant, Init->getSourceRange());
960 return true;
961 }
962 if (CheckArithmeticConstantExpression(Exp->getCond()))
963 return true;
964 if (Exp->getLHS() &&
965 CheckAddressConstantExpression(Exp->getLHS()))
966 return true;
967 return CheckAddressConstantExpression(Exp->getRHS());
968 }
969 case Expr::AddrLabelExprClass:
970 return false;
971 }
972}
973
Eli Friedman998dffb2008-06-09 05:05:07 +0000974static const Expr* FindExpressionBaseAddress(const Expr* E);
975
976static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
977 switch (E->getStmtClass()) {
978 default:
979 return E;
980 case Expr::ParenExprClass: {
981 const ParenExpr* PE = cast<ParenExpr>(E);
982 return FindExpressionBaseAddressLValue(PE->getSubExpr());
983 }
984 case Expr::MemberExprClass: {
985 const MemberExpr *M = cast<MemberExpr>(E);
986 if (M->isArrow())
987 return FindExpressionBaseAddress(M->getBase());
988 return FindExpressionBaseAddressLValue(M->getBase());
989 }
990 case Expr::ArraySubscriptExprClass: {
991 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
992 return FindExpressionBaseAddress(ASE->getBase());
993 }
994 case Expr::UnaryOperatorClass: {
995 const UnaryOperator *Exp = cast<UnaryOperator>(E);
996
997 if (Exp->getOpcode() == UnaryOperator::Deref)
998 return FindExpressionBaseAddress(Exp->getSubExpr());
999
1000 return E;
1001 }
1002 }
1003}
1004
1005static const Expr* FindExpressionBaseAddress(const Expr* E) {
1006 switch (E->getStmtClass()) {
1007 default:
1008 return E;
1009 case Expr::ParenExprClass: {
1010 const ParenExpr* PE = cast<ParenExpr>(E);
1011 return FindExpressionBaseAddress(PE->getSubExpr());
1012 }
1013 case Expr::UnaryOperatorClass: {
1014 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1015
1016 // C99 6.6p9
1017 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1018 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1019
1020 if (Exp->getOpcode() == UnaryOperator::Extension)
1021 return FindExpressionBaseAddress(Exp->getSubExpr());
1022
1023 return E;
1024 }
1025 case Expr::BinaryOperatorClass: {
1026 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1027
1028 Expr *PExp = Exp->getLHS();
1029 Expr *IExp = Exp->getRHS();
1030 if (IExp->getType()->isPointerType())
1031 std::swap(PExp, IExp);
1032
1033 return FindExpressionBaseAddress(PExp);
1034 }
1035 case Expr::ImplicitCastExprClass: {
1036 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1037
1038 // Check for implicit promotion
1039 if (SubExpr->getType()->isFunctionType() ||
1040 SubExpr->getType()->isArrayType())
1041 return FindExpressionBaseAddressLValue(SubExpr);
1042
1043 // Check for pointer->pointer cast
1044 if (SubExpr->getType()->isPointerType())
1045 return FindExpressionBaseAddress(SubExpr);
1046
1047 // We assume that we have an arithmetic expression here;
1048 // if we don't, we'll figure it out later
1049 return 0;
1050 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001051 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001052 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1053
1054 // Check for pointer->pointer cast
1055 if (SubExpr->getType()->isPointerType())
1056 return FindExpressionBaseAddress(SubExpr);
1057
1058 // We assume that we have an arithmetic expression here;
1059 // if we don't, we'll figure it out later
1060 return 0;
1061 }
1062 }
1063}
1064
Eli Friedman02c22ce2008-05-20 13:48:25 +00001065bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1066 switch (Init->getStmtClass()) {
1067 default:
1068 Diag(Init->getExprLoc(),
1069 diag::err_init_element_not_constant, Init->getSourceRange());
1070 return true;
1071 case Expr::ParenExprClass: {
1072 const ParenExpr* PE = cast<ParenExpr>(Init);
1073 return CheckArithmeticConstantExpression(PE->getSubExpr());
1074 }
1075 case Expr::FloatingLiteralClass:
1076 case Expr::IntegerLiteralClass:
1077 case Expr::CharacterLiteralClass:
1078 case Expr::ImaginaryLiteralClass:
1079 case Expr::TypesCompatibleExprClass:
1080 case Expr::CXXBoolLiteralExprClass:
1081 return false;
1082 case Expr::CallExprClass: {
1083 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001084
1085 // Allow any constant foldable calls to builtins.
1086 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001087 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001088
Eli Friedman02c22ce2008-05-20 13:48:25 +00001089 Diag(Init->getExprLoc(),
1090 diag::err_init_element_not_constant, Init->getSourceRange());
1091 return true;
1092 }
1093 case Expr::DeclRefExprClass: {
1094 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1095 if (isa<EnumConstantDecl>(D))
1096 return false;
1097 Diag(Init->getExprLoc(),
1098 diag::err_init_element_not_constant, Init->getSourceRange());
1099 return true;
1100 }
1101 case Expr::CompoundLiteralExprClass:
1102 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1103 // but vectors are allowed to be magic.
1104 if (Init->getType()->isVectorType())
1105 return false;
1106 Diag(Init->getExprLoc(),
1107 diag::err_init_element_not_constant, Init->getSourceRange());
1108 return true;
1109 case Expr::UnaryOperatorClass: {
1110 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1111
1112 switch (Exp->getOpcode()) {
1113 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1114 // See C99 6.6p3.
1115 default:
1116 Diag(Init->getExprLoc(),
1117 diag::err_init_element_not_constant, Init->getSourceRange());
1118 return true;
1119 case UnaryOperator::SizeOf:
1120 case UnaryOperator::AlignOf:
1121 case UnaryOperator::OffsetOf:
1122 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1123 // See C99 6.5.3.4p2 and 6.6p3.
1124 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1125 return false;
1126 Diag(Init->getExprLoc(),
1127 diag::err_init_element_not_constant, Init->getSourceRange());
1128 return true;
1129 case UnaryOperator::Extension:
1130 case UnaryOperator::LNot:
1131 case UnaryOperator::Plus:
1132 case UnaryOperator::Minus:
1133 case UnaryOperator::Not:
1134 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1135 }
1136 }
1137 case Expr::SizeOfAlignOfTypeExprClass: {
1138 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1139 // Special check for void types, which are allowed as an extension
1140 if (Exp->getArgumentType()->isVoidType())
1141 return false;
1142 // alignof always evaluates to a constant.
1143 // FIXME: is sizeof(int[3.0]) a constant expression?
1144 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1145 Diag(Init->getExprLoc(),
1146 diag::err_init_element_not_constant, Init->getSourceRange());
1147 return true;
1148 }
1149 return false;
1150 }
1151 case Expr::BinaryOperatorClass: {
1152 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1153
1154 if (Exp->getLHS()->getType()->isArithmeticType() &&
1155 Exp->getRHS()->getType()->isArithmeticType()) {
1156 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1157 CheckArithmeticConstantExpression(Exp->getRHS());
1158 }
1159
Eli Friedman998dffb2008-06-09 05:05:07 +00001160 if (Exp->getLHS()->getType()->isPointerType() &&
1161 Exp->getRHS()->getType()->isPointerType()) {
1162 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1163 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1164
1165 // Only allow a null (constant integer) base; we could
1166 // allow some additional cases if necessary, but this
1167 // is sufficient to cover offsetof-like constructs.
1168 if (!LHSBase && !RHSBase) {
1169 return CheckAddressConstantExpression(Exp->getLHS()) ||
1170 CheckAddressConstantExpression(Exp->getRHS());
1171 }
1172 }
1173
Eli Friedman02c22ce2008-05-20 13:48:25 +00001174 Diag(Init->getExprLoc(),
1175 diag::err_init_element_not_constant, Init->getSourceRange());
1176 return true;
1177 }
1178 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001179 case Expr::ExplicitCastExprClass: {
1180 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001181 if (SubExpr->getType()->isArithmeticType())
1182 return CheckArithmeticConstantExpression(SubExpr);
1183
Eli Friedman266df142008-09-02 09:37:00 +00001184 if (SubExpr->getType()->isPointerType()) {
1185 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1186 // If the pointer has a null base, this is an offsetof-like construct
1187 if (!Base)
1188 return CheckAddressConstantExpression(SubExpr);
1189 }
1190
Eli Friedmand662caa2008-09-01 22:08:17 +00001191 Diag(Init->getExprLoc(),
1192 diag::err_init_element_not_constant, Init->getSourceRange());
1193 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001194 }
1195 case Expr::ConditionalOperatorClass: {
1196 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001197
1198 // If GNU extensions are disabled, we require all operands to be arithmetic
1199 // constant expressions.
1200 if (getLangOptions().NoExtensions) {
1201 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1202 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1203 CheckArithmeticConstantExpression(Exp->getRHS());
1204 }
1205
1206 // Otherwise, we have to emulate some of the behavior of fold here.
1207 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1208 // because it can constant fold things away. To retain compatibility with
1209 // GCC code, we see if we can fold the condition to a constant (which we
1210 // should always be able to do in theory). If so, we only require the
1211 // specified arm of the conditional to be a constant. This is a horrible
1212 // hack, but is require by real world code that uses __builtin_constant_p.
1213 APValue Val;
1214 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1215 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1216 // won't be able to either. Use it to emit the diagnostic though.
1217 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1218 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1219 return Res;
1220 }
1221
1222 // Verify that the side following the condition is also a constant.
1223 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1224 if (Val.getInt() == 0)
1225 std::swap(TrueSide, FalseSide);
1226
1227 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001228 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001229
1230 // Okay, the evaluated side evaluates to a constant, so we accept this.
1231 // Check to see if the other side is obviously not a constant. If so,
1232 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001233 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001234 Diag(Init->getExprLoc(),
1235 diag::ext_typecheck_expression_not_constant_but_accepted,
1236 FalseSide->getSourceRange());
1237 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001238 }
1239 }
1240}
1241
1242bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001243 Init = Init->IgnoreParens();
1244
Eli Friedman02c22ce2008-05-20 13:48:25 +00001245 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1246 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1247 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1248
Nuno Lopese7280452008-07-07 16:46:50 +00001249 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1250 return CheckForConstantInitializer(e->getInitializer(), DclT);
1251
Eli Friedman02c22ce2008-05-20 13:48:25 +00001252 if (Init->getType()->isReferenceType()) {
Chris Lattner94d45412008-10-06 05:42:39 +00001253 // FIXME: Work out how the heck references work.
Eli Friedman02c22ce2008-05-20 13:48:25 +00001254 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001255 }
1256
1257 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1258 unsigned numInits = Exp->getNumInits();
1259 for (unsigned i = 0; i < numInits; i++) {
1260 // FIXME: Need to get the type of the declaration for C++,
1261 // because it could be a reference?
1262 if (CheckForConstantInitializer(Exp->getInit(i),
1263 Exp->getInit(i)->getType()))
1264 return true;
1265 }
1266 return false;
1267 }
1268
1269 if (Init->isNullPointerConstant(Context))
1270 return false;
1271 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001272 QualType InitTy = Context.getCanonicalType(Init->getType())
1273 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001274 if (InitTy == Context.BoolTy) {
1275 // Special handling for pointers implicitly cast to bool;
1276 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1277 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1278 Expr* SubE = ICE->getSubExpr();
1279 if (SubE->getType()->isPointerType() ||
1280 SubE->getType()->isArrayType() ||
1281 SubE->getType()->isFunctionType()) {
1282 return CheckAddressConstantExpression(Init);
1283 }
1284 }
1285 } else if (InitTy->isIntegralType()) {
1286 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001287 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001288 SubE = CE->getSubExpr();
1289 // Special check for pointer cast to int; we allow as an extension
1290 // an address constant cast to an integer if the integer
1291 // is of an appropriate width (this sort of code is apparently used
1292 // in some places).
1293 // FIXME: Add pedwarn?
1294 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1295 if (SubE && (SubE->getType()->isPointerType() ||
1296 SubE->getType()->isArrayType() ||
1297 SubE->getType()->isFunctionType())) {
1298 unsigned IntWidth = Context.getTypeSize(Init->getType());
1299 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1300 if (IntWidth >= PointerWidth)
1301 return CheckAddressConstantExpression(Init);
1302 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001303 }
1304
1305 return CheckArithmeticConstantExpression(Init);
1306 }
1307
1308 if (Init->getType()->isPointerType())
1309 return CheckAddressConstantExpression(Init);
1310
Eli Friedman25086f02008-05-30 18:14:48 +00001311 // An array type at the top level that isn't an init-list must
1312 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001313 if (Init->getType()->isArrayType())
1314 return false;
1315
Nuno Lopes1dc26762008-09-01 18:42:41 +00001316 if (Init->getType()->isFunctionType())
1317 return false;
1318
Steve Naroffdff3fb22008-10-02 17:12:56 +00001319 // Allow block exprs at top level.
1320 if (Init->getType()->isBlockPointerType())
1321 return false;
1322
Eli Friedman02c22ce2008-05-20 13:48:25 +00001323 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1324 Init->getSourceRange());
1325 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001326}
1327
Steve Naroff6a0e2092007-09-12 14:07:44 +00001328void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001329 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001330 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001331 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001332
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001333 // If there is no declaration, there was an error parsing it. Just ignore
1334 // the initializer.
1335 if (RealDecl == 0) {
1336 delete Init;
1337 return;
1338 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001339
Steve Naroff420d0f52007-09-12 20:13:48 +00001340 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1341 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001342 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1343 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001344 RealDecl->setInvalidDecl();
1345 return;
1346 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001347 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001348 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001349 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001350 if (VDecl->isBlockVarDecl()) {
1351 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001352 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001353 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001354 VDecl->setInvalidDecl();
1355 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001356 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001357 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001358
1359 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1360 if (!getLangOptions().CPlusPlus) {
1361 if (SC == VarDecl::Static) // C99 6.7.8p4.
1362 CheckForConstantInitializer(Init, DclT);
1363 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001364 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001365 } else if (VDecl->isFileVarDecl()) {
1366 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001367 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001368 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001369 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001370 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001371
Anders Carlssonea7140a2008-08-22 05:00:02 +00001372 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1373 if (!getLangOptions().CPlusPlus) {
1374 // C99 6.7.8p4. All file scoped initializers need to be constant.
1375 CheckForConstantInitializer(Init, DclT);
1376 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001377 }
1378 // If the type changed, it means we had an incomplete type that was
1379 // completed by the initializer. For example:
1380 // int ary[] = { 1, 3, 5 };
1381 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001382 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001383 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001384 Init->setType(DclT);
1385 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001386
1387 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001388 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001389 return;
1390}
1391
Chris Lattner4b009652007-07-25 00:24:17 +00001392/// The declarators are chained together backwards, reverse the list.
1393Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1394 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001395 Decl *GroupDecl = static_cast<Decl*>(group);
1396 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001397 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001398
1399 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1400 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001401 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001402 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001403 else { // reverse the list.
1404 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001405 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001406 Group->setNextDeclarator(NewGroup);
1407 NewGroup = Group;
1408 Group = Next;
1409 }
1410 }
1411 // Perform semantic analysis that depends on having fully processed both
1412 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001413 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001414 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1415 if (!IDecl)
1416 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001417 QualType T = IDecl->getType();
1418
1419 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1420 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001421 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1422 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001423 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001424 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1425 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001426 }
1427 }
1428 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1429 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001430 if (IDecl->isBlockVarDecl() &&
1431 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001432 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001433 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1434 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001435 IDecl->setInvalidDecl();
1436 }
1437 }
1438 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1439 // object that has file scope without an initializer, and without a
1440 // storage-class specifier or with the storage-class specifier "static",
1441 // constitutes a tentative definition. Note: A tentative definition with
1442 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001443 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001444 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001445 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1446 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001447 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001448 // C99 6.9.2p3: If the declaration of an identifier for an object is
1449 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1450 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001451 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1452 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001453 IDecl->setInvalidDecl();
1454 }
1455 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001456 if (IDecl->isFileVarDecl())
1457 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001458 }
1459 return NewGroup;
1460}
Steve Naroff91b03f72007-08-28 03:03:08 +00001461
Chris Lattner3e254fb2008-04-08 04:40:51 +00001462/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1463/// to introduce parameters into function prototype scope.
1464Sema::DeclTy *
1465Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001466 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001467
1468 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001469 VarDecl::StorageClass StorageClass = VarDecl::None;
1470 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1471 StorageClass = VarDecl::Register;
1472 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001473 Diag(DS.getStorageClassSpecLoc(),
1474 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001475 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001476 }
1477 if (DS.isThreadSpecified()) {
1478 Diag(DS.getThreadSpecLoc(),
1479 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001480 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001481 }
1482
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001483 // Check that there are no default arguments inside the type of this
1484 // parameter (C++ only).
1485 if (getLangOptions().CPlusPlus)
1486 CheckExtraCXXDefaultArguments(D);
1487
Chris Lattner3e254fb2008-04-08 04:40:51 +00001488 // In this context, we *do not* check D.getInvalidType(). If the declarator
1489 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1490 // though it will not reflect the user specified type.
1491 QualType parmDeclType = GetTypeForDeclarator(D, S);
1492
1493 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1494
Chris Lattner4b009652007-07-25 00:24:17 +00001495 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1496 // Can this happen for params? We already checked that they don't conflict
1497 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001498 IdentifierInfo *II = D.getIdentifier();
1499 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1500 if (S->isDeclScope(PrevDecl)) {
1501 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1502 dyn_cast<NamedDecl>(PrevDecl)->getName());
1503
1504 // Recover by removing the name
1505 II = 0;
1506 D.SetIdentifier(0, D.getIdentifierLoc());
1507 }
Chris Lattner4b009652007-07-25 00:24:17 +00001508 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001509
1510 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1511 // Doing the promotion here has a win and a loss. The win is the type for
1512 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1513 // code generator). The loss is the orginal type isn't preserved. For example:
1514 //
1515 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1516 // int blockvardecl[5];
1517 // sizeof(parmvardecl); // size == 4
1518 // sizeof(blockvardecl); // size == 20
1519 // }
1520 //
1521 // For expressions, all implicit conversions are captured using the
1522 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1523 //
1524 // FIXME: If a source translation tool needs to see the original type, then
1525 // we need to consider storing both types (in ParmVarDecl)...
1526 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001527 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001528 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001529 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001530 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001531 parmDeclType = Context.getPointerType(parmDeclType);
1532
Chris Lattner3e254fb2008-04-08 04:40:51 +00001533 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1534 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001535 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001536 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001537
Chris Lattner3e254fb2008-04-08 04:40:51 +00001538 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001539 New->setInvalidDecl();
1540
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001541 if (II)
1542 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001543
Chris Lattner9b384ca2008-06-29 00:02:00 +00001544 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001545 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001546
Chris Lattner4b009652007-07-25 00:24:17 +00001547}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001548
Chris Lattnerea148702007-10-09 17:14:05 +00001549Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001550 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001551 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1552 "Not a function declarator!");
1553 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001554
Chris Lattner4b009652007-07-25 00:24:17 +00001555 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1556 // for a K&R function.
1557 if (!FTI.hasPrototype) {
1558 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001559 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001560 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1561 FTI.ArgInfo[i].Ident->getName());
1562 // Implicitly declare the argument as type 'int' for lack of a better
1563 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001564 DeclSpec DS;
1565 const char* PrevSpec; // unused
1566 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1567 PrevSpec);
1568 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1569 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1570 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001571 }
1572 }
Chris Lattner4b009652007-07-25 00:24:17 +00001573 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001574 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001575 }
1576
1577 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001578
1579 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001580 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001581 GlobalScope);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001582 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1584 const FunctionDecl *Definition;
1585 if (FD->getBody(Definition)) {
1586 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1587 D.getIdentifier()->getName());
1588 Diag(Definition->getLocation(), diag::err_previous_definition);
1589 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001590 }
1591 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001592
1593 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001594 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001595}
1596
1597Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1598 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001599 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001600 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001601
1602 // Check the validity of our function parameters
1603 CheckParmsForFunctionDef(FD);
1604
1605 // Introduce our parameters into the function scope
1606 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1607 ParmVarDecl *Param = FD->getParamDecl(p);
1608 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001609 if (Param->getIdentifier())
1610 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001611 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001612
Chris Lattner4b009652007-07-25 00:24:17 +00001613 return FD;
1614}
1615
Steve Naroff99ee4302007-11-11 23:20:51 +00001616Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1617 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001618 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001619 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001620 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001621 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001622 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001623 } else
1624 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001625 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001626 // Verify and clean out per-function state.
1627
1628 // Check goto/label use.
1629 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1630 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1631 // Verify that we have no forward references left. If so, there was a goto
1632 // or address of a label taken, but no definition of it. Label fwd
1633 // definitions are indicated with a null substmt.
1634 if (I->second->getSubStmt() == 0) {
1635 LabelStmt *L = I->second;
1636 // Emit error.
1637 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1638
1639 // At this point, we have gotos that use the bogus label. Stitch it into
1640 // the function body so that they aren't leaked and that the AST is well
1641 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001642 if (Body) {
1643 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1644 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1645 } else {
1646 // The whole function wasn't parsed correctly, just delete this.
1647 delete L;
1648 }
Chris Lattner4b009652007-07-25 00:24:17 +00001649 }
1650 }
1651 LabelMap.clear();
1652
Steve Naroff99ee4302007-11-11 23:20:51 +00001653 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001654}
1655
Chris Lattner4b009652007-07-25 00:24:17 +00001656/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1657/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001658ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1659 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001660 // Extension in C99. Legal in C90, but warn about it.
1661 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001662 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001663 else
Chris Lattner4b009652007-07-25 00:24:17 +00001664 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1665
1666 // FIXME: handle stuff like:
1667 // void foo() { extern float X(); }
1668 // void bar() { X(); } <-- implicit decl for X in another scope.
1669
1670 // Set a Declarator for the implicit definition: int foo();
1671 const char *Dummy;
1672 DeclSpec DS;
1673 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1674 Error = Error; // Silence warning.
1675 assert(!Error && "Error setting up implicit decl!");
1676 Declarator D(DS, Declarator::BlockContext);
1677 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1678 D.SetIdentifier(&II, Loc);
1679
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001680 // Insert this function into translation-unit scope.
1681
1682 DeclContext *PrevDC = CurContext;
1683 CurContext = Context.getTranslationUnitDecl();
1684
Steve Naroff9104f3c2008-04-04 14:32:09 +00001685 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001686 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001687 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001688
1689 CurContext = PrevDC;
1690
Steve Naroff9104f3c2008-04-04 14:32:09 +00001691 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001692}
1693
1694
Chris Lattner82bb4792007-11-14 06:34:38 +00001695TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001696 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001697 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001698 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001699
1700 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001701 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1702 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001703 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001704 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001705 if (D.getInvalidType())
1706 NewTD->setInvalidDecl();
1707 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
Steve Naroff0acc9c92007-09-15 18:49:24 +00001710/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001711/// former case, Name will be non-null. In the later case, Name will be null.
1712/// TagType indicates what kind of tag this is. TK indicates whether this is a
1713/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001714Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001715 SourceLocation KWLoc, IdentifierInfo *Name,
1716 SourceLocation NameLoc, AttributeList *Attr) {
1717 // If this is a use of an existing tag, it must have a name.
1718 assert((Name != 0 || TK == TK_Definition) &&
1719 "Nameless record must be a definition!");
1720
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001721 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001722 switch (TagType) {
1723 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001724 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1725 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1726 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1727 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001728 }
1729
Ted Kremenek46a837c2008-09-05 17:16:31 +00001730 // Two code paths: a new one for structs/unions/classes where we create
1731 // separate decls for forward declarations, and an old (eventually to
1732 // be removed) code path for enums.
1733 if (Kind != TagDecl::TK_enum)
1734 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1735
Chris Lattner4b009652007-07-25 00:24:17 +00001736 // If this is a named struct, check to see if there was a previous forward
1737 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001738 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenekd4434152008-09-02 21:26:19 +00001739 ScopedDecl *PrevDecl =
1740 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1741
1742 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001743 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1744 "unexpected Decl type");
1745 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001746 // If this is a use of a previous tag, or if the tag is already declared
1747 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001748 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001749 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001750 // Make sure that this wasn't declared as an enum and now used as a
1751 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001752 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001753 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1754 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001755 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001756 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001757 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001758 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001759 // If this is a use or a forward declaration, we're good.
1760 if (TK != TK_Definition)
1761 return PrevDecl;
1762
1763 // Diagnose attempts to redefine a tag.
1764 if (PrevTagDecl->isDefinition()) {
1765 Diag(NameLoc, diag::err_redefinition, Name->getName());
1766 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1767 // If this is a redefinition, recover by making this struct be
1768 // anonymous, which will make any later references get the previous
1769 // definition.
1770 Name = 0;
1771 } else {
1772 // Okay, this is definition of a previously declared or referenced
1773 // tag. Move the location of the decl to be the definition site.
1774 PrevDecl->setLocation(NameLoc);
1775 return PrevDecl;
1776 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001777 }
Chris Lattner4b009652007-07-25 00:24:17 +00001778 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001779 // If we get here, this is a definition of a new struct type in a nested
1780 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1781 // type.
1782 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001783 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001784 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00001785 // The tag name clashes with a namespace name, issue an error and
1786 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001787 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1788 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1789 Name = 0;
1790 }
Chris Lattner4b009652007-07-25 00:24:17 +00001791 }
Chris Lattner4b009652007-07-25 00:24:17 +00001792 }
1793
1794 // If there is an identifier, use the location of the identifier as the
1795 // location of the decl, otherwise use the location of the struct/union
1796 // keyword.
1797 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1798
1799 // Otherwise, if this is the first time we've seen this tag, create the decl.
1800 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001801 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001802 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1803 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001804 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001805 // If this is an undefined enum, warn.
1806 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001807 } else {
1808 // struct/union/class
1809
Chris Lattner4b009652007-07-25 00:24:17 +00001810 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1811 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001812 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001813 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek2c984042008-09-05 01:34:33 +00001814 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001815 else
Ted Kremenek2c984042008-09-05 01:34:33 +00001816 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001817 }
Chris Lattner4b009652007-07-25 00:24:17 +00001818
1819 // If this has an identifier, add it to the scope stack.
1820 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001821 // The scope passed in may not be a decl scope. Zip up the scope tree until
1822 // we find one that is.
1823 while ((S->getFlags() & Scope::DeclScope) == 0)
1824 S = S->getParent();
1825
1826 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001827 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001828 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001829
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001830 if (Attr)
1831 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001832 return New;
1833}
1834
Ted Kremenek46a837c2008-09-05 17:16:31 +00001835/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1836/// the logic for enums, we create separate decls for forward declarations.
1837/// This is called by ActOnTag, but eventually will replace its logic.
1838Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1839 SourceLocation KWLoc, IdentifierInfo *Name,
1840 SourceLocation NameLoc, AttributeList *Attr) {
1841
1842 // If this is a named struct, check to see if there was a previous forward
1843 // declaration or definition.
1844 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1845 ScopedDecl *PrevDecl =
1846 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1847
1848 if (PrevDecl) {
1849 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1850 "unexpected Decl type");
1851
1852 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1853 // If this is a use of a previous tag, or if the tag is already declared
1854 // in the same scope (so that the definition/declaration completes or
1855 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001856 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00001857 // Make sure that this wasn't declared as an enum and now used as a
1858 // struct or something similar.
1859 if (PrevTagDecl->getTagKind() != Kind) {
1860 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1861 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1862 // Recover by making this an anonymous redefinition.
1863 Name = 0;
1864 PrevDecl = 0;
1865 } else {
1866 // If this is a use, return the original decl.
1867
1868 // FIXME: In the future, return a variant or some other clue
1869 // for the consumer of this Decl to know it doesn't own it.
1870 // For our current ASTs this shouldn't be a problem, but will
1871 // need to be changed with DeclGroups.
1872 if (TK == TK_Reference)
1873 return PrevDecl;
1874
1875 // The new decl is a definition?
1876 if (TK == TK_Definition) {
1877 // Diagnose attempts to redefine a tag.
1878 if (RecordDecl* DefRecord =
1879 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1880 Diag(NameLoc, diag::err_redefinition, Name->getName());
1881 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1882 // If this is a redefinition, recover by making this struct be
1883 // anonymous, which will make any later references get the previous
1884 // definition.
1885 Name = 0;
1886 PrevDecl = 0;
1887 }
1888 // Okay, this is definition of a previously declared or referenced
1889 // tag. We're going to create a new Decl.
1890 }
1891 }
1892 // If we get here we have (another) forward declaration. Just create
1893 // a new decl.
1894 }
1895 else {
1896 // If we get here, this is a definition of a new struct type in a nested
1897 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1898 // new decl/type. We set PrevDecl to NULL so that the Records
1899 // have distinct types.
1900 PrevDecl = 0;
1901 }
1902 } else {
1903 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001904 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00001905 // The tag name clashes with a namespace name, issue an error and
1906 // recover by making this tag be anonymous.
1907 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1908 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1909 Name = 0;
1910 }
1911 }
1912 }
1913
1914 // If there is an identifier, use the location of the identifier as the
1915 // location of the decl, otherwise use the location of the struct/union
1916 // keyword.
1917 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1918
1919 // Otherwise, if this is the first time we've seen this tag, create the decl.
1920 TagDecl *New;
1921
1922 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1923 // struct X { int A; } D; D should chain to X.
1924 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001925 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001926 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1927 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1928 else
1929 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1930 dyn_cast_or_null<RecordDecl>(PrevDecl));
1931
1932 // If this has an identifier, add it to the scope stack.
1933 if ((TK == TK_Definition || !PrevDecl) && Name) {
1934 // The scope passed in may not be a decl scope. Zip up the scope tree until
1935 // we find one that is.
1936 while ((S->getFlags() & Scope::DeclScope) == 0)
1937 S = S->getParent();
1938
1939 // Add it to the decl chain.
1940 PushOnScopeChains(New, S);
1941 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00001942
1943 // Handle #pragma pack: if the #pragma pack stack has non-default
1944 // alignment, make up a packed attribute for this decl. These
1945 // attributes are checked when the ASTContext lays out the
1946 // structure.
1947 //
1948 // It is important for implementing the correct semantics that this
1949 // happen here (in act on tag decl). The #pragma pack stack is
1950 // maintained as a result of parser callbacks which can occur at
1951 // many points during the parsing of a struct declaration (because
1952 // the #pragma tokens are effectively skipped over during the
1953 // parsing of the struct).
1954 if (unsigned Alignment = PackContext.getAlignment())
1955 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00001956
1957 if (Attr)
1958 ProcessDeclAttributeList(New, Attr);
1959
1960 return New;
1961}
1962
1963
Chris Lattner1bf58f62008-06-21 19:39:06 +00001964/// Collect the instance variables declared in an Objective-C object. Used in
1965/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001966static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001967 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001968 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001969 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1970
1971 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00001972 for (ObjCInterfaceDecl::ivar_iterator
1973 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1974
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001975 ObjCIvarDecl* ID = *I;
1976 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1977 ID->getIdentifier(),
1978 ID->getType(),
1979 ID->getBitWidth()));
1980 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001981}
1982
1983/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1984/// instance variables of ClassName into Decls.
1985void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1986 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001987 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001988 // Check that ClassName is a valid class
1989 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1990 if (!Class) {
1991 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1992 return;
1993 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001994 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001995 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001996}
1997
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001998QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1999 // This method tries to turn a variable array into a constant
2000 // array even when the size isn't an ICE. This is necessary
2001 // for compatibility with code that depends on gcc's buggy
2002 // constant expression folding, like struct {char x[(int)(char*)2];}
2003 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00002004 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002005 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00002006 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2007 llvm::APSInt &Res = Result.getInt();
2008 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2009 return Context.getConstantArrayType(VLATy->getElementType(),
2010 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002011 }
2012 }
2013 return QualType();
2014}
2015
Steve Naroff0acc9c92007-09-15 18:49:24 +00002016/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002017/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002018Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002019 SourceLocation DeclStart,
2020 Declarator &D, ExprTy *BitfieldWidth) {
2021 IdentifierInfo *II = D.getIdentifier();
2022 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002023 SourceLocation Loc = DeclStart;
2024 if (II) Loc = D.getIdentifierLoc();
2025
2026 // FIXME: Unnamed fields can be handled in various different ways, for
2027 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002028
Chris Lattner4b009652007-07-25 00:24:17 +00002029 if (BitWidth) {
2030 // TODO: Validate.
2031 //printf("WARNING: BITFIELDS IGNORED!\n");
2032
2033 // 6.7.2.1p3
2034 // 6.7.2.1p4
2035
2036 } else {
2037 // Not a bitfield.
2038
2039 // validate II.
2040
2041 }
2042
2043 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002044 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2045 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002046
Chris Lattner4b009652007-07-25 00:24:17 +00002047 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2048 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002049 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002050 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2051 if (!FixedTy.isNull()) {
2052 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2053 T = FixedTy;
2054 } else {
2055 // FIXME: This diagnostic needs work
2056 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2057 InvalidDecl = true;
2058 }
Chris Lattner4b009652007-07-25 00:24:17 +00002059 }
Chris Lattner4b009652007-07-25 00:24:17 +00002060 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002061 FieldDecl *NewFD;
2062
2063 if (getLangOptions().CPlusPlus) {
2064 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2065 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2066 Loc, II, T, BitWidth);
2067 if (II)
2068 PushOnScopeChains(NewFD, S);
2069 }
2070 else
2071 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002072
Chris Lattner9b384ca2008-06-29 00:02:00 +00002073 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002074
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002075 if (D.getInvalidType() || InvalidDecl)
2076 NewFD->setInvalidDecl();
2077 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002078}
2079
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002080/// TranslateIvarVisibility - Translate visibility from a token ID to an
2081/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002082static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002083TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002084 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002085 default: assert(0 && "Unknown visitibility kind");
2086 case tok::objc_private: return ObjCIvarDecl::Private;
2087 case tok::objc_public: return ObjCIvarDecl::Public;
2088 case tok::objc_protected: return ObjCIvarDecl::Protected;
2089 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002090 }
2091}
2092
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002093/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2094/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002095Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002096 SourceLocation DeclStart,
2097 Declarator &D, ExprTy *BitfieldWidth,
2098 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002099 IdentifierInfo *II = D.getIdentifier();
2100 Expr *BitWidth = (Expr*)BitfieldWidth;
2101 SourceLocation Loc = DeclStart;
2102 if (II) Loc = D.getIdentifierLoc();
2103
2104 // FIXME: Unnamed fields can be handled in various different ways, for
2105 // example, unnamed unions inject all members into the struct namespace!
2106
2107
2108 if (BitWidth) {
2109 // TODO: Validate.
2110 //printf("WARNING: BITFIELDS IGNORED!\n");
2111
2112 // 6.7.2.1p3
2113 // 6.7.2.1p4
2114
2115 } else {
2116 // Not a bitfield.
2117
2118 // validate II.
2119
2120 }
2121
2122 QualType T = GetTypeForDeclarator(D, S);
2123 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2124 bool InvalidDecl = false;
2125
2126 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2127 // than a variably modified type.
2128 if (T->isVariablyModifiedType()) {
2129 // FIXME: This diagnostic needs work
2130 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2131 InvalidDecl = true;
2132 }
2133
Ted Kremenek173dd312008-07-23 18:04:17 +00002134 // Get the visibility (access control) for this ivar.
2135 ObjCIvarDecl::AccessControl ac =
2136 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2137 : ObjCIvarDecl::None;
2138
2139 // Construct the decl.
2140 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002141 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002142
Ted Kremenek173dd312008-07-23 18:04:17 +00002143 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002144 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002145
2146 if (D.getInvalidType() || InvalidDecl)
2147 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002148
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002149 return NewID;
2150}
2151
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002152void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002153 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002154 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002155 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002156 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002157 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2158 assert(EnclosingDecl && "missing record or interface decl");
2159 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2160
Ted Kremenek46a837c2008-09-05 17:16:31 +00002161 if (Record)
2162 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2163 // Diagnose code like:
2164 // struct S { struct S {} X; };
2165 // We discover this when we complete the outer S. Reject and ignore the
2166 // outer S.
2167 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2168 DefRecord->getKindName());
2169 Diag(RecLoc, diag::err_previous_definition);
2170 Record->setInvalidDecl();
2171 return;
2172 }
2173
Chris Lattner4b009652007-07-25 00:24:17 +00002174 // Verify that all the fields are okay.
2175 unsigned NumNamedMembers = 0;
2176 llvm::SmallVector<FieldDecl*, 32> RecFields;
2177 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002178
Chris Lattner4b009652007-07-25 00:24:17 +00002179 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002180
Steve Naroff9bb759f2007-09-14 22:20:54 +00002181 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2182 assert(FD && "missing field decl");
2183
2184 // Remember all fields.
2185 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002186
2187 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002188 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002189
Chris Lattner4b009652007-07-25 00:24:17 +00002190 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002191 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002192 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002193 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002194 FD->setInvalidDecl();
2195 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002196 continue;
2197 }
Chris Lattner4b009652007-07-25 00:24:17 +00002198 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2199 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002200 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002201 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002202 FD->setInvalidDecl();
2203 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002204 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002205 }
Chris Lattner4b009652007-07-25 00:24:17 +00002206 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002207 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002208 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002209 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002210 FD->setInvalidDecl();
2211 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002212 continue;
2213 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002214 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002215 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2216 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002217 FD->setInvalidDecl();
2218 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002219 continue;
2220 }
Chris Lattner4b009652007-07-25 00:24:17 +00002221 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002222 if (Record)
2223 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002224 }
Chris Lattner4b009652007-07-25 00:24:17 +00002225 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2226 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002227 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002228 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2229 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002230 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002231 Record->setHasFlexibleArrayMember(true);
2232 } else {
2233 // If this is a struct/class and this is not the last element, reject
2234 // it. Note that GCC supports variable sized arrays in the middle of
2235 // structures.
2236 if (i != NumFields-1) {
2237 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2238 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002239 FD->setInvalidDecl();
2240 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002241 continue;
2242 }
Chris Lattner4b009652007-07-25 00:24:17 +00002243 // We support flexible arrays at the end of structs in other structs
2244 // as an extension.
2245 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2246 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002247 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002248 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002249 }
2250 }
2251 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002252 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002253 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002254 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2255 FD->getName());
2256 FD->setInvalidDecl();
2257 EnclosingDecl->setInvalidDecl();
2258 continue;
2259 }
Chris Lattner4b009652007-07-25 00:24:17 +00002260 // Keep track of the number of named members.
2261 if (IdentifierInfo *II = FD->getIdentifier()) {
2262 // Detect duplicate member names.
2263 if (!FieldIDs.insert(II)) {
2264 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2265 // Find the previous decl.
2266 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002267 for (unsigned i = 0; ; ++i) {
2268 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002269 if (RecFields[i]->getIdentifier() == II) {
2270 PrevLoc = RecFields[i]->getLocation();
2271 break;
2272 }
2273 }
2274 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002275 FD->setInvalidDecl();
2276 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002277 continue;
2278 }
2279 ++NumNamedMembers;
2280 }
Chris Lattner4b009652007-07-25 00:24:17 +00002281 }
2282
Chris Lattner4b009652007-07-25 00:24:17 +00002283 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002284 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002285 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002286 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2287 // Sema::ActOnFinishCXXClassDef.
2288 if (!isa<CXXRecordDecl>(Record))
2289 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002290 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002291 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2292 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2293 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2294 else if (ObjCImplementationDecl *IMPDecl =
2295 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002296 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2297 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002298 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002299 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002300 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002301
2302 if (Attr)
2303 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002304}
2305
Steve Naroff0acc9c92007-09-15 18:49:24 +00002306Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002307 DeclTy *lastEnumConst,
2308 SourceLocation IdLoc, IdentifierInfo *Id,
2309 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002310 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002311 EnumConstantDecl *LastEnumConst =
2312 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2313 Expr *Val = static_cast<Expr*>(val);
2314
Chris Lattnera7549902007-08-26 06:24:45 +00002315 // The scope passed in may not be a decl scope. Zip up the scope tree until
2316 // we find one that is.
2317 while ((S->getFlags() & Scope::DeclScope) == 0)
2318 S = S->getParent();
2319
Chris Lattner4b009652007-07-25 00:24:17 +00002320 // Verify that there isn't already something declared with this name in this
2321 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002322 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002323 // When in C++, we may get a TagDecl with the same name; in this case the
2324 // enum constant will 'hide' the tag.
2325 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2326 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002327 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002328 if (isa<EnumConstantDecl>(PrevDecl))
2329 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2330 else
2331 Diag(IdLoc, diag::err_redefinition, Id->getName());
2332 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002333 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002334 return 0;
2335 }
2336 }
2337
2338 llvm::APSInt EnumVal(32);
2339 QualType EltTy;
2340 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002341 // Make sure to promote the operand type to int.
2342 UsualUnaryConversions(Val);
2343
Chris Lattner4b009652007-07-25 00:24:17 +00002344 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2345 SourceLocation ExpLoc;
2346 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2347 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2348 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002349 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002350 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002351 } else {
2352 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002353 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002354 }
2355
2356 if (!Val) {
2357 if (LastEnumConst) {
2358 // Assign the last value + 1.
2359 EnumVal = LastEnumConst->getInitVal();
2360 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002361
2362 // Check for overflow on increment.
2363 if (EnumVal < LastEnumConst->getInitVal())
2364 Diag(IdLoc, diag::warn_enum_value_overflow);
2365
Chris Lattnere7f53a42007-08-27 17:37:24 +00002366 EltTy = LastEnumConst->getType();
2367 } else {
2368 // First value, set to zero.
2369 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002370 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002371 }
Chris Lattner4b009652007-07-25 00:24:17 +00002372 }
2373
Chris Lattnere4650482008-03-15 06:12:44 +00002374 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002375 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2376 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002377 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002378
2379 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002380 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002381 return New;
2382}
2383
Steve Naroffb0726b82008-08-07 14:08:16 +00002384// FIXME: For consistency with ActOnFields(), we should have the parser
2385// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002386void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002387 DeclTy **Elements, unsigned NumElements) {
2388 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002389
Steve Naroffb0726b82008-08-07 14:08:16 +00002390 if (Enum && Enum->isDefinition()) {
2391 // Diagnose code like:
2392 // enum e0 {
2393 // E0 = sizeof(enum e0 { E1 })
2394 // };
2395 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2396 Enum->getName());
2397 Diag(EnumLoc, diag::err_previous_definition);
2398 Enum->setInvalidDecl();
2399 return;
2400 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002401 // TODO: If the result value doesn't fit in an int, it must be a long or long
2402 // long value. ISO C does not support this, but GCC does as an extension,
2403 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002404 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002405
Chris Lattner206754a2007-08-28 06:15:15 +00002406 // Verify that all the values are okay, compute the size of the values, and
2407 // reverse the list.
2408 unsigned NumNegativeBits = 0;
2409 unsigned NumPositiveBits = 0;
2410
2411 // Keep track of whether all elements have type int.
2412 bool AllElementsInt = true;
2413
Chris Lattner4b009652007-07-25 00:24:17 +00002414 EnumConstantDecl *EltList = 0;
2415 for (unsigned i = 0; i != NumElements; ++i) {
2416 EnumConstantDecl *ECD =
2417 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2418 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002419
2420 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002421 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002422 assert(InitVal.getBitWidth() >= IntWidth &&
2423 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002424 if (InitVal.getBitWidth() > IntWidth) {
2425 llvm::APSInt V(InitVal);
2426 V.trunc(IntWidth);
2427 V.extend(InitVal.getBitWidth());
2428 if (V != InitVal)
2429 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002430 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002431 }
Chris Lattner206754a2007-08-28 06:15:15 +00002432
2433 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002434 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002435 NumPositiveBits = std::max(NumPositiveBits,
2436 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002437 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002438 NumNegativeBits = std::max(NumNegativeBits,
2439 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002440
Chris Lattner206754a2007-08-28 06:15:15 +00002441 // Keep track of whether every enum element has type int (very commmon).
2442 if (AllElementsInt)
2443 AllElementsInt = ECD->getType() == Context.IntTy;
2444
Chris Lattner4b009652007-07-25 00:24:17 +00002445 ECD->setNextDeclarator(EltList);
2446 EltList = ECD;
2447 }
2448
Chris Lattner206754a2007-08-28 06:15:15 +00002449 // Figure out the type that should be used for this enum.
2450 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2451 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002452 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002453
2454 if (NumNegativeBits) {
2455 // If there is a negative value, figure out the smallest integer type (of
2456 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002457 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002458 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002459 BestWidth = IntWidth;
2460 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002461 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002462
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002463 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002464 BestType = Context.LongTy;
2465 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002466 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002467
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002468 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002469 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2470 BestType = Context.LongLongTy;
2471 }
2472 }
2473 } else {
2474 // If there is no negative value, figure out which of uint, ulong, ulonglong
2475 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002476 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002477 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002478 BestWidth = IntWidth;
2479 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002480 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002481 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002482 } else {
2483 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002484 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002485 "How could an initializer get larger than ULL?");
2486 BestType = Context.UnsignedLongLongTy;
2487 }
2488 }
2489
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002490 // Loop over all of the enumerator constants, changing their types to match
2491 // the type of the enum if needed.
2492 for (unsigned i = 0; i != NumElements; ++i) {
2493 EnumConstantDecl *ECD =
2494 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2495 if (!ECD) continue; // Already issued a diagnostic.
2496
2497 // Standard C says the enumerators have int type, but we allow, as an
2498 // extension, the enumerators to be larger than int size. If each
2499 // enumerator value fits in an int, type it as an int, otherwise type it the
2500 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2501 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002502 if (ECD->getType() == Context.IntTy) {
2503 // Make sure the init value is signed.
2504 llvm::APSInt IV = ECD->getInitVal();
2505 IV.setIsSigned(true);
2506 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002507 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002508 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002509
2510 // Determine whether the value fits into an int.
2511 llvm::APSInt InitVal = ECD->getInitVal();
2512 bool FitsInInt;
2513 if (InitVal.isUnsigned() || !InitVal.isNegative())
2514 FitsInInt = InitVal.getActiveBits() < IntWidth;
2515 else
2516 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2517
2518 // If it fits into an integer type, force it. Otherwise force it to match
2519 // the enum decl type.
2520 QualType NewTy;
2521 unsigned NewWidth;
2522 bool NewSign;
2523 if (FitsInInt) {
2524 NewTy = Context.IntTy;
2525 NewWidth = IntWidth;
2526 NewSign = true;
2527 } else if (ECD->getType() == BestType) {
2528 // Already the right type!
2529 continue;
2530 } else {
2531 NewTy = BestType;
2532 NewWidth = BestWidth;
2533 NewSign = BestType->isSignedIntegerType();
2534 }
2535
2536 // Adjust the APSInt value.
2537 InitVal.extOrTrunc(NewWidth);
2538 InitVal.setIsSigned(NewSign);
2539 ECD->setInitVal(InitVal);
2540
2541 // Adjust the Expr initializer and type.
2542 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2543 ECD->setType(NewTy);
2544 }
Chris Lattner206754a2007-08-28 06:15:15 +00002545
Chris Lattner90a018d2007-08-28 18:24:31 +00002546 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002547 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002548}
2549
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002550Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2551 ExprTy *expr) {
2552 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2553
Chris Lattner81db64a2008-03-16 00:16:02 +00002554 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002555}
2556
Chris Lattner806a5f52008-01-12 07:05:38 +00002557Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002558 SourceLocation LBrace,
2559 SourceLocation RBrace,
2560 const char *Lang,
2561 unsigned StrSize,
2562 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002563 LinkageSpecDecl::LanguageIDs Language;
2564 Decl *dcl = static_cast<Decl *>(D);
2565 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2566 Language = LinkageSpecDecl::lang_c;
2567 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2568 Language = LinkageSpecDecl::lang_cxx;
2569 else {
2570 Diag(Loc, diag::err_bad_language);
2571 return 0;
2572 }
2573
2574 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002575 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002576}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00002577
2578void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2579 ExprTy *alignment, SourceLocation PragmaLoc,
2580 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2581 Expr *Alignment = static_cast<Expr *>(alignment);
2582
2583 // If specified then alignment must be a "small" power of two.
2584 unsigned AlignmentVal = 0;
2585 if (Alignment) {
2586 llvm::APSInt Val;
2587 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2588 !Val.isPowerOf2() ||
2589 Val.getZExtValue() > 16) {
2590 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2591 delete Alignment;
2592 return; // Ignore
2593 }
2594
2595 AlignmentVal = (unsigned) Val.getZExtValue();
2596 }
2597
2598 switch (Kind) {
2599 case Action::PPK_Default: // pack([n])
2600 PackContext.setAlignment(AlignmentVal);
2601 break;
2602
2603 case Action::PPK_Show: // pack(show)
2604 // Show the current alignment, making sure to show the right value
2605 // for the default.
2606 AlignmentVal = PackContext.getAlignment();
2607 // FIXME: This should come from the target.
2608 if (AlignmentVal == 0)
2609 AlignmentVal = 8;
2610 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2611 break;
2612
2613 case Action::PPK_Push: // pack(push [, id] [, [n])
2614 PackContext.push(Name);
2615 // Set the new alignment if specified.
2616 if (Alignment)
2617 PackContext.setAlignment(AlignmentVal);
2618 break;
2619
2620 case Action::PPK_Pop: // pack(pop [, id] [, n])
2621 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2622 // "#pragma pack(pop, identifier, n) is undefined"
2623 if (Alignment && Name)
2624 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2625
2626 // Do the pop.
2627 if (!PackContext.pop(Name)) {
2628 // If a name was specified then failure indicates the name
2629 // wasn't found. Otherwise failure indicates the stack was
2630 // empty.
2631 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2632 Name ? "no record matching name" : "stack empty");
2633
2634 // FIXME: Warn about popping named records as MSVC does.
2635 } else {
2636 // Pop succeeded, set the new alignment if specified.
2637 if (Alignment)
2638 PackContext.setAlignment(AlignmentVal);
2639 }
2640 break;
2641
2642 default:
2643 assert(0 && "Invalid #pragma pack kind.");
2644 }
2645}
2646
2647bool PragmaPackStack::pop(IdentifierInfo *Name) {
2648 if (Stack.empty())
2649 return false;
2650
2651 // If name is empty just pop top.
2652 if (!Name) {
2653 Alignment = Stack.back().first;
2654 Stack.pop_back();
2655 return true;
2656 }
2657
2658 // Otherwise, find the named record.
2659 for (unsigned i = Stack.size(); i != 0; ) {
2660 --i;
2661 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
2662 // Found it, pop up to and including this record.
2663 Alignment = Stack[i].first;
2664 Stack.erase(Stack.begin() + i, Stack.end());
2665 return true;
2666 }
2667 }
2668
2669 return false;
2670}