blob: 74ce855add5baecb277f541dfe7f139d7163ed8f [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"
28using namespace clang;
29
Argiris Kirtzidis46403632008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff6384a012008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor1d661552008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000037 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000038}
39
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattneref87a202008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000067}
68
Chris Lattnerf3874bc2008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000072}
73
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000076 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +000089 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000090 // There is already a declaration with the same name in the same
91 // scope. It must be found before we find the new declaration,
92 // so swap the order on the shadowed declaration chain.
93
Argiris Kirtzidis94805232008-07-17 17:49:50 +000094 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000095 return;
96 }
97 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000098 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000099}
100
Steve Naroff9637a9b2007-10-09 22:01:59 +0000101void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000102 if (S->decl_empty()) return;
103 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104
Chris Lattner4b009652007-07-25 00:24:17 +0000105 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
106 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000107 Decl *TmpD = static_cast<Decl*>(*I);
108 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000109
110 if (isa<CXXFieldDecl>(TmpD)) continue;
111
112 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
113 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000114
Chris Lattner4b009652007-07-25 00:24:17 +0000115 IdentifierInfo *II = D->getIdentifier();
116 if (!II) continue;
117
Ted Kremenek40e70e72008-09-03 18:03:35 +0000118 // We only want to remove the decls from the identifier decl chains for
119 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000120 if (S->getFnParent() != 0)
121 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000122
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000123 // Chain this decl to the containing DeclContext.
124 D->setNext(CurContext->getDeclChain());
125 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000126 }
127}
128
Steve Naroffe57c21a2008-04-01 23:04:06 +0000129/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
130/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000131ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000132 // The third "scope" argument is 0 since we aren't enabling lazy built-in
133 // creation from this context.
134 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000135
Steve Naroff6384a012008-04-02 14:35:35 +0000136 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000137}
138
Steve Naroffe57c21a2008-04-01 23:04:06 +0000139/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000140/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000141Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
142 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000143 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000144 unsigned NS = NSI;
145 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
146 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000147
Chris Lattner4b009652007-07-25 00:24:17 +0000148 // Scan up the scope chain looking for a decl that matches this identifier
149 // that is in the appropriate namespace. This search should not take long, as
150 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000151 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000152 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000153 if ((*I)->getIdentifierNamespace() & NS)
154 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000155
Chris Lattner4b009652007-07-25 00:24:17 +0000156 // If we didn't find a use of this identifier, and if the identifier
157 // corresponds to a compiler builtin, create the decl object for the builtin
158 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000159 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000160 if (enableLazyBuiltinCreation) {
161 // If this is a builtin on this (or all) targets, create the decl.
162 if (unsigned BuiltinID = II->getBuiltinID())
163 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
164 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000165 if (getLangOptions().ObjC1) {
166 // @interface and @compatibility_alias introduce typedef-like names.
167 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000168 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000169 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000170 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
171 if (IDI != ObjCInterfaceDecls.end())
172 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000173 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
174 if (I != ObjCAliasDecls.end())
175 return I->second->getClassInterface();
176 }
Chris Lattner4b009652007-07-25 00:24:17 +0000177 }
178 return 0;
179}
180
Chris Lattnera9c87f22008-05-05 22:18:14 +0000181void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000182 if (!Context.getBuiltinVaListType().isNull())
183 return;
184
185 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000186 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000187 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000188 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
189}
190
Chris Lattner4b009652007-07-25 00:24:17 +0000191/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
192/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000193ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
194 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000195 Builtin::ID BID = (Builtin::ID)bid;
196
Chris Lattnerb23469f2008-09-28 05:54:29 +0000197 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000198 InitBuiltinVaListType();
199
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000200 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000201 FunctionDecl *New = FunctionDecl::Create(Context,
202 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000203 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000204 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000205
Chris Lattnera9c87f22008-05-05 22:18:14 +0000206 // Create Decl objects for each parameter, adding them to the
207 // FunctionDecl.
208 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
209 llvm::SmallVector<ParmVarDecl*, 16> Params;
210 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
211 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
212 FT->getArgType(i), VarDecl::None, 0,
213 0));
214 New->setParams(&Params[0], Params.size());
215 }
216
217
218
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000219 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000220 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000221 return New;
222}
223
224/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
225/// and scope as a previous declaration 'Old'. Figure out how to resolve this
226/// situation, merging decls or emitting diagnostics as appropriate.
227///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000228TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000229 // Allow multiple definitions for ObjC built-in typedefs.
230 // FIXME: Verify the underlying types are equivalent!
231 if (getLangOptions().ObjC1) {
232 const IdentifierInfo *typeIdent = New->getIdentifier();
233 if (typeIdent == Ident_id) {
234 Context.setObjCIdType(New);
235 return New;
236 } else if (typeIdent == Ident_Class) {
237 Context.setObjCClassType(New);
238 return New;
239 } else if (typeIdent == Ident_SEL) {
240 Context.setObjCSelType(New);
241 return New;
242 } else if (typeIdent == Ident_Protocol) {
243 Context.setObjCProtoType(New->getUnderlyingType());
244 return New;
245 }
246 // Fall through - the typedef name was not a builtin type.
247 }
Chris Lattner4b009652007-07-25 00:24:17 +0000248 // Verify the old decl was also a typedef.
249 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
250 if (!Old) {
251 Diag(New->getLocation(), diag::err_redefinition_different_kind,
252 New->getName());
253 Diag(OldD->getLocation(), diag::err_previous_definition);
254 return New;
255 }
256
Chris Lattnerbef8d622008-07-25 18:44:27 +0000257 // If the typedef types are not identical, reject them in all languages and
258 // with any extensions enabled.
259 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
260 Context.getCanonicalType(Old->getUnderlyingType()) !=
261 Context.getCanonicalType(New->getUnderlyingType())) {
262 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
263 New->getUnderlyingType().getAsString(),
264 Old->getUnderlyingType().getAsString());
265 Diag(Old->getLocation(), diag::err_previous_definition);
266 return Old;
267 }
268
Eli Friedman324d5032008-06-11 06:20:39 +0000269 if (getLangOptions().Microsoft) return New;
270
Steve Naroffa9eae582008-01-30 23:46:05 +0000271 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
272 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
273 // *either* declaration is in a system header. The code below implements
274 // this adhoc compatibility rule. FIXME: The following code will not
275 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000276 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
277 SourceManager &SrcMgr = Context.getSourceManager();
278 if (SrcMgr.isInSystemHeader(Old->getLocation()))
279 return New;
280 if (SrcMgr.isInSystemHeader(New->getLocation()))
281 return New;
282 }
Eli Friedman324d5032008-06-11 06:20:39 +0000283
Ted Kremenek64845ce2008-05-23 21:28:18 +0000284 Diag(New->getLocation(), diag::err_redefinition, New->getName());
285 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000286 return New;
287}
288
Chris Lattner6953a072008-06-26 18:38:35 +0000289/// DeclhasAttr - returns true if decl Declaration already has the target
290/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000291static bool DeclHasAttr(const Decl *decl, const Attr *target) {
292 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
293 if (attr->getKind() == target->getKind())
294 return true;
295
296 return false;
297}
298
299/// MergeAttributes - append attributes from the Old decl to the New one.
300static void MergeAttributes(Decl *New, Decl *Old) {
301 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
302
Chris Lattner402b3372008-03-03 03:28:21 +0000303 while (attr) {
304 tmp = attr;
305 attr = attr->getNext();
306
307 if (!DeclHasAttr(New, tmp)) {
308 New->addAttr(tmp);
309 } else {
310 tmp->setNext(0);
311 delete(tmp);
312 }
313 }
Nuno Lopes77654342008-06-01 22:53:53 +0000314
315 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000316}
317
Chris Lattner3e254fb2008-04-08 04:40:51 +0000318/// MergeFunctionDecl - We just parsed a function 'New' from
319/// declarator D which has the same name and scope as a previous
320/// declaration 'Old'. Figure out how to resolve this situation,
321/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000322/// Redeclaration will be set true if thisNew is a redeclaration OldD.
323FunctionDecl *
324Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
325 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000326 // Verify the old decl was also a function.
327 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
328 if (!Old) {
329 Diag(New->getLocation(), diag::err_redefinition_different_kind,
330 New->getName());
331 Diag(OldD->getLocation(), diag::err_previous_definition);
332 return New;
333 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000334
Chris Lattner42a21742008-04-06 23:10:54 +0000335 QualType OldQType = Context.getCanonicalType(Old->getType());
336 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000337
Chris Lattner3e254fb2008-04-08 04:40:51 +0000338 // C++ [dcl.fct]p3:
339 // All declarations for a function shall agree exactly in both the
340 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000341 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
342 MergeAttributes(New, Old);
343 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000344 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000345 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000346
347 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000348 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000349 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000350 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000351 MergeAttributes(New, Old);
352 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000353 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000354 }
Chris Lattner1470b072007-11-06 06:07:26 +0000355
Steve Naroff6c9e7922008-01-16 15:01:34 +0000356 // A function that has already been declared has been redeclared or defined
357 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000358 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000359 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000360 PrevDiag = diag::err_previous_definition;
361 else if (Old->isImplicit())
362 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000363 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000364 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000365
Chris Lattner4b009652007-07-25 00:24:17 +0000366 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
367 // TODO: This is totally simplistic. It should handle merging functions
368 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000369 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
370 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000371 return New;
372}
373
Steve Naroffb5e78152008-08-08 17:50:35 +0000374/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000375static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000376 if (VD->isFileVarDecl())
377 return (!VD->getInit() &&
378 (VD->getStorageClass() == VarDecl::None ||
379 VD->getStorageClass() == VarDecl::Static));
380 return false;
381}
382
383/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
384/// when dealing with C "tentative" external object definitions (C99 6.9.2).
385void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
386 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000387 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000388
389 for (IdentifierResolver::iterator
390 I = IdResolver.begin(VD->getIdentifier(),
391 VD->getDeclContext(), false/*LookInParentCtx*/),
392 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000393 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000394 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
395
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000396 // Handle the following case:
397 // int a[10];
398 // int a[]; - the code below makes sure we set the correct type.
399 // int a[11]; - this is an error, size isn't 10.
400 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
401 OldDecl->getType()->isConstantArrayType())
402 VD->setType(OldDecl->getType());
403
Steve Naroffb5e78152008-08-08 17:50:35 +0000404 // Check for "tentative" definitions. We can't accomplish this in
405 // MergeVarDecl since the initializer hasn't been attached.
406 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
407 continue;
408
409 // Handle __private_extern__ just like extern.
410 if (OldDecl->getStorageClass() != VarDecl::Extern &&
411 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
412 VD->getStorageClass() != VarDecl::Extern &&
413 VD->getStorageClass() != VarDecl::PrivateExtern) {
414 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
415 Diag(OldDecl->getLocation(), diag::err_previous_definition);
416 }
417 }
418 }
419}
420
Chris Lattner4b009652007-07-25 00:24:17 +0000421/// MergeVarDecl - We just parsed a variable 'New' which has the same name
422/// and scope as a previous declaration 'Old'. Figure out how to resolve this
423/// situation, merging decls or emitting diagnostics as appropriate.
424///
Steve Naroffb5e78152008-08-08 17:50:35 +0000425/// Tentative definition rules (C99 6.9.2p2) are checked by
426/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
427/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000428///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000429VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000430 // Verify the old decl was also a variable.
431 VarDecl *Old = dyn_cast<VarDecl>(OldD);
432 if (!Old) {
433 Diag(New->getLocation(), diag::err_redefinition_different_kind,
434 New->getName());
435 Diag(OldD->getLocation(), diag::err_previous_definition);
436 return New;
437 }
Chris Lattner402b3372008-03-03 03:28:21 +0000438
439 MergeAttributes(New, Old);
440
Chris Lattner4b009652007-07-25 00:24:17 +0000441 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000442 QualType OldCType = Context.getCanonicalType(Old->getType());
443 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000444 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000445 Diag(New->getLocation(), diag::err_redefinition, New->getName());
446 Diag(Old->getLocation(), diag::err_previous_definition);
447 return New;
448 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000449 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
450 if (New->getStorageClass() == VarDecl::Static &&
451 (Old->getStorageClass() == VarDecl::None ||
452 Old->getStorageClass() == VarDecl::Extern)) {
453 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
454 Diag(Old->getLocation(), diag::err_previous_definition);
455 return New;
456 }
457 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
458 if (New->getStorageClass() != VarDecl::Static &&
459 Old->getStorageClass() == VarDecl::Static) {
460 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
461 Diag(Old->getLocation(), diag::err_previous_definition);
462 return New;
463 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000464 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
465 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000466 Diag(New->getLocation(), diag::err_redefinition, New->getName());
467 Diag(Old->getLocation(), diag::err_previous_definition);
468 }
469 return New;
470}
471
Chris Lattner3e254fb2008-04-08 04:40:51 +0000472/// CheckParmsForFunctionDef - Check that the parameters of the given
473/// function are appropriate for the definition of a function. This
474/// takes care of any checks that cannot be performed on the
475/// declaration itself, e.g., that the types of each of the function
476/// parameters are complete.
477bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
478 bool HasInvalidParm = false;
479 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
480 ParmVarDecl *Param = FD->getParamDecl(p);
481
482 // C99 6.7.5.3p4: the parameters in a parameter type list in a
483 // function declarator that is part of a function definition of
484 // that function shall not have incomplete type.
485 if (Param->getType()->isIncompleteType() &&
486 !Param->isInvalidDecl()) {
487 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
488 Param->getType().getAsString());
489 Param->setInvalidDecl();
490 HasInvalidParm = true;
491 }
492 }
493
494 return HasInvalidParm;
495}
496
Chris Lattner4b009652007-07-25 00:24:17 +0000497/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
498/// no declarator (e.g. "struct foo;") is parsed.
499Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
500 // TODO: emit error on 'int;' or 'const enum foo;'.
501 // TODO: emit error on 'typedef int;'
502 // if (!DS.isMissingDeclaratorOk()) Diag(...);
503
Steve Naroffedafc0b2007-11-17 21:37:36 +0000504 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000505}
506
Steve Narofff0b23542008-01-10 22:15:12 +0000507bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000508 // Get the type before calling CheckSingleAssignmentConstraints(), since
509 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000510 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000511
Chris Lattner005ed752008-01-04 18:04:52 +0000512 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
513 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
514 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000515}
516
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000517bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000518 const ArrayType *AT = Context.getAsArrayType(DeclT);
519
520 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000521 // C99 6.7.8p14. We have an array of character type with unknown size
522 // being initialized to a string literal.
523 llvm::APSInt ConstVal(32);
524 ConstVal = strLiteral->getByteLength() + 1;
525 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000526 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000527 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000528 } else {
529 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000530 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000531 // FIXME: Avoid truncation for 64-bit length strings.
532 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000533 Diag(strLiteral->getSourceRange().getBegin(),
534 diag::warn_initializer_string_for_char_array_too_long,
535 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000536 }
537 // Set type from "char *" to "constant array of char".
538 strLiteral->setType(DeclT);
539 // For now, we always return false (meaning success).
540 return false;
541}
542
543StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000544 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000545 if (AT && AT->getElementType()->isCharType()) {
546 return dyn_cast<StringLiteral>(Init);
547 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000548 return 0;
549}
550
Steve Narofff3cb5142008-01-25 00:51:06 +0000551bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000552 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
553 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000554 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000555 return Diag(VAT->getSizeExpr()->getLocStart(),
556 diag::err_variable_object_no_init,
557 VAT->getSizeExpr()->getSourceRange());
558
Steve Naroffcb69fb72007-12-10 22:44:33 +0000559 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
560 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000561 // FIXME: Handle wide strings
562 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
563 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000564
Steve Naroffb2f72412008-09-29 20:07:05 +0000565 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000566 if (DeclType->isArrayType())
567 return Diag(Init->getLocStart(),
568 diag::err_array_init_list_required,
569 Init->getSourceRange());
570
Steve Narofff0b23542008-01-10 22:15:12 +0000571 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000572 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000573
Steve Naroffc4d4a482008-05-01 22:18:59 +0000574 InitListChecker CheckInitList(this, InitList, DeclType);
575 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000576}
577
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000578Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000579Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000580 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000581 IdentifierInfo *II = D.getIdentifier();
582
583 // All of these full declarators require an identifier. If it doesn't have
584 // one, the ParsedFreeStandingDeclSpec action should be used.
585 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000586 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000587 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000588 D.getDeclSpec().getSourceRange(), D.getSourceRange());
589 return 0;
590 }
591
Chris Lattnera7549902007-08-26 06:24:45 +0000592 // The scope passed in may not be a decl scope. Zip up the scope tree until
593 // we find one that is.
594 while ((S->getFlags() & Scope::DeclScope) == 0)
595 S = S->getParent();
596
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000598 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000599 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000600 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000601
602 // In C++, the previous declaration we find might be a tag type
603 // (class or enum). In this case, the new declaration will hide the
604 // tag type.
605 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
606 PrevDecl = 0;
607
Chris Lattner82bb4792007-11-14 06:34:38 +0000608 QualType R = GetTypeForDeclarator(D, S);
609 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
610
Chris Lattner4b009652007-07-25 00:24:17 +0000611 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000612 // Check that there are no default arguments (C++ only).
613 if (getLangOptions().CPlusPlus)
614 CheckExtraCXXDefaultArguments(D);
615
Chris Lattner82bb4792007-11-14 06:34:38 +0000616 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000617 if (!NewTD) return 0;
618
619 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000620 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000621 // Merge the decl with the existing one if appropriate. If the decl is
622 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000623 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000624 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
625 if (NewTD == 0) return 0;
626 }
627 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000628 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000629 // C99 6.7.7p2: If a typedef name specifies a variably modified type
630 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000631 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
632 // FIXME: Diagnostic needs to be fixed.
633 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000634 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000635 }
636 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000637 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000638 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000639 switch (D.getDeclSpec().getStorageClassSpec()) {
640 default: assert(0 && "Unknown storage class!");
641 case DeclSpec::SCS_auto:
642 case DeclSpec::SCS_register:
643 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
644 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000645 InvalidDecl = true;
646 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000647 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
648 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
649 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000650 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000651 }
652
Chris Lattner4c7802b2008-03-15 21:24:04 +0000653 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000654 FunctionDecl *NewFD;
655 if (D.getContext() == Declarator::MemberContext) {
656 // This is a C++ method declaration.
657 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
658 D.getIdentifierLoc(), II, R,
659 (SC == FunctionDecl::Static), isInline,
660 LastDeclarator);
661 } else {
662 NewFD = FunctionDecl::Create(Context, CurContext,
663 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000664 II, R, SC, isInline, LastDeclarator,
665 // FIXME: Move to DeclGroup...
666 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000667 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000668 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000669 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000670
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000671 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000672 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000673 // The parser guarantees this is a string.
674 StringLiteral *SE = cast<StringLiteral>(E);
675 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
676 SE->getByteLength())));
677 }
678
Chris Lattner3e254fb2008-04-08 04:40:51 +0000679 // Copy the parameter declarations from the declarator D to
680 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000681 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000682 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
683
684 // Create Decl objects for each parameter, adding them to the
685 // FunctionDecl.
686 llvm::SmallVector<ParmVarDecl*, 16> Params;
687
688 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
689 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000690 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000691 // We let through "const void" here because Sema::GetTypeForDeclarator
692 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000693 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
694 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000695 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
696 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000697 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
698
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000699 // In C++, the empty parameter-type-list must be spelled "void"; a
700 // typedef of void is not permitted.
701 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000702 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000703 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
704 }
705
Eli Friedman769e7302008-08-25 21:31:01 +0000706 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000707 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
708 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
709 }
710
711 NewFD->setParams(&Params[0], Params.size());
712 }
713
Steve Narofff8a09432008-01-09 23:34:55 +0000714 // Merge the decl with the existing one if appropriate. Since C functions
715 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000716 if (PrevDecl &&
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000717 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000718 bool Redeclaration = false;
719 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000720 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000721 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000722 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000723 }
Chris Lattner4b009652007-07-25 00:24:17 +0000724 }
725 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000726
727 // In C++, check default arguments now that we have merged decls.
728 if (getLangOptions().CPlusPlus)
729 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000730 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000731 // Check that there are no default arguments (C++ only).
732 if (getLangOptions().CPlusPlus)
733 CheckExtraCXXDefaultArguments(D);
734
Ted Kremenek42730c52008-01-07 19:49:32 +0000735 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000736 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
737 D.getIdentifier()->getName());
738 InvalidDecl = true;
739 }
Chris Lattner4b009652007-07-25 00:24:17 +0000740
741 VarDecl *NewVD;
742 VarDecl::StorageClass SC;
743 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000744 default: assert(0 && "Unknown storage class!");
745 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
746 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
747 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
748 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
749 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
750 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000751 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000752 if (D.getContext() == Declarator::MemberContext) {
753 assert(SC == VarDecl::Static && "Invalid storage class for member!");
754 // This is a static data member for a C++ class.
755 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
756 D.getIdentifierLoc(), II,
757 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000758 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000759 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000760 if (S->getFnParent() == 0) {
761 // C99 6.9p2: The storage-class specifiers auto and register shall not
762 // appear in the declaration specifiers in an external declaration.
763 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
764 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
765 R.getAsString());
766 InvalidDecl = true;
767 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000768 }
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000769 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000770 II, R, SC, LastDeclarator,
771 // FIXME: Move to DeclGroup...
772 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000773 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +0000774 }
Chris Lattner4b009652007-07-25 00:24:17 +0000775 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000776 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000777
Daniel Dunbarced89142008-08-06 00:03:29 +0000778 // Handle GNU asm-label extension (encoded as an attribute).
779 if (Expr *E = (Expr*) D.getAsmLabel()) {
780 // The parser guarantees this is a string.
781 StringLiteral *SE = cast<StringLiteral>(E);
782 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
783 SE->getByteLength())));
784 }
785
Nate Begemanea583262008-03-14 18:07:10 +0000786 // Emit an error if an address space was applied to decl with local storage.
787 // This includes arrays of objects with address space qualifiers, but not
788 // automatic variables that point to other address spaces.
789 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000790 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
791 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
792 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000793 }
Steve Narofff8a09432008-01-09 23:34:55 +0000794 // Merge the decl with the existing one if appropriate. If the decl is
795 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000796 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000797 NewVD = MergeVarDecl(NewVD, PrevDecl);
798 if (NewVD == 0) return 0;
799 }
Chris Lattner4b009652007-07-25 00:24:17 +0000800 New = NewVD;
801 }
802
803 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000804 if (II)
805 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000806 // If any semantic error occurred, mark the decl as invalid.
807 if (D.getInvalidType() || InvalidDecl)
808 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000809
810 return New;
811}
812
Eli Friedman02c22ce2008-05-20 13:48:25 +0000813bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
814 switch (Init->getStmtClass()) {
815 default:
816 Diag(Init->getExprLoc(),
817 diag::err_init_element_not_constant, Init->getSourceRange());
818 return true;
819 case Expr::ParenExprClass: {
820 const ParenExpr* PE = cast<ParenExpr>(Init);
821 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
822 }
823 case Expr::CompoundLiteralExprClass:
824 return cast<CompoundLiteralExpr>(Init)->isFileScope();
825 case Expr::DeclRefExprClass: {
826 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000827 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
828 if (VD->hasGlobalStorage())
829 return false;
830 Diag(Init->getExprLoc(),
831 diag::err_init_element_not_constant, Init->getSourceRange());
832 return true;
833 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000834 if (isa<FunctionDecl>(D))
835 return false;
836 Diag(Init->getExprLoc(),
837 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000838 return true;
839 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000840 case Expr::MemberExprClass: {
841 const MemberExpr *M = cast<MemberExpr>(Init);
842 if (M->isArrow())
843 return CheckAddressConstantExpression(M->getBase());
844 return CheckAddressConstantExpressionLValue(M->getBase());
845 }
846 case Expr::ArraySubscriptExprClass: {
847 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
848 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
849 return CheckAddressConstantExpression(ASE->getBase()) ||
850 CheckArithmeticConstantExpression(ASE->getIdx());
851 }
852 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000853 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000854 return false;
855 case Expr::UnaryOperatorClass: {
856 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
857
858 // C99 6.6p9
859 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000860 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000861
862 Diag(Init->getExprLoc(),
863 diag::err_init_element_not_constant, Init->getSourceRange());
864 return true;
865 }
866 }
867}
868
869bool Sema::CheckAddressConstantExpression(const Expr* Init) {
870 switch (Init->getStmtClass()) {
871 default:
872 Diag(Init->getExprLoc(),
873 diag::err_init_element_not_constant, Init->getSourceRange());
874 return true;
875 case Expr::ParenExprClass: {
876 const ParenExpr* PE = cast<ParenExpr>(Init);
877 return CheckAddressConstantExpression(PE->getSubExpr());
878 }
879 case Expr::StringLiteralClass:
880 case Expr::ObjCStringLiteralClass:
881 return false;
882 case Expr::CallExprClass: {
883 const CallExpr *CE = cast<CallExpr>(Init);
Daniel Dunbar07253c72008-10-02 23:30:31 +0000884 if (CE->isBuiltinConstantExpr(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +0000885 return false;
886 Diag(Init->getExprLoc(),
887 diag::err_init_element_not_constant, Init->getSourceRange());
888 return true;
889 }
890 case Expr::UnaryOperatorClass: {
891 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
892
893 // C99 6.6p9
894 if (Exp->getOpcode() == UnaryOperator::AddrOf)
895 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
896
897 if (Exp->getOpcode() == UnaryOperator::Extension)
898 return CheckAddressConstantExpression(Exp->getSubExpr());
899
900 Diag(Init->getExprLoc(),
901 diag::err_init_element_not_constant, Init->getSourceRange());
902 return true;
903 }
904 case Expr::BinaryOperatorClass: {
905 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
906 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
907
908 Expr *PExp = Exp->getLHS();
909 Expr *IExp = Exp->getRHS();
910 if (IExp->getType()->isPointerType())
911 std::swap(PExp, IExp);
912
913 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
914 return CheckAddressConstantExpression(PExp) ||
915 CheckArithmeticConstantExpression(IExp);
916 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000917 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000918 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000919 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000920 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
921 // Check for implicit promotion
922 if (SubExpr->getType()->isFunctionType() ||
923 SubExpr->getType()->isArrayType())
924 return CheckAddressConstantExpressionLValue(SubExpr);
925 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000926
927 // Check for pointer->pointer cast
928 if (SubExpr->getType()->isPointerType())
929 return CheckAddressConstantExpression(SubExpr);
930
Eli Friedman1fad3c62008-08-25 20:46:57 +0000931 if (SubExpr->getType()->isIntegralType()) {
932 // Check for the special-case of a pointer->int->pointer cast;
933 // this isn't standard, but some code requires it. See
934 // PR2720 for an example.
935 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
936 if (SubCast->getSubExpr()->getType()->isPointerType()) {
937 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
938 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
939 if (IntWidth >= PointerWidth) {
940 return CheckAddressConstantExpression(SubCast->getSubExpr());
941 }
942 }
943 }
944 }
945 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000946 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000947 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000948
949 Diag(Init->getExprLoc(),
950 diag::err_init_element_not_constant, Init->getSourceRange());
951 return true;
952 }
953 case Expr::ConditionalOperatorClass: {
954 // FIXME: Should we pedwarn here?
955 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
956 if (!Exp->getCond()->getType()->isArithmeticType()) {
957 Diag(Init->getExprLoc(),
958 diag::err_init_element_not_constant, Init->getSourceRange());
959 return true;
960 }
961 if (CheckArithmeticConstantExpression(Exp->getCond()))
962 return true;
963 if (Exp->getLHS() &&
964 CheckAddressConstantExpression(Exp->getLHS()))
965 return true;
966 return CheckAddressConstantExpression(Exp->getRHS());
967 }
968 case Expr::AddrLabelExprClass:
969 return false;
970 }
971}
972
Eli Friedman998dffb2008-06-09 05:05:07 +0000973static const Expr* FindExpressionBaseAddress(const Expr* E);
974
975static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
976 switch (E->getStmtClass()) {
977 default:
978 return E;
979 case Expr::ParenExprClass: {
980 const ParenExpr* PE = cast<ParenExpr>(E);
981 return FindExpressionBaseAddressLValue(PE->getSubExpr());
982 }
983 case Expr::MemberExprClass: {
984 const MemberExpr *M = cast<MemberExpr>(E);
985 if (M->isArrow())
986 return FindExpressionBaseAddress(M->getBase());
987 return FindExpressionBaseAddressLValue(M->getBase());
988 }
989 case Expr::ArraySubscriptExprClass: {
990 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
991 return FindExpressionBaseAddress(ASE->getBase());
992 }
993 case Expr::UnaryOperatorClass: {
994 const UnaryOperator *Exp = cast<UnaryOperator>(E);
995
996 if (Exp->getOpcode() == UnaryOperator::Deref)
997 return FindExpressionBaseAddress(Exp->getSubExpr());
998
999 return E;
1000 }
1001 }
1002}
1003
1004static const Expr* FindExpressionBaseAddress(const Expr* E) {
1005 switch (E->getStmtClass()) {
1006 default:
1007 return E;
1008 case Expr::ParenExprClass: {
1009 const ParenExpr* PE = cast<ParenExpr>(E);
1010 return FindExpressionBaseAddress(PE->getSubExpr());
1011 }
1012 case Expr::UnaryOperatorClass: {
1013 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1014
1015 // C99 6.6p9
1016 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1017 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1018
1019 if (Exp->getOpcode() == UnaryOperator::Extension)
1020 return FindExpressionBaseAddress(Exp->getSubExpr());
1021
1022 return E;
1023 }
1024 case Expr::BinaryOperatorClass: {
1025 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1026
1027 Expr *PExp = Exp->getLHS();
1028 Expr *IExp = Exp->getRHS();
1029 if (IExp->getType()->isPointerType())
1030 std::swap(PExp, IExp);
1031
1032 return FindExpressionBaseAddress(PExp);
1033 }
1034 case Expr::ImplicitCastExprClass: {
1035 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1036
1037 // Check for implicit promotion
1038 if (SubExpr->getType()->isFunctionType() ||
1039 SubExpr->getType()->isArrayType())
1040 return FindExpressionBaseAddressLValue(SubExpr);
1041
1042 // Check for pointer->pointer cast
1043 if (SubExpr->getType()->isPointerType())
1044 return FindExpressionBaseAddress(SubExpr);
1045
1046 // We assume that we have an arithmetic expression here;
1047 // if we don't, we'll figure it out later
1048 return 0;
1049 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001050 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001051 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1052
1053 // Check for pointer->pointer cast
1054 if (SubExpr->getType()->isPointerType())
1055 return FindExpressionBaseAddress(SubExpr);
1056
1057 // We assume that we have an arithmetic expression here;
1058 // if we don't, we'll figure it out later
1059 return 0;
1060 }
1061 }
1062}
1063
Eli Friedman02c22ce2008-05-20 13:48:25 +00001064bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1065 switch (Init->getStmtClass()) {
1066 default:
1067 Diag(Init->getExprLoc(),
1068 diag::err_init_element_not_constant, Init->getSourceRange());
1069 return true;
1070 case Expr::ParenExprClass: {
1071 const ParenExpr* PE = cast<ParenExpr>(Init);
1072 return CheckArithmeticConstantExpression(PE->getSubExpr());
1073 }
1074 case Expr::FloatingLiteralClass:
1075 case Expr::IntegerLiteralClass:
1076 case Expr::CharacterLiteralClass:
1077 case Expr::ImaginaryLiteralClass:
1078 case Expr::TypesCompatibleExprClass:
1079 case Expr::CXXBoolLiteralExprClass:
1080 return false;
1081 case Expr::CallExprClass: {
1082 const CallExpr *CE = cast<CallExpr>(Init);
Daniel Dunbar07253c72008-10-02 23:30:31 +00001083 if (CE->isBuiltinConstantExpr(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001084 return false;
1085 Diag(Init->getExprLoc(),
1086 diag::err_init_element_not_constant, Init->getSourceRange());
1087 return true;
1088 }
1089 case Expr::DeclRefExprClass: {
1090 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1091 if (isa<EnumConstantDecl>(D))
1092 return false;
1093 Diag(Init->getExprLoc(),
1094 diag::err_init_element_not_constant, Init->getSourceRange());
1095 return true;
1096 }
1097 case Expr::CompoundLiteralExprClass:
1098 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1099 // but vectors are allowed to be magic.
1100 if (Init->getType()->isVectorType())
1101 return false;
1102 Diag(Init->getExprLoc(),
1103 diag::err_init_element_not_constant, Init->getSourceRange());
1104 return true;
1105 case Expr::UnaryOperatorClass: {
1106 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1107
1108 switch (Exp->getOpcode()) {
1109 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1110 // See C99 6.6p3.
1111 default:
1112 Diag(Init->getExprLoc(),
1113 diag::err_init_element_not_constant, Init->getSourceRange());
1114 return true;
1115 case UnaryOperator::SizeOf:
1116 case UnaryOperator::AlignOf:
1117 case UnaryOperator::OffsetOf:
1118 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1119 // See C99 6.5.3.4p2 and 6.6p3.
1120 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1121 return false;
1122 Diag(Init->getExprLoc(),
1123 diag::err_init_element_not_constant, Init->getSourceRange());
1124 return true;
1125 case UnaryOperator::Extension:
1126 case UnaryOperator::LNot:
1127 case UnaryOperator::Plus:
1128 case UnaryOperator::Minus:
1129 case UnaryOperator::Not:
1130 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1131 }
1132 }
1133 case Expr::SizeOfAlignOfTypeExprClass: {
1134 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1135 // Special check for void types, which are allowed as an extension
1136 if (Exp->getArgumentType()->isVoidType())
1137 return false;
1138 // alignof always evaluates to a constant.
1139 // FIXME: is sizeof(int[3.0]) a constant expression?
1140 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1141 Diag(Init->getExprLoc(),
1142 diag::err_init_element_not_constant, Init->getSourceRange());
1143 return true;
1144 }
1145 return false;
1146 }
1147 case Expr::BinaryOperatorClass: {
1148 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1149
1150 if (Exp->getLHS()->getType()->isArithmeticType() &&
1151 Exp->getRHS()->getType()->isArithmeticType()) {
1152 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1153 CheckArithmeticConstantExpression(Exp->getRHS());
1154 }
1155
Eli Friedman998dffb2008-06-09 05:05:07 +00001156 if (Exp->getLHS()->getType()->isPointerType() &&
1157 Exp->getRHS()->getType()->isPointerType()) {
1158 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1159 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1160
1161 // Only allow a null (constant integer) base; we could
1162 // allow some additional cases if necessary, but this
1163 // is sufficient to cover offsetof-like constructs.
1164 if (!LHSBase && !RHSBase) {
1165 return CheckAddressConstantExpression(Exp->getLHS()) ||
1166 CheckAddressConstantExpression(Exp->getRHS());
1167 }
1168 }
1169
Eli Friedman02c22ce2008-05-20 13:48:25 +00001170 Diag(Init->getExprLoc(),
1171 diag::err_init_element_not_constant, Init->getSourceRange());
1172 return true;
1173 }
1174 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001175 case Expr::ExplicitCastExprClass: {
1176 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001177 if (SubExpr->getType()->isArithmeticType())
1178 return CheckArithmeticConstantExpression(SubExpr);
1179
Eli Friedman266df142008-09-02 09:37:00 +00001180 if (SubExpr->getType()->isPointerType()) {
1181 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1182 // If the pointer has a null base, this is an offsetof-like construct
1183 if (!Base)
1184 return CheckAddressConstantExpression(SubExpr);
1185 }
1186
Eli Friedmand662caa2008-09-01 22:08:17 +00001187 Diag(Init->getExprLoc(),
1188 diag::err_init_element_not_constant, Init->getSourceRange());
1189 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001190 }
1191 case Expr::ConditionalOperatorClass: {
1192 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001193
1194 // If GNU extensions are disabled, we require all operands to be arithmetic
1195 // constant expressions.
1196 if (getLangOptions().NoExtensions) {
1197 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1198 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1199 CheckArithmeticConstantExpression(Exp->getRHS());
1200 }
1201
1202 // Otherwise, we have to emulate some of the behavior of fold here.
1203 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1204 // because it can constant fold things away. To retain compatibility with
1205 // GCC code, we see if we can fold the condition to a constant (which we
1206 // should always be able to do in theory). If so, we only require the
1207 // specified arm of the conditional to be a constant. This is a horrible
1208 // hack, but is require by real world code that uses __builtin_constant_p.
1209 APValue Val;
1210 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1211 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1212 // won't be able to either. Use it to emit the diagnostic though.
1213 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1214 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1215 return Res;
1216 }
1217
1218 // Verify that the side following the condition is also a constant.
1219 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1220 if (Val.getInt() == 0)
1221 std::swap(TrueSide, FalseSide);
1222
1223 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001224 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001225
1226 // Okay, the evaluated side evaluates to a constant, so we accept this.
1227 // Check to see if the other side is obviously not a constant. If so,
1228 // emit a warning that this is a GNU extension.
1229 if (FalseSide && !FalseSide->tryEvaluate(Val, Context))
1230 Diag(Init->getExprLoc(),
1231 diag::ext_typecheck_expression_not_constant_but_accepted,
1232 FalseSide->getSourceRange());
1233 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001234 }
1235 }
1236}
1237
1238bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001239 Init = Init->IgnoreParens();
1240
Eli Friedman02c22ce2008-05-20 13:48:25 +00001241 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1242 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1243 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1244
Nuno Lopese7280452008-07-07 16:46:50 +00001245 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1246 return CheckForConstantInitializer(e->getInitializer(), DclT);
1247
Eli Friedman02c22ce2008-05-20 13:48:25 +00001248 if (Init->getType()->isReferenceType()) {
Chris Lattner94d45412008-10-06 05:42:39 +00001249 // FIXME: Work out how the heck references work.
Eli Friedman02c22ce2008-05-20 13:48:25 +00001250 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001251 }
1252
1253 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1254 unsigned numInits = Exp->getNumInits();
1255 for (unsigned i = 0; i < numInits; i++) {
1256 // FIXME: Need to get the type of the declaration for C++,
1257 // because it could be a reference?
1258 if (CheckForConstantInitializer(Exp->getInit(i),
1259 Exp->getInit(i)->getType()))
1260 return true;
1261 }
1262 return false;
1263 }
1264
1265 if (Init->isNullPointerConstant(Context))
1266 return false;
1267 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001268 QualType InitTy = Context.getCanonicalType(Init->getType())
1269 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001270 if (InitTy == Context.BoolTy) {
1271 // Special handling for pointers implicitly cast to bool;
1272 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1273 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1274 Expr* SubE = ICE->getSubExpr();
1275 if (SubE->getType()->isPointerType() ||
1276 SubE->getType()->isArrayType() ||
1277 SubE->getType()->isFunctionType()) {
1278 return CheckAddressConstantExpression(Init);
1279 }
1280 }
1281 } else if (InitTy->isIntegralType()) {
1282 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001283 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001284 SubE = CE->getSubExpr();
1285 // Special check for pointer cast to int; we allow as an extension
1286 // an address constant cast to an integer if the integer
1287 // is of an appropriate width (this sort of code is apparently used
1288 // in some places).
1289 // FIXME: Add pedwarn?
1290 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1291 if (SubE && (SubE->getType()->isPointerType() ||
1292 SubE->getType()->isArrayType() ||
1293 SubE->getType()->isFunctionType())) {
1294 unsigned IntWidth = Context.getTypeSize(Init->getType());
1295 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1296 if (IntWidth >= PointerWidth)
1297 return CheckAddressConstantExpression(Init);
1298 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001299 }
1300
1301 return CheckArithmeticConstantExpression(Init);
1302 }
1303
1304 if (Init->getType()->isPointerType())
1305 return CheckAddressConstantExpression(Init);
1306
Eli Friedman25086f02008-05-30 18:14:48 +00001307 // An array type at the top level that isn't an init-list must
1308 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001309 if (Init->getType()->isArrayType())
1310 return false;
1311
Nuno Lopes1dc26762008-09-01 18:42:41 +00001312 if (Init->getType()->isFunctionType())
1313 return false;
1314
Steve Naroffdff3fb22008-10-02 17:12:56 +00001315 // Allow block exprs at top level.
1316 if (Init->getType()->isBlockPointerType())
1317 return false;
1318
Eli Friedman02c22ce2008-05-20 13:48:25 +00001319 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1320 Init->getSourceRange());
1321 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001322}
1323
Steve Naroff6a0e2092007-09-12 14:07:44 +00001324void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001325 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001326 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001327 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001328
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001329 // If there is no declaration, there was an error parsing it. Just ignore
1330 // the initializer.
1331 if (RealDecl == 0) {
1332 delete Init;
1333 return;
1334 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001335
Steve Naroff420d0f52007-09-12 20:13:48 +00001336 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1337 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001338 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1339 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001340 RealDecl->setInvalidDecl();
1341 return;
1342 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001343 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001344 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001345 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001346 if (VDecl->isBlockVarDecl()) {
1347 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001348 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001349 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001350 VDecl->setInvalidDecl();
1351 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001352 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001353 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001354
1355 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1356 if (!getLangOptions().CPlusPlus) {
1357 if (SC == VarDecl::Static) // C99 6.7.8p4.
1358 CheckForConstantInitializer(Init, DclT);
1359 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001360 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001361 } else if (VDecl->isFileVarDecl()) {
1362 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001363 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001364 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001365 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001366 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001367
Anders Carlssonea7140a2008-08-22 05:00:02 +00001368 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1369 if (!getLangOptions().CPlusPlus) {
1370 // C99 6.7.8p4. All file scoped initializers need to be constant.
1371 CheckForConstantInitializer(Init, DclT);
1372 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001373 }
1374 // If the type changed, it means we had an incomplete type that was
1375 // completed by the initializer. For example:
1376 // int ary[] = { 1, 3, 5 };
1377 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001378 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001379 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001380 Init->setType(DclT);
1381 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001382
1383 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001384 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001385 return;
1386}
1387
Chris Lattner4b009652007-07-25 00:24:17 +00001388/// The declarators are chained together backwards, reverse the list.
1389Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1390 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001391 Decl *GroupDecl = static_cast<Decl*>(group);
1392 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001393 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001394
1395 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1396 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001397 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001398 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001399 else { // reverse the list.
1400 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001401 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001402 Group->setNextDeclarator(NewGroup);
1403 NewGroup = Group;
1404 Group = Next;
1405 }
1406 }
1407 // Perform semantic analysis that depends on having fully processed both
1408 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001409 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001410 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1411 if (!IDecl)
1412 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001413 QualType T = IDecl->getType();
1414
1415 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1416 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001417 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1418 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001419 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001420 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1421 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001422 }
1423 }
1424 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1425 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001426 if (IDecl->isBlockVarDecl() &&
1427 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001428 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001429 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1430 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001431 IDecl->setInvalidDecl();
1432 }
1433 }
1434 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1435 // object that has file scope without an initializer, and without a
1436 // storage-class specifier or with the storage-class specifier "static",
1437 // constitutes a tentative definition. Note: A tentative definition with
1438 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001439 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001440 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001441 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1442 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001443 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001444 // C99 6.9.2p3: If the declaration of an identifier for an object is
1445 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1446 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001447 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1448 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001449 IDecl->setInvalidDecl();
1450 }
1451 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001452 if (IDecl->isFileVarDecl())
1453 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001454 }
1455 return NewGroup;
1456}
Steve Naroff91b03f72007-08-28 03:03:08 +00001457
Chris Lattner3e254fb2008-04-08 04:40:51 +00001458/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1459/// to introduce parameters into function prototype scope.
1460Sema::DeclTy *
1461Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001462 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001463
1464 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001465 VarDecl::StorageClass StorageClass = VarDecl::None;
1466 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1467 StorageClass = VarDecl::Register;
1468 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001469 Diag(DS.getStorageClassSpecLoc(),
1470 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001471 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001472 }
1473 if (DS.isThreadSpecified()) {
1474 Diag(DS.getThreadSpecLoc(),
1475 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001476 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001477 }
1478
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001479 // Check that there are no default arguments inside the type of this
1480 // parameter (C++ only).
1481 if (getLangOptions().CPlusPlus)
1482 CheckExtraCXXDefaultArguments(D);
1483
Chris Lattner3e254fb2008-04-08 04:40:51 +00001484 // In this context, we *do not* check D.getInvalidType(). If the declarator
1485 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1486 // though it will not reflect the user specified type.
1487 QualType parmDeclType = GetTypeForDeclarator(D, S);
1488
1489 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1490
Chris Lattner4b009652007-07-25 00:24:17 +00001491 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1492 // Can this happen for params? We already checked that they don't conflict
1493 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001494 IdentifierInfo *II = D.getIdentifier();
1495 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1496 if (S->isDeclScope(PrevDecl)) {
1497 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1498 dyn_cast<NamedDecl>(PrevDecl)->getName());
1499
1500 // Recover by removing the name
1501 II = 0;
1502 D.SetIdentifier(0, D.getIdentifierLoc());
1503 }
Chris Lattner4b009652007-07-25 00:24:17 +00001504 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001505
1506 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1507 // Doing the promotion here has a win and a loss. The win is the type for
1508 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1509 // code generator). The loss is the orginal type isn't preserved. For example:
1510 //
1511 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1512 // int blockvardecl[5];
1513 // sizeof(parmvardecl); // size == 4
1514 // sizeof(blockvardecl); // size == 20
1515 // }
1516 //
1517 // For expressions, all implicit conversions are captured using the
1518 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1519 //
1520 // FIXME: If a source translation tool needs to see the original type, then
1521 // we need to consider storing both types (in ParmVarDecl)...
1522 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001523 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001524 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001525 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001526 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001527 parmDeclType = Context.getPointerType(parmDeclType);
1528
Chris Lattner3e254fb2008-04-08 04:40:51 +00001529 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1530 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001531 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001532 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001533
Chris Lattner3e254fb2008-04-08 04:40:51 +00001534 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001535 New->setInvalidDecl();
1536
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001537 if (II)
1538 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001539
Chris Lattner9b384ca2008-06-29 00:02:00 +00001540 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001541 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001542
Chris Lattner4b009652007-07-25 00:24:17 +00001543}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001544
Chris Lattnerea148702007-10-09 17:14:05 +00001545Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001546 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001547 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1548 "Not a function declarator!");
1549 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001550
Chris Lattner4b009652007-07-25 00:24:17 +00001551 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1552 // for a K&R function.
1553 if (!FTI.hasPrototype) {
1554 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001555 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001556 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1557 FTI.ArgInfo[i].Ident->getName());
1558 // Implicitly declare the argument as type 'int' for lack of a better
1559 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001560 DeclSpec DS;
1561 const char* PrevSpec; // unused
1562 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1563 PrevSpec);
1564 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1565 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1566 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001567 }
1568 }
Chris Lattner4b009652007-07-25 00:24:17 +00001569 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001570 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001571 }
1572
1573 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001574
1575 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001576 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001577 GlobalScope);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001578 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001579 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1580 const FunctionDecl *Definition;
1581 if (FD->getBody(Definition)) {
1582 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1583 D.getIdentifier()->getName());
1584 Diag(Definition->getLocation(), diag::err_previous_definition);
1585 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001586 }
1587 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001588
1589 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001590 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001591}
1592
1593Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1594 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001595 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001596 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001597
1598 // Check the validity of our function parameters
1599 CheckParmsForFunctionDef(FD);
1600
1601 // Introduce our parameters into the function scope
1602 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1603 ParmVarDecl *Param = FD->getParamDecl(p);
1604 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001605 if (Param->getIdentifier())
1606 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001607 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001608
Chris Lattner4b009652007-07-25 00:24:17 +00001609 return FD;
1610}
1611
Steve Naroff99ee4302007-11-11 23:20:51 +00001612Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1613 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001614 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001615 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001616 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001617 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001618 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001619 } else
1620 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001621 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001622 // Verify and clean out per-function state.
1623
1624 // Check goto/label use.
1625 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1626 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1627 // Verify that we have no forward references left. If so, there was a goto
1628 // or address of a label taken, but no definition of it. Label fwd
1629 // definitions are indicated with a null substmt.
1630 if (I->second->getSubStmt() == 0) {
1631 LabelStmt *L = I->second;
1632 // Emit error.
1633 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1634
1635 // At this point, we have gotos that use the bogus label. Stitch it into
1636 // the function body so that they aren't leaked and that the AST is well
1637 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001638 if (Body) {
1639 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1640 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1641 } else {
1642 // The whole function wasn't parsed correctly, just delete this.
1643 delete L;
1644 }
Chris Lattner4b009652007-07-25 00:24:17 +00001645 }
1646 }
1647 LabelMap.clear();
1648
Steve Naroff99ee4302007-11-11 23:20:51 +00001649 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001650}
1651
Chris Lattner4b009652007-07-25 00:24:17 +00001652/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1653/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001654ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1655 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001656 // Extension in C99. Legal in C90, but warn about it.
1657 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001658 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001659 else
Chris Lattner4b009652007-07-25 00:24:17 +00001660 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1661
1662 // FIXME: handle stuff like:
1663 // void foo() { extern float X(); }
1664 // void bar() { X(); } <-- implicit decl for X in another scope.
1665
1666 // Set a Declarator for the implicit definition: int foo();
1667 const char *Dummy;
1668 DeclSpec DS;
1669 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1670 Error = Error; // Silence warning.
1671 assert(!Error && "Error setting up implicit decl!");
1672 Declarator D(DS, Declarator::BlockContext);
1673 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1674 D.SetIdentifier(&II, Loc);
1675
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001676 // Insert this function into translation-unit scope.
1677
1678 DeclContext *PrevDC = CurContext;
1679 CurContext = Context.getTranslationUnitDecl();
1680
Steve Naroff9104f3c2008-04-04 14:32:09 +00001681 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001682 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001683 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001684
1685 CurContext = PrevDC;
1686
Steve Naroff9104f3c2008-04-04 14:32:09 +00001687 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001688}
1689
1690
Chris Lattner82bb4792007-11-14 06:34:38 +00001691TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001692 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001693 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001694 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001695
1696 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001697 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1698 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001699 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001700 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001701 if (D.getInvalidType())
1702 NewTD->setInvalidDecl();
1703 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001704}
1705
Steve Naroff0acc9c92007-09-15 18:49:24 +00001706/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001707/// former case, Name will be non-null. In the later case, Name will be null.
1708/// TagType indicates what kind of tag this is. TK indicates whether this is a
1709/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001710Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001711 SourceLocation KWLoc, IdentifierInfo *Name,
1712 SourceLocation NameLoc, AttributeList *Attr) {
1713 // If this is a use of an existing tag, it must have a name.
1714 assert((Name != 0 || TK == TK_Definition) &&
1715 "Nameless record must be a definition!");
1716
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001717 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001718 switch (TagType) {
1719 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001720 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1721 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1722 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1723 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001724 }
1725
Ted Kremenek46a837c2008-09-05 17:16:31 +00001726 // Two code paths: a new one for structs/unions/classes where we create
1727 // separate decls for forward declarations, and an old (eventually to
1728 // be removed) code path for enums.
1729 if (Kind != TagDecl::TK_enum)
1730 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1731
Chris Lattner4b009652007-07-25 00:24:17 +00001732 // If this is a named struct, check to see if there was a previous forward
1733 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001734 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenekd4434152008-09-02 21:26:19 +00001735 ScopedDecl *PrevDecl =
1736 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1737
1738 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001739 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1740 "unexpected Decl type");
1741 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001742 // If this is a use of a previous tag, or if the tag is already declared
1743 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001744 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001745 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001746 // Make sure that this wasn't declared as an enum and now used as a
1747 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001748 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001749 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1750 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001751 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001752 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001753 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001754 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001755 // If this is a use or a forward declaration, we're good.
1756 if (TK != TK_Definition)
1757 return PrevDecl;
1758
1759 // Diagnose attempts to redefine a tag.
1760 if (PrevTagDecl->isDefinition()) {
1761 Diag(NameLoc, diag::err_redefinition, Name->getName());
1762 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1763 // If this is a redefinition, recover by making this struct be
1764 // anonymous, which will make any later references get the previous
1765 // definition.
1766 Name = 0;
1767 } else {
1768 // Okay, this is definition of a previously declared or referenced
1769 // tag. Move the location of the decl to be the definition site.
1770 PrevDecl->setLocation(NameLoc);
1771 return PrevDecl;
1772 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001773 }
Chris Lattner4b009652007-07-25 00:24:17 +00001774 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001775 // If we get here, this is a definition of a new struct type in a nested
1776 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1777 // type.
1778 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001779 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001780 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00001781 // The tag name clashes with a namespace name, issue an error and
1782 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001783 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1784 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1785 Name = 0;
1786 }
Chris Lattner4b009652007-07-25 00:24:17 +00001787 }
Chris Lattner4b009652007-07-25 00:24:17 +00001788 }
1789
1790 // If there is an identifier, use the location of the identifier as the
1791 // location of the decl, otherwise use the location of the struct/union
1792 // keyword.
1793 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1794
1795 // Otherwise, if this is the first time we've seen this tag, create the decl.
1796 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001797 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001798 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1799 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001800 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001801 // If this is an undefined enum, warn.
1802 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001803 } else {
1804 // struct/union/class
1805
Chris Lattner4b009652007-07-25 00:24:17 +00001806 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1807 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001808 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001809 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek2c984042008-09-05 01:34:33 +00001810 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001811 else
Ted Kremenek2c984042008-09-05 01:34:33 +00001812 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001813 }
Chris Lattner4b009652007-07-25 00:24:17 +00001814
1815 // If this has an identifier, add it to the scope stack.
1816 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001817 // The scope passed in may not be a decl scope. Zip up the scope tree until
1818 // we find one that is.
1819 while ((S->getFlags() & Scope::DeclScope) == 0)
1820 S = S->getParent();
1821
1822 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001823 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001824 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001825
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001826 if (Attr)
1827 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001828 return New;
1829}
1830
Ted Kremenek46a837c2008-09-05 17:16:31 +00001831/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1832/// the logic for enums, we create separate decls for forward declarations.
1833/// This is called by ActOnTag, but eventually will replace its logic.
1834Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1835 SourceLocation KWLoc, IdentifierInfo *Name,
1836 SourceLocation NameLoc, AttributeList *Attr) {
1837
1838 // If this is a named struct, check to see if there was a previous forward
1839 // declaration or definition.
1840 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1841 ScopedDecl *PrevDecl =
1842 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1843
1844 if (PrevDecl) {
1845 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1846 "unexpected Decl type");
1847
1848 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1849 // If this is a use of a previous tag, or if the tag is already declared
1850 // in the same scope (so that the definition/declaration completes or
1851 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001852 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00001853 // Make sure that this wasn't declared as an enum and now used as a
1854 // struct or something similar.
1855 if (PrevTagDecl->getTagKind() != Kind) {
1856 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1857 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1858 // Recover by making this an anonymous redefinition.
1859 Name = 0;
1860 PrevDecl = 0;
1861 } else {
1862 // If this is a use, return the original decl.
1863
1864 // FIXME: In the future, return a variant or some other clue
1865 // for the consumer of this Decl to know it doesn't own it.
1866 // For our current ASTs this shouldn't be a problem, but will
1867 // need to be changed with DeclGroups.
1868 if (TK == TK_Reference)
1869 return PrevDecl;
1870
1871 // The new decl is a definition?
1872 if (TK == TK_Definition) {
1873 // Diagnose attempts to redefine a tag.
1874 if (RecordDecl* DefRecord =
1875 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1876 Diag(NameLoc, diag::err_redefinition, Name->getName());
1877 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1878 // If this is a redefinition, recover by making this struct be
1879 // anonymous, which will make any later references get the previous
1880 // definition.
1881 Name = 0;
1882 PrevDecl = 0;
1883 }
1884 // Okay, this is definition of a previously declared or referenced
1885 // tag. We're going to create a new Decl.
1886 }
1887 }
1888 // If we get here we have (another) forward declaration. Just create
1889 // a new decl.
1890 }
1891 else {
1892 // If we get here, this is a definition of a new struct type in a nested
1893 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1894 // new decl/type. We set PrevDecl to NULL so that the Records
1895 // have distinct types.
1896 PrevDecl = 0;
1897 }
1898 } else {
1899 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001900 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00001901 // The tag name clashes with a namespace name, issue an error and
1902 // recover by making this tag be anonymous.
1903 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1904 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1905 Name = 0;
1906 }
1907 }
1908 }
1909
1910 // If there is an identifier, use the location of the identifier as the
1911 // location of the decl, otherwise use the location of the struct/union
1912 // keyword.
1913 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1914
1915 // Otherwise, if this is the first time we've seen this tag, create the decl.
1916 TagDecl *New;
1917
1918 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1919 // struct X { int A; } D; D should chain to X.
1920 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001921 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001922 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1923 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1924 else
1925 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1926 dyn_cast_or_null<RecordDecl>(PrevDecl));
1927
1928 // If this has an identifier, add it to the scope stack.
1929 if ((TK == TK_Definition || !PrevDecl) && Name) {
1930 // The scope passed in may not be a decl scope. Zip up the scope tree until
1931 // we find one that is.
1932 while ((S->getFlags() & Scope::DeclScope) == 0)
1933 S = S->getParent();
1934
1935 // Add it to the decl chain.
1936 PushOnScopeChains(New, S);
1937 }
1938
1939 if (Attr)
1940 ProcessDeclAttributeList(New, Attr);
1941
1942 return New;
1943}
1944
1945
Chris Lattner1bf58f62008-06-21 19:39:06 +00001946/// Collect the instance variables declared in an Objective-C object. Used in
1947/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001948static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001949 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001950 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001951 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1952
1953 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00001954 for (ObjCInterfaceDecl::ivar_iterator
1955 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1956
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001957 ObjCIvarDecl* ID = *I;
1958 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1959 ID->getIdentifier(),
1960 ID->getType(),
1961 ID->getBitWidth()));
1962 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001963}
1964
1965/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1966/// instance variables of ClassName into Decls.
1967void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1968 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001969 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001970 // Check that ClassName is a valid class
1971 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1972 if (!Class) {
1973 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1974 return;
1975 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001976 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001977 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001978}
1979
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001980QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1981 // This method tries to turn a variable array into a constant
1982 // array even when the size isn't an ICE. This is necessary
1983 // for compatibility with code that depends on gcc's buggy
1984 // constant expression folding, like struct {char x[(int)(char*)2];}
1985 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00001986 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001987 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00001988 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1989 llvm::APSInt &Res = Result.getInt();
1990 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1991 return Context.getConstantArrayType(VLATy->getElementType(),
1992 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001993 }
1994 }
1995 return QualType();
1996}
1997
Steve Naroff0acc9c92007-09-15 18:49:24 +00001998/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001999/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002000Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002001 SourceLocation DeclStart,
2002 Declarator &D, ExprTy *BitfieldWidth) {
2003 IdentifierInfo *II = D.getIdentifier();
2004 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002005 SourceLocation Loc = DeclStart;
2006 if (II) Loc = D.getIdentifierLoc();
2007
2008 // FIXME: Unnamed fields can be handled in various different ways, for
2009 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002010
Chris Lattner4b009652007-07-25 00:24:17 +00002011 if (BitWidth) {
2012 // TODO: Validate.
2013 //printf("WARNING: BITFIELDS IGNORED!\n");
2014
2015 // 6.7.2.1p3
2016 // 6.7.2.1p4
2017
2018 } else {
2019 // Not a bitfield.
2020
2021 // validate II.
2022
2023 }
2024
2025 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002026 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2027 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002028
Chris Lattner4b009652007-07-25 00:24:17 +00002029 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2030 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002031 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002032 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2033 if (!FixedTy.isNull()) {
2034 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2035 T = FixedTy;
2036 } else {
2037 // FIXME: This diagnostic needs work
2038 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2039 InvalidDecl = true;
2040 }
Chris Lattner4b009652007-07-25 00:24:17 +00002041 }
Chris Lattner4b009652007-07-25 00:24:17 +00002042 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002043 FieldDecl *NewFD;
2044
2045 if (getLangOptions().CPlusPlus) {
2046 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2047 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2048 Loc, II, T, BitWidth);
2049 if (II)
2050 PushOnScopeChains(NewFD, S);
2051 }
2052 else
2053 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002054
Chris Lattner9b384ca2008-06-29 00:02:00 +00002055 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002056
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002057 if (D.getInvalidType() || InvalidDecl)
2058 NewFD->setInvalidDecl();
2059 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002060}
2061
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002062/// TranslateIvarVisibility - Translate visibility from a token ID to an
2063/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002064static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002065TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002066 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002067 case tok::objc_private: return ObjCIvarDecl::Private;
2068 case tok::objc_public: return ObjCIvarDecl::Public;
2069 case tok::objc_protected: return ObjCIvarDecl::Protected;
2070 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002071 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00002072 }
2073}
2074
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002075/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2076/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002077Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002078 SourceLocation DeclStart,
2079 Declarator &D, ExprTy *BitfieldWidth,
2080 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002081 IdentifierInfo *II = D.getIdentifier();
2082 Expr *BitWidth = (Expr*)BitfieldWidth;
2083 SourceLocation Loc = DeclStart;
2084 if (II) Loc = D.getIdentifierLoc();
2085
2086 // FIXME: Unnamed fields can be handled in various different ways, for
2087 // example, unnamed unions inject all members into the struct namespace!
2088
2089
2090 if (BitWidth) {
2091 // TODO: Validate.
2092 //printf("WARNING: BITFIELDS IGNORED!\n");
2093
2094 // 6.7.2.1p3
2095 // 6.7.2.1p4
2096
2097 } else {
2098 // Not a bitfield.
2099
2100 // validate II.
2101
2102 }
2103
2104 QualType T = GetTypeForDeclarator(D, S);
2105 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2106 bool InvalidDecl = false;
2107
2108 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2109 // than a variably modified type.
2110 if (T->isVariablyModifiedType()) {
2111 // FIXME: This diagnostic needs work
2112 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2113 InvalidDecl = true;
2114 }
2115
Ted Kremenek173dd312008-07-23 18:04:17 +00002116 // Get the visibility (access control) for this ivar.
2117 ObjCIvarDecl::AccessControl ac =
2118 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2119 : ObjCIvarDecl::None;
2120
2121 // Construct the decl.
2122 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002123 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002124
Ted Kremenek173dd312008-07-23 18:04:17 +00002125 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002126 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002127
2128 if (D.getInvalidType() || InvalidDecl)
2129 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002130
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002131 return NewID;
2132}
2133
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002134void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002135 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002136 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002137 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002138 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002139 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2140 assert(EnclosingDecl && "missing record or interface decl");
2141 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2142
Ted Kremenek46a837c2008-09-05 17:16:31 +00002143 if (Record)
2144 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2145 // Diagnose code like:
2146 // struct S { struct S {} X; };
2147 // We discover this when we complete the outer S. Reject and ignore the
2148 // outer S.
2149 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2150 DefRecord->getKindName());
2151 Diag(RecLoc, diag::err_previous_definition);
2152 Record->setInvalidDecl();
2153 return;
2154 }
2155
Chris Lattner4b009652007-07-25 00:24:17 +00002156 // Verify that all the fields are okay.
2157 unsigned NumNamedMembers = 0;
2158 llvm::SmallVector<FieldDecl*, 32> RecFields;
2159 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002160
Chris Lattner4b009652007-07-25 00:24:17 +00002161 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002162
Steve Naroff9bb759f2007-09-14 22:20:54 +00002163 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2164 assert(FD && "missing field decl");
2165
2166 // Remember all fields.
2167 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002168
2169 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002170 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002171
Chris Lattner4b009652007-07-25 00:24:17 +00002172 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002173 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002174 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002175 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002176 FD->setInvalidDecl();
2177 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002178 continue;
2179 }
Chris Lattner4b009652007-07-25 00:24:17 +00002180 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2181 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002182 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002183 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002184 FD->setInvalidDecl();
2185 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002186 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002187 }
Chris Lattner4b009652007-07-25 00:24:17 +00002188 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002189 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002190 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002191 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002192 FD->setInvalidDecl();
2193 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002194 continue;
2195 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002196 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002197 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2198 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002199 FD->setInvalidDecl();
2200 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002201 continue;
2202 }
Chris Lattner4b009652007-07-25 00:24:17 +00002203 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002204 if (Record)
2205 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002206 }
Chris Lattner4b009652007-07-25 00:24:17 +00002207 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2208 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002209 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002210 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2211 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002212 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002213 Record->setHasFlexibleArrayMember(true);
2214 } else {
2215 // If this is a struct/class and this is not the last element, reject
2216 // it. Note that GCC supports variable sized arrays in the middle of
2217 // structures.
2218 if (i != NumFields-1) {
2219 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2220 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002221 FD->setInvalidDecl();
2222 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002223 continue;
2224 }
Chris Lattner4b009652007-07-25 00:24:17 +00002225 // We support flexible arrays at the end of structs in other structs
2226 // as an extension.
2227 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2228 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002229 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002230 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002231 }
2232 }
2233 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002234 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002235 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002236 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2237 FD->getName());
2238 FD->setInvalidDecl();
2239 EnclosingDecl->setInvalidDecl();
2240 continue;
2241 }
Chris Lattner4b009652007-07-25 00:24:17 +00002242 // Keep track of the number of named members.
2243 if (IdentifierInfo *II = FD->getIdentifier()) {
2244 // Detect duplicate member names.
2245 if (!FieldIDs.insert(II)) {
2246 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2247 // Find the previous decl.
2248 SourceLocation PrevLoc;
2249 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2250 assert(i != e && "Didn't find previous def!");
2251 if (RecFields[i]->getIdentifier() == II) {
2252 PrevLoc = RecFields[i]->getLocation();
2253 break;
2254 }
2255 }
2256 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002257 FD->setInvalidDecl();
2258 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002259 continue;
2260 }
2261 ++NumNamedMembers;
2262 }
Chris Lattner4b009652007-07-25 00:24:17 +00002263 }
2264
Chris Lattner4b009652007-07-25 00:24:17 +00002265 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002266 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002267 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002268 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2269 // Sema::ActOnFinishCXXClassDef.
2270 if (!isa<CXXRecordDecl>(Record))
2271 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002272 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002273 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2274 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2275 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2276 else if (ObjCImplementationDecl *IMPDecl =
2277 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002278 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2279 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002280 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002281 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002282 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002283
2284 if (Attr)
2285 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002286}
2287
Steve Naroff0acc9c92007-09-15 18:49:24 +00002288Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002289 DeclTy *lastEnumConst,
2290 SourceLocation IdLoc, IdentifierInfo *Id,
2291 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002292 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002293 EnumConstantDecl *LastEnumConst =
2294 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2295 Expr *Val = static_cast<Expr*>(val);
2296
Chris Lattnera7549902007-08-26 06:24:45 +00002297 // The scope passed in may not be a decl scope. Zip up the scope tree until
2298 // we find one that is.
2299 while ((S->getFlags() & Scope::DeclScope) == 0)
2300 S = S->getParent();
2301
Chris Lattner4b009652007-07-25 00:24:17 +00002302 // Verify that there isn't already something declared with this name in this
2303 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002304 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002305 // When in C++, we may get a TagDecl with the same name; in this case the
2306 // enum constant will 'hide' the tag.
2307 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2308 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002309 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002310 if (isa<EnumConstantDecl>(PrevDecl))
2311 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2312 else
2313 Diag(IdLoc, diag::err_redefinition, Id->getName());
2314 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002315 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002316 return 0;
2317 }
2318 }
2319
2320 llvm::APSInt EnumVal(32);
2321 QualType EltTy;
2322 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002323 // Make sure to promote the operand type to int.
2324 UsualUnaryConversions(Val);
2325
Chris Lattner4b009652007-07-25 00:24:17 +00002326 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2327 SourceLocation ExpLoc;
2328 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2329 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2330 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002331 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002332 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002333 } else {
2334 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002335 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002336 }
2337
2338 if (!Val) {
2339 if (LastEnumConst) {
2340 // Assign the last value + 1.
2341 EnumVal = LastEnumConst->getInitVal();
2342 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002343
2344 // Check for overflow on increment.
2345 if (EnumVal < LastEnumConst->getInitVal())
2346 Diag(IdLoc, diag::warn_enum_value_overflow);
2347
Chris Lattnere7f53a42007-08-27 17:37:24 +00002348 EltTy = LastEnumConst->getType();
2349 } else {
2350 // First value, set to zero.
2351 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002352 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002353 }
Chris Lattner4b009652007-07-25 00:24:17 +00002354 }
2355
Chris Lattnere4650482008-03-15 06:12:44 +00002356 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002357 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2358 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002359 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002360
2361 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002362 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002363 return New;
2364}
2365
Steve Naroffb0726b82008-08-07 14:08:16 +00002366// FIXME: For consistency with ActOnFields(), we should have the parser
2367// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002368void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002369 DeclTy **Elements, unsigned NumElements) {
2370 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002371
Steve Naroffb0726b82008-08-07 14:08:16 +00002372 if (Enum && Enum->isDefinition()) {
2373 // Diagnose code like:
2374 // enum e0 {
2375 // E0 = sizeof(enum e0 { E1 })
2376 // };
2377 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2378 Enum->getName());
2379 Diag(EnumLoc, diag::err_previous_definition);
2380 Enum->setInvalidDecl();
2381 return;
2382 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002383 // TODO: If the result value doesn't fit in an int, it must be a long or long
2384 // long value. ISO C does not support this, but GCC does as an extension,
2385 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002386 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002387
Chris Lattner206754a2007-08-28 06:15:15 +00002388 // Verify that all the values are okay, compute the size of the values, and
2389 // reverse the list.
2390 unsigned NumNegativeBits = 0;
2391 unsigned NumPositiveBits = 0;
2392
2393 // Keep track of whether all elements have type int.
2394 bool AllElementsInt = true;
2395
Chris Lattner4b009652007-07-25 00:24:17 +00002396 EnumConstantDecl *EltList = 0;
2397 for (unsigned i = 0; i != NumElements; ++i) {
2398 EnumConstantDecl *ECD =
2399 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2400 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002401
2402 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002403 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002404 assert(InitVal.getBitWidth() >= IntWidth &&
2405 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002406 if (InitVal.getBitWidth() > IntWidth) {
2407 llvm::APSInt V(InitVal);
2408 V.trunc(IntWidth);
2409 V.extend(InitVal.getBitWidth());
2410 if (V != InitVal)
2411 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002412 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002413 }
Chris Lattner206754a2007-08-28 06:15:15 +00002414
2415 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002416 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002417 NumPositiveBits = std::max(NumPositiveBits,
2418 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002419 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002420 NumNegativeBits = std::max(NumNegativeBits,
2421 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002422
Chris Lattner206754a2007-08-28 06:15:15 +00002423 // Keep track of whether every enum element has type int (very commmon).
2424 if (AllElementsInt)
2425 AllElementsInt = ECD->getType() == Context.IntTy;
2426
Chris Lattner4b009652007-07-25 00:24:17 +00002427 ECD->setNextDeclarator(EltList);
2428 EltList = ECD;
2429 }
2430
Chris Lattner206754a2007-08-28 06:15:15 +00002431 // Figure out the type that should be used for this enum.
2432 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2433 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002434 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002435
2436 if (NumNegativeBits) {
2437 // If there is a negative value, figure out the smallest integer type (of
2438 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002439 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002440 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002441 BestWidth = IntWidth;
2442 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002443 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002444
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002445 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002446 BestType = Context.LongTy;
2447 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002448 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002449
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002450 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002451 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2452 BestType = Context.LongLongTy;
2453 }
2454 }
2455 } else {
2456 // If there is no negative value, figure out which of uint, ulong, ulonglong
2457 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002458 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002459 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002460 BestWidth = IntWidth;
2461 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002462 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002463 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002464 } else {
2465 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002466 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002467 "How could an initializer get larger than ULL?");
2468 BestType = Context.UnsignedLongLongTy;
2469 }
2470 }
2471
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002472 // Loop over all of the enumerator constants, changing their types to match
2473 // the type of the enum if needed.
2474 for (unsigned i = 0; i != NumElements; ++i) {
2475 EnumConstantDecl *ECD =
2476 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2477 if (!ECD) continue; // Already issued a diagnostic.
2478
2479 // Standard C says the enumerators have int type, but we allow, as an
2480 // extension, the enumerators to be larger than int size. If each
2481 // enumerator value fits in an int, type it as an int, otherwise type it the
2482 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2483 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002484 if (ECD->getType() == Context.IntTy) {
2485 // Make sure the init value is signed.
2486 llvm::APSInt IV = ECD->getInitVal();
2487 IV.setIsSigned(true);
2488 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002489 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002490 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002491
2492 // Determine whether the value fits into an int.
2493 llvm::APSInt InitVal = ECD->getInitVal();
2494 bool FitsInInt;
2495 if (InitVal.isUnsigned() || !InitVal.isNegative())
2496 FitsInInt = InitVal.getActiveBits() < IntWidth;
2497 else
2498 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2499
2500 // If it fits into an integer type, force it. Otherwise force it to match
2501 // the enum decl type.
2502 QualType NewTy;
2503 unsigned NewWidth;
2504 bool NewSign;
2505 if (FitsInInt) {
2506 NewTy = Context.IntTy;
2507 NewWidth = IntWidth;
2508 NewSign = true;
2509 } else if (ECD->getType() == BestType) {
2510 // Already the right type!
2511 continue;
2512 } else {
2513 NewTy = BestType;
2514 NewWidth = BestWidth;
2515 NewSign = BestType->isSignedIntegerType();
2516 }
2517
2518 // Adjust the APSInt value.
2519 InitVal.extOrTrunc(NewWidth);
2520 InitVal.setIsSigned(NewSign);
2521 ECD->setInitVal(InitVal);
2522
2523 // Adjust the Expr initializer and type.
2524 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2525 ECD->setType(NewTy);
2526 }
Chris Lattner206754a2007-08-28 06:15:15 +00002527
Chris Lattner90a018d2007-08-28 18:24:31 +00002528 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002529 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002530}
2531
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002532Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2533 ExprTy *expr) {
2534 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2535
Chris Lattner81db64a2008-03-16 00:16:02 +00002536 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002537}
2538
Chris Lattner806a5f52008-01-12 07:05:38 +00002539Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002540 SourceLocation LBrace,
2541 SourceLocation RBrace,
2542 const char *Lang,
2543 unsigned StrSize,
2544 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002545 LinkageSpecDecl::LanguageIDs Language;
2546 Decl *dcl = static_cast<Decl *>(D);
2547 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2548 Language = LinkageSpecDecl::lang_c;
2549 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2550 Language = LinkageSpecDecl::lang_cxx;
2551 else {
2552 Diag(Loc, diag::err_bad_language);
2553 return 0;
2554 }
2555
2556 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002557 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002558}