blob: cf84bcc5e1e87f12c38dc7787a4c226b1b47aafe [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*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argiris Kirtzidis94805232008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096 return;
97 }
98 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000100}
101
Steve Naroff9637a9b2007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000105
Chris Lattner4b009652007-07-25 00:24:17 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000115
Chris Lattner4b009652007-07-25 00:24:17 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Ted Kremenek40e70e72008-09-03 18:03:35 +0000119 // We only want to remove the decls from the identifier decl chains for
120 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000123
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000127 }
128}
129
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000136
Steve Naroff6384a012008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000138}
139
Steve Naroffe57c21a2008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000141/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000144 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000148
Chris Lattner4b009652007-07-25 00:24:17 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000156
Chris Lattner4b009652007-07-25 00:24:17 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179 return 0;
180}
181
Chris Lattnera9c87f22008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Chris Lattner4b009652007-07-25 00:24:17 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson36760332007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattnera9c87f22008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerdf40dbf2008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson36760332007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000209
Chris Lattnera9c87f22008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000225 return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000233 // Verify the old decl was also a typedef.
234 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
235 if (!Old) {
236 Diag(New->getLocation(), diag::err_redefinition_different_kind,
237 New->getName());
238 Diag(OldD->getLocation(), diag::err_previous_definition);
239 return New;
240 }
241
Chris Lattnerbef8d622008-07-25 18:44:27 +0000242 // If the typedef types are not identical, reject them in all languages and
243 // with any extensions enabled.
244 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
245 Context.getCanonicalType(Old->getUnderlyingType()) !=
246 Context.getCanonicalType(New->getUnderlyingType())) {
247 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
248 New->getUnderlyingType().getAsString(),
249 Old->getUnderlyingType().getAsString());
250 Diag(Old->getLocation(), diag::err_previous_definition);
251 return Old;
252 }
253
Steve Naroffae84af82007-10-31 18:42:27 +0000254 // Allow multiple definitions for ObjC built-in typedefs.
255 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000256 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000257 return Old;
Eli Friedman324d5032008-06-11 06:20:39 +0000258
259 if (getLangOptions().Microsoft) return New;
260
Steve Naroffa9eae582008-01-30 23:46:05 +0000261 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
262 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
263 // *either* declaration is in a system header. The code below implements
264 // this adhoc compatibility rule. FIXME: The following code will not
265 // work properly when compiling ".i" files (containing preprocessed output).
266 SourceManager &SrcMgr = Context.getSourceManager();
Nico Weber7d3196c2008-08-29 17:02:23 +0000267 if (SrcMgr.isInSystemHeader(Old->getLocation()))
268 return New;
269 if (SrcMgr.isInSystemHeader(New->getLocation()))
270 return New;
Eli Friedman324d5032008-06-11 06:20:39 +0000271
Ted Kremenek64845ce2008-05-23 21:28:18 +0000272 Diag(New->getLocation(), diag::err_redefinition, New->getName());
273 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000274 return New;
275}
276
Chris Lattner6953a072008-06-26 18:38:35 +0000277/// DeclhasAttr - returns true if decl Declaration already has the target
278/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000279static bool DeclHasAttr(const Decl *decl, const Attr *target) {
280 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
281 if (attr->getKind() == target->getKind())
282 return true;
283
284 return false;
285}
286
287/// MergeAttributes - append attributes from the Old decl to the New one.
288static void MergeAttributes(Decl *New, Decl *Old) {
289 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
290
Chris Lattner402b3372008-03-03 03:28:21 +0000291 while (attr) {
292 tmp = attr;
293 attr = attr->getNext();
294
295 if (!DeclHasAttr(New, tmp)) {
296 New->addAttr(tmp);
297 } else {
298 tmp->setNext(0);
299 delete(tmp);
300 }
301 }
Nuno Lopes77654342008-06-01 22:53:53 +0000302
303 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000304}
305
Chris Lattner3e254fb2008-04-08 04:40:51 +0000306/// MergeFunctionDecl - We just parsed a function 'New' from
307/// declarator D which has the same name and scope as a previous
308/// declaration 'Old'. Figure out how to resolve this situation,
309/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor42214c52008-04-21 02:02:58 +0000310/// Redeclaration will be set true if thisNew is a redeclaration OldD.
311FunctionDecl *
312Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
313 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000314 // Verify the old decl was also a function.
315 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000322
Chris Lattner42a21742008-04-06 23:10:54 +0000323 QualType OldQType = Context.getCanonicalType(Old->getType());
324 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000325
Chris Lattner3e254fb2008-04-08 04:40:51 +0000326 // C++ [dcl.fct]p3:
327 // All declarations for a function shall agree exactly in both the
328 // return type and the parameter-type-list.
Douglas Gregor42214c52008-04-21 02:02:58 +0000329 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
330 MergeAttributes(New, Old);
331 Redeclaration = true;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000332 return MergeCXXFunctionDecl(New, Old);
Douglas Gregor42214c52008-04-21 02:02:58 +0000333 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000334
335 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000336 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000337 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000338 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000339 MergeAttributes(New, Old);
340 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000341 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000342 }
Chris Lattner1470b072007-11-06 06:07:26 +0000343
Steve Naroff6c9e7922008-01-16 15:01:34 +0000344 // A function that has already been declared has been redeclared or defined
345 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000346 diag::kind PrevDiag;
Douglas Gregor42214c52008-04-21 02:02:58 +0000347 if (Old->isThisDeclarationADefinition())
Steve Naroff9104f3c2008-04-04 14:32:09 +0000348 PrevDiag = diag::err_previous_definition;
349 else if (Old->isImplicit())
350 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000351 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000352 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000353
Chris Lattner4b009652007-07-25 00:24:17 +0000354 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
355 // TODO: This is totally simplistic. It should handle merging functions
356 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000357 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
358 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000359 return New;
360}
361
Steve Naroffb5e78152008-08-08 17:50:35 +0000362/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000363static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000364 if (VD->isFileVarDecl())
365 return (!VD->getInit() &&
366 (VD->getStorageClass() == VarDecl::None ||
367 VD->getStorageClass() == VarDecl::Static));
368 return false;
369}
370
371/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
372/// when dealing with C "tentative" external object definitions (C99 6.9.2).
373void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
374 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000375 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000376
377 for (IdentifierResolver::iterator
378 I = IdResolver.begin(VD->getIdentifier(),
379 VD->getDeclContext(), false/*LookInParentCtx*/),
380 E = IdResolver.end(); I != E; ++I) {
381 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
382 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
383
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000384 // Handle the following case:
385 // int a[10];
386 // int a[]; - the code below makes sure we set the correct type.
387 // int a[11]; - this is an error, size isn't 10.
388 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
389 OldDecl->getType()->isConstantArrayType())
390 VD->setType(OldDecl->getType());
391
Steve Naroffb5e78152008-08-08 17:50:35 +0000392 // Check for "tentative" definitions. We can't accomplish this in
393 // MergeVarDecl since the initializer hasn't been attached.
394 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
395 continue;
396
397 // Handle __private_extern__ just like extern.
398 if (OldDecl->getStorageClass() != VarDecl::Extern &&
399 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
400 VD->getStorageClass() != VarDecl::Extern &&
401 VD->getStorageClass() != VarDecl::PrivateExtern) {
402 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
403 Diag(OldDecl->getLocation(), diag::err_previous_definition);
404 }
405 }
406 }
407}
408
Chris Lattner4b009652007-07-25 00:24:17 +0000409/// MergeVarDecl - We just parsed a variable 'New' which has the same name
410/// and scope as a previous declaration 'Old'. Figure out how to resolve this
411/// situation, merging decls or emitting diagnostics as appropriate.
412///
Steve Naroffb5e78152008-08-08 17:50:35 +0000413/// Tentative definition rules (C99 6.9.2p2) are checked by
414/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
415/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000416///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000417VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000418 // Verify the old decl was also a variable.
419 VarDecl *Old = dyn_cast<VarDecl>(OldD);
420 if (!Old) {
421 Diag(New->getLocation(), diag::err_redefinition_different_kind,
422 New->getName());
423 Diag(OldD->getLocation(), diag::err_previous_definition);
424 return New;
425 }
Chris Lattner402b3372008-03-03 03:28:21 +0000426
427 MergeAttributes(New, Old);
428
Chris Lattner4b009652007-07-25 00:24:17 +0000429 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000430 QualType OldCType = Context.getCanonicalType(Old->getType());
431 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000432 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000433 Diag(New->getLocation(), diag::err_redefinition, New->getName());
434 Diag(Old->getLocation(), diag::err_previous_definition);
435 return New;
436 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000437 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
438 if (New->getStorageClass() == VarDecl::Static &&
439 (Old->getStorageClass() == VarDecl::None ||
440 Old->getStorageClass() == VarDecl::Extern)) {
441 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
442 Diag(Old->getLocation(), diag::err_previous_definition);
443 return New;
444 }
445 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
446 if (New->getStorageClass() != VarDecl::Static &&
447 Old->getStorageClass() == VarDecl::Static) {
448 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
449 Diag(Old->getLocation(), diag::err_previous_definition);
450 return New;
451 }
Steve Naroffb5e78152008-08-08 17:50:35 +0000452 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
453 if (!New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000454 Diag(New->getLocation(), diag::err_redefinition, New->getName());
455 Diag(Old->getLocation(), diag::err_previous_definition);
456 }
457 return New;
458}
459
Chris Lattner3e254fb2008-04-08 04:40:51 +0000460/// CheckParmsForFunctionDef - Check that the parameters of the given
461/// function are appropriate for the definition of a function. This
462/// takes care of any checks that cannot be performed on the
463/// declaration itself, e.g., that the types of each of the function
464/// parameters are complete.
465bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
466 bool HasInvalidParm = false;
467 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
468 ParmVarDecl *Param = FD->getParamDecl(p);
469
470 // C99 6.7.5.3p4: the parameters in a parameter type list in a
471 // function declarator that is part of a function definition of
472 // that function shall not have incomplete type.
473 if (Param->getType()->isIncompleteType() &&
474 !Param->isInvalidDecl()) {
475 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
476 Param->getType().getAsString());
477 Param->setInvalidDecl();
478 HasInvalidParm = true;
479 }
480 }
481
482 return HasInvalidParm;
483}
484
Chris Lattner4b009652007-07-25 00:24:17 +0000485/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
486/// no declarator (e.g. "struct foo;") is parsed.
487Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
488 // TODO: emit error on 'int;' or 'const enum foo;'.
489 // TODO: emit error on 'typedef int;'
490 // if (!DS.isMissingDeclaratorOk()) Diag(...);
491
Steve Naroffedafc0b2007-11-17 21:37:36 +0000492 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000493}
494
Steve Narofff0b23542008-01-10 22:15:12 +0000495bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000496 // Get the type before calling CheckSingleAssignmentConstraints(), since
497 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000498 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000499
Chris Lattner005ed752008-01-04 18:04:52 +0000500 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
501 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
502 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000503}
504
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000505bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000506 const ArrayType *AT = Context.getAsArrayType(DeclT);
507
508 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000509 // C99 6.7.8p14. We have an array of character type with unknown size
510 // being initialized to a string literal.
511 llvm::APSInt ConstVal(32);
512 ConstVal = strLiteral->getByteLength() + 1;
513 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000514 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000515 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000516 } else {
517 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000518 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000519 // FIXME: Avoid truncation for 64-bit length strings.
520 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000521 Diag(strLiteral->getSourceRange().getBegin(),
522 diag::warn_initializer_string_for_char_array_too_long,
523 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000524 }
525 // Set type from "char *" to "constant array of char".
526 strLiteral->setType(DeclT);
527 // For now, we always return false (meaning success).
528 return false;
529}
530
531StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000532 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000533 if (AT && AT->getElementType()->isCharType()) {
534 return dyn_cast<StringLiteral>(Init);
535 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000536 return 0;
537}
538
Steve Narofff3cb5142008-01-25 00:51:06 +0000539bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000540 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
541 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000542 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroff8e9337f2008-01-21 23:53:58 +0000543 return Diag(VAT->getSizeExpr()->getLocStart(),
544 diag::err_variable_object_no_init,
545 VAT->getSizeExpr()->getSourceRange());
546
Steve Naroffcb69fb72007-12-10 22:44:33 +0000547 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
548 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000549 // FIXME: Handle wide strings
550 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
551 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000552
553 if (DeclType->isArrayType())
554 return Diag(Init->getLocStart(),
555 diag::err_array_init_list_required,
556 Init->getSourceRange());
557
Steve Narofff0b23542008-01-10 22:15:12 +0000558 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000559 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000560
Steve Naroffc4d4a482008-05-01 22:18:59 +0000561 InitListChecker CheckInitList(this, InitList, DeclType);
562 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000563}
564
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000565Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000566Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000567 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000568 IdentifierInfo *II = D.getIdentifier();
569
570 // All of these full declarators require an identifier. If it doesn't have
571 // one, the ParsedFreeStandingDeclSpec action should be used.
572 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000573 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000574 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000575 D.getDeclSpec().getSourceRange(), D.getSourceRange());
576 return 0;
577 }
578
Chris Lattnera7549902007-08-26 06:24:45 +0000579 // The scope passed in may not be a decl scope. Zip up the scope tree until
580 // we find one that is.
581 while ((S->getFlags() & Scope::DeclScope) == 0)
582 S = S->getParent();
583
Chris Lattner4b009652007-07-25 00:24:17 +0000584 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000585 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000586 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000587 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000588
589 // In C++, the previous declaration we find might be a tag type
590 // (class or enum). In this case, the new declaration will hide the
591 // tag type.
592 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
593 PrevDecl = 0;
594
Chris Lattner82bb4792007-11-14 06:34:38 +0000595 QualType R = GetTypeForDeclarator(D, S);
596 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
597
Chris Lattner4b009652007-07-25 00:24:17 +0000598 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000599 // Check that there are no default arguments (C++ only).
600 if (getLangOptions().CPlusPlus)
601 CheckExtraCXXDefaultArguments(D);
602
Chris Lattner82bb4792007-11-14 06:34:38 +0000603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000604 if (!NewTD) return 0;
605
606 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000607 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000608 // Merge the decl with the existing one if appropriate. If the decl is
609 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000610 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000611 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
612 if (NewTD == 0) return 0;
613 }
614 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000615 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000616 // C99 6.7.7p2: If a typedef name specifies a variably modified type
617 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000618 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
619 // FIXME: Diagnostic needs to be fixed.
620 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000621 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000622 }
623 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000624 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000625 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000626 switch (D.getDeclSpec().getStorageClassSpec()) {
627 default: assert(0 && "Unknown storage class!");
628 case DeclSpec::SCS_auto:
629 case DeclSpec::SCS_register:
630 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
631 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000632 InvalidDecl = true;
633 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000634 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
635 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
636 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000637 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000638 }
639
Chris Lattner4c7802b2008-03-15 21:24:04 +0000640 bool isInline = D.getDeclSpec().isInlineSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000641 FunctionDecl *NewFD;
642 if (D.getContext() == Declarator::MemberContext) {
643 // This is a C++ method declaration.
644 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
645 D.getIdentifierLoc(), II, R,
646 (SC == FunctionDecl::Static), isInline,
647 LastDeclarator);
648 } else {
649 NewFD = FunctionDecl::Create(Context, CurContext,
650 D.getIdentifierLoc(),
651 II, R, SC, isInline,
652 LastDeclarator);
653 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000654 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000655 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000656
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000657 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000658 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000659 // The parser guarantees this is a string.
660 StringLiteral *SE = cast<StringLiteral>(E);
661 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
662 SE->getByteLength())));
663 }
664
Chris Lattner3e254fb2008-04-08 04:40:51 +0000665 // Copy the parameter declarations from the declarator D to
666 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000667 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000668 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
669
670 // Create Decl objects for each parameter, adding them to the
671 // FunctionDecl.
672 llvm::SmallVector<ParmVarDecl*, 16> Params;
673
674 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
675 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000676 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000677 // We let through "const void" here because Sema::GetTypeForDeclarator
678 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000679 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
680 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000681 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
682 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000683 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
684
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000685 // In C++, the empty parameter-type-list must be spelled "void"; a
686 // typedef of void is not permitted.
687 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000688 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000689 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
690 }
691
Eli Friedman769e7302008-08-25 21:31:01 +0000692 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000693 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
694 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
695 }
696
697 NewFD->setParams(&Params[0], Params.size());
698 }
699
Steve Narofff8a09432008-01-09 23:34:55 +0000700 // Merge the decl with the existing one if appropriate. Since C functions
701 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000702 if (PrevDecl &&
703 (!getLangOptions().CPlusPlus ||
704 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000705 bool Redeclaration = false;
706 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Chris Lattner4b009652007-07-25 00:24:17 +0000707 if (NewFD == 0) return 0;
Douglas Gregor42214c52008-04-21 02:02:58 +0000708 if (Redeclaration) {
Eli Friedmand2701812008-05-27 05:07:37 +0000709 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregor42214c52008-04-21 02:02:58 +0000710 }
Chris Lattner4b009652007-07-25 00:24:17 +0000711 }
712 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000713
714 // In C++, check default arguments now that we have merged decls.
715 if (getLangOptions().CPlusPlus)
716 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000717 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000718 // Check that there are no default arguments (C++ only).
719 if (getLangOptions().CPlusPlus)
720 CheckExtraCXXDefaultArguments(D);
721
Ted Kremenek42730c52008-01-07 19:49:32 +0000722 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000723 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
724 D.getIdentifier()->getName());
725 InvalidDecl = true;
726 }
Chris Lattner4b009652007-07-25 00:24:17 +0000727
728 VarDecl *NewVD;
729 VarDecl::StorageClass SC;
730 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000731 default: assert(0 && "Unknown storage class!");
732 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
733 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
734 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
735 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
736 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
737 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000738 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000739 if (D.getContext() == Declarator::MemberContext) {
740 assert(SC == VarDecl::Static && "Invalid storage class for member!");
741 // This is a static data member for a C++ class.
742 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
743 D.getIdentifierLoc(), II,
744 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000745 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000746 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000747 if (S->getFnParent() == 0) {
748 // C99 6.9p2: The storage-class specifiers auto and register shall not
749 // appear in the declaration specifiers in an external declaration.
750 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
751 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
752 R.getAsString());
753 InvalidDecl = true;
754 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000755 }
Daniel Dunbar5eea5622008-09-08 20:05:47 +0000756 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
757 II, R, SC, LastDeclarator);
758 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +0000759 }
Chris Lattner4b009652007-07-25 00:24:17 +0000760 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000761 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +0000762
Daniel Dunbarced89142008-08-06 00:03:29 +0000763 // Handle GNU asm-label extension (encoded as an attribute).
764 if (Expr *E = (Expr*) D.getAsmLabel()) {
765 // The parser guarantees this is a string.
766 StringLiteral *SE = cast<StringLiteral>(E);
767 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
768 SE->getByteLength())));
769 }
770
Nate Begemanea583262008-03-14 18:07:10 +0000771 // Emit an error if an address space was applied to decl with local storage.
772 // This includes arrays of objects with address space qualifiers, but not
773 // automatic variables that point to other address spaces.
774 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000775 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
776 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
777 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000778 }
Steve Narofff8a09432008-01-09 23:34:55 +0000779 // Merge the decl with the existing one if appropriate. If the decl is
780 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000781 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000782 NewVD = MergeVarDecl(NewVD, PrevDecl);
783 if (NewVD == 0) return 0;
784 }
Chris Lattner4b009652007-07-25 00:24:17 +0000785 New = NewVD;
786 }
787
788 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000789 if (II)
790 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000791 // If any semantic error occurred, mark the decl as invalid.
792 if (D.getInvalidType() || InvalidDecl)
793 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000794
795 return New;
796}
797
Eli Friedman02c22ce2008-05-20 13:48:25 +0000798bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
799 switch (Init->getStmtClass()) {
800 default:
801 Diag(Init->getExprLoc(),
802 diag::err_init_element_not_constant, Init->getSourceRange());
803 return true;
804 case Expr::ParenExprClass: {
805 const ParenExpr* PE = cast<ParenExpr>(Init);
806 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
807 }
808 case Expr::CompoundLiteralExprClass:
809 return cast<CompoundLiteralExpr>(Init)->isFileScope();
810 case Expr::DeclRefExprClass: {
811 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +0000812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
813 if (VD->hasGlobalStorage())
814 return false;
815 Diag(Init->getExprLoc(),
816 diag::err_init_element_not_constant, Init->getSourceRange());
817 return true;
818 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000819 if (isa<FunctionDecl>(D))
820 return false;
821 Diag(Init->getExprLoc(),
822 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Narofff0b23542008-01-10 22:15:12 +0000823 return true;
824 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000825 case Expr::MemberExprClass: {
826 const MemberExpr *M = cast<MemberExpr>(Init);
827 if (M->isArrow())
828 return CheckAddressConstantExpression(M->getBase());
829 return CheckAddressConstantExpressionLValue(M->getBase());
830 }
831 case Expr::ArraySubscriptExprClass: {
832 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
833 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
834 return CheckAddressConstantExpression(ASE->getBase()) ||
835 CheckArithmeticConstantExpression(ASE->getIdx());
836 }
837 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +0000838 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +0000839 return false;
840 case Expr::UnaryOperatorClass: {
841 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
842
843 // C99 6.6p9
844 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +0000845 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +0000846
847 Diag(Init->getExprLoc(),
848 diag::err_init_element_not_constant, Init->getSourceRange());
849 return true;
850 }
851 }
852}
853
854bool Sema::CheckAddressConstantExpression(const Expr* Init) {
855 switch (Init->getStmtClass()) {
856 default:
857 Diag(Init->getExprLoc(),
858 diag::err_init_element_not_constant, Init->getSourceRange());
859 return true;
860 case Expr::ParenExprClass: {
861 const ParenExpr* PE = cast<ParenExpr>(Init);
862 return CheckAddressConstantExpression(PE->getSubExpr());
863 }
864 case Expr::StringLiteralClass:
865 case Expr::ObjCStringLiteralClass:
866 return false;
867 case Expr::CallExprClass: {
868 const CallExpr *CE = cast<CallExpr>(Init);
869 if (CE->isBuiltinConstantExpr())
870 return false;
871 Diag(Init->getExprLoc(),
872 diag::err_init_element_not_constant, Init->getSourceRange());
873 return true;
874 }
875 case Expr::UnaryOperatorClass: {
876 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
877
878 // C99 6.6p9
879 if (Exp->getOpcode() == UnaryOperator::AddrOf)
880 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
881
882 if (Exp->getOpcode() == UnaryOperator::Extension)
883 return CheckAddressConstantExpression(Exp->getSubExpr());
884
885 Diag(Init->getExprLoc(),
886 diag::err_init_element_not_constant, Init->getSourceRange());
887 return true;
888 }
889 case Expr::BinaryOperatorClass: {
890 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
891 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
892
893 Expr *PExp = Exp->getLHS();
894 Expr *IExp = Exp->getRHS();
895 if (IExp->getType()->isPointerType())
896 std::swap(PExp, IExp);
897
898 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
899 return CheckAddressConstantExpression(PExp) ||
900 CheckArithmeticConstantExpression(IExp);
901 }
Eli Friedman1fad3c62008-08-25 20:46:57 +0000902 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000903 case Expr::ExplicitCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000904 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +0000905 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
906 // Check for implicit promotion
907 if (SubExpr->getType()->isFunctionType() ||
908 SubExpr->getType()->isArrayType())
909 return CheckAddressConstantExpressionLValue(SubExpr);
910 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000911
912 // Check for pointer->pointer cast
913 if (SubExpr->getType()->isPointerType())
914 return CheckAddressConstantExpression(SubExpr);
915
Eli Friedman1fad3c62008-08-25 20:46:57 +0000916 if (SubExpr->getType()->isIntegralType()) {
917 // Check for the special-case of a pointer->int->pointer cast;
918 // this isn't standard, but some code requires it. See
919 // PR2720 for an example.
920 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
921 if (SubCast->getSubExpr()->getType()->isPointerType()) {
922 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
923 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
924 if (IntWidth >= PointerWidth) {
925 return CheckAddressConstantExpression(SubCast->getSubExpr());
926 }
927 }
928 }
929 }
930 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +0000931 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +0000932 }
Eli Friedman02c22ce2008-05-20 13:48:25 +0000933
934 Diag(Init->getExprLoc(),
935 diag::err_init_element_not_constant, Init->getSourceRange());
936 return true;
937 }
938 case Expr::ConditionalOperatorClass: {
939 // FIXME: Should we pedwarn here?
940 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
941 if (!Exp->getCond()->getType()->isArithmeticType()) {
942 Diag(Init->getExprLoc(),
943 diag::err_init_element_not_constant, Init->getSourceRange());
944 return true;
945 }
946 if (CheckArithmeticConstantExpression(Exp->getCond()))
947 return true;
948 if (Exp->getLHS() &&
949 CheckAddressConstantExpression(Exp->getLHS()))
950 return true;
951 return CheckAddressConstantExpression(Exp->getRHS());
952 }
953 case Expr::AddrLabelExprClass:
954 return false;
955 }
956}
957
Eli Friedman998dffb2008-06-09 05:05:07 +0000958static const Expr* FindExpressionBaseAddress(const Expr* E);
959
960static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
961 switch (E->getStmtClass()) {
962 default:
963 return E;
964 case Expr::ParenExprClass: {
965 const ParenExpr* PE = cast<ParenExpr>(E);
966 return FindExpressionBaseAddressLValue(PE->getSubExpr());
967 }
968 case Expr::MemberExprClass: {
969 const MemberExpr *M = cast<MemberExpr>(E);
970 if (M->isArrow())
971 return FindExpressionBaseAddress(M->getBase());
972 return FindExpressionBaseAddressLValue(M->getBase());
973 }
974 case Expr::ArraySubscriptExprClass: {
975 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
976 return FindExpressionBaseAddress(ASE->getBase());
977 }
978 case Expr::UnaryOperatorClass: {
979 const UnaryOperator *Exp = cast<UnaryOperator>(E);
980
981 if (Exp->getOpcode() == UnaryOperator::Deref)
982 return FindExpressionBaseAddress(Exp->getSubExpr());
983
984 return E;
985 }
986 }
987}
988
989static const Expr* FindExpressionBaseAddress(const Expr* E) {
990 switch (E->getStmtClass()) {
991 default:
992 return E;
993 case Expr::ParenExprClass: {
994 const ParenExpr* PE = cast<ParenExpr>(E);
995 return FindExpressionBaseAddress(PE->getSubExpr());
996 }
997 case Expr::UnaryOperatorClass: {
998 const UnaryOperator *Exp = cast<UnaryOperator>(E);
999
1000 // C99 6.6p9
1001 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1002 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1003
1004 if (Exp->getOpcode() == UnaryOperator::Extension)
1005 return FindExpressionBaseAddress(Exp->getSubExpr());
1006
1007 return E;
1008 }
1009 case Expr::BinaryOperatorClass: {
1010 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1011
1012 Expr *PExp = Exp->getLHS();
1013 Expr *IExp = Exp->getRHS();
1014 if (IExp->getType()->isPointerType())
1015 std::swap(PExp, IExp);
1016
1017 return FindExpressionBaseAddress(PExp);
1018 }
1019 case Expr::ImplicitCastExprClass: {
1020 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1021
1022 // Check for implicit promotion
1023 if (SubExpr->getType()->isFunctionType() ||
1024 SubExpr->getType()->isArrayType())
1025 return FindExpressionBaseAddressLValue(SubExpr);
1026
1027 // Check for pointer->pointer cast
1028 if (SubExpr->getType()->isPointerType())
1029 return FindExpressionBaseAddress(SubExpr);
1030
1031 // We assume that we have an arithmetic expression here;
1032 // if we don't, we'll figure it out later
1033 return 0;
1034 }
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001035 case Expr::ExplicitCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001036 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1037
1038 // Check for pointer->pointer cast
1039 if (SubExpr->getType()->isPointerType())
1040 return FindExpressionBaseAddress(SubExpr);
1041
1042 // We assume that we have an arithmetic expression here;
1043 // if we don't, we'll figure it out later
1044 return 0;
1045 }
1046 }
1047}
1048
Eli Friedman02c22ce2008-05-20 13:48:25 +00001049bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1050 switch (Init->getStmtClass()) {
1051 default:
1052 Diag(Init->getExprLoc(),
1053 diag::err_init_element_not_constant, Init->getSourceRange());
1054 return true;
1055 case Expr::ParenExprClass: {
1056 const ParenExpr* PE = cast<ParenExpr>(Init);
1057 return CheckArithmeticConstantExpression(PE->getSubExpr());
1058 }
1059 case Expr::FloatingLiteralClass:
1060 case Expr::IntegerLiteralClass:
1061 case Expr::CharacterLiteralClass:
1062 case Expr::ImaginaryLiteralClass:
1063 case Expr::TypesCompatibleExprClass:
1064 case Expr::CXXBoolLiteralExprClass:
1065 return false;
1066 case Expr::CallExprClass: {
1067 const CallExpr *CE = cast<CallExpr>(Init);
1068 if (CE->isBuiltinConstantExpr())
1069 return false;
1070 Diag(Init->getExprLoc(),
1071 diag::err_init_element_not_constant, Init->getSourceRange());
1072 return true;
1073 }
1074 case Expr::DeclRefExprClass: {
1075 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1076 if (isa<EnumConstantDecl>(D))
1077 return false;
1078 Diag(Init->getExprLoc(),
1079 diag::err_init_element_not_constant, Init->getSourceRange());
1080 return true;
1081 }
1082 case Expr::CompoundLiteralExprClass:
1083 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1084 // but vectors are allowed to be magic.
1085 if (Init->getType()->isVectorType())
1086 return false;
1087 Diag(Init->getExprLoc(),
1088 diag::err_init_element_not_constant, Init->getSourceRange());
1089 return true;
1090 case Expr::UnaryOperatorClass: {
1091 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1092
1093 switch (Exp->getOpcode()) {
1094 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1095 // See C99 6.6p3.
1096 default:
1097 Diag(Init->getExprLoc(),
1098 diag::err_init_element_not_constant, Init->getSourceRange());
1099 return true;
1100 case UnaryOperator::SizeOf:
1101 case UnaryOperator::AlignOf:
1102 case UnaryOperator::OffsetOf:
1103 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1104 // See C99 6.5.3.4p2 and 6.6p3.
1105 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1106 return false;
1107 Diag(Init->getExprLoc(),
1108 diag::err_init_element_not_constant, Init->getSourceRange());
1109 return true;
1110 case UnaryOperator::Extension:
1111 case UnaryOperator::LNot:
1112 case UnaryOperator::Plus:
1113 case UnaryOperator::Minus:
1114 case UnaryOperator::Not:
1115 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1116 }
1117 }
1118 case Expr::SizeOfAlignOfTypeExprClass: {
1119 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1120 // Special check for void types, which are allowed as an extension
1121 if (Exp->getArgumentType()->isVoidType())
1122 return false;
1123 // alignof always evaluates to a constant.
1124 // FIXME: is sizeof(int[3.0]) a constant expression?
1125 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1126 Diag(Init->getExprLoc(),
1127 diag::err_init_element_not_constant, Init->getSourceRange());
1128 return true;
1129 }
1130 return false;
1131 }
1132 case Expr::BinaryOperatorClass: {
1133 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1134
1135 if (Exp->getLHS()->getType()->isArithmeticType() &&
1136 Exp->getRHS()->getType()->isArithmeticType()) {
1137 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1138 CheckArithmeticConstantExpression(Exp->getRHS());
1139 }
1140
Eli Friedman998dffb2008-06-09 05:05:07 +00001141 if (Exp->getLHS()->getType()->isPointerType() &&
1142 Exp->getRHS()->getType()->isPointerType()) {
1143 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1144 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1145
1146 // Only allow a null (constant integer) base; we could
1147 // allow some additional cases if necessary, but this
1148 // is sufficient to cover offsetof-like constructs.
1149 if (!LHSBase && !RHSBase) {
1150 return CheckAddressConstantExpression(Exp->getLHS()) ||
1151 CheckAddressConstantExpression(Exp->getRHS());
1152 }
1153 }
1154
Eli Friedman02c22ce2008-05-20 13:48:25 +00001155 Diag(Init->getExprLoc(),
1156 diag::err_init_element_not_constant, Init->getSourceRange());
1157 return true;
1158 }
1159 case Expr::ImplicitCastExprClass:
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001160 case Expr::ExplicitCastExprClass: {
1161 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001162 if (SubExpr->getType()->isArithmeticType())
1163 return CheckArithmeticConstantExpression(SubExpr);
1164
Eli Friedman266df142008-09-02 09:37:00 +00001165 if (SubExpr->getType()->isPointerType()) {
1166 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1167 // If the pointer has a null base, this is an offsetof-like construct
1168 if (!Base)
1169 return CheckAddressConstantExpression(SubExpr);
1170 }
1171
Eli Friedmand662caa2008-09-01 22:08:17 +00001172 Diag(Init->getExprLoc(),
1173 diag::err_init_element_not_constant, Init->getSourceRange());
1174 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001175 }
1176 case Expr::ConditionalOperatorClass: {
1177 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1178 if (CheckArithmeticConstantExpression(Exp->getCond()))
1179 return true;
1180 if (Exp->getLHS() &&
1181 CheckArithmeticConstantExpression(Exp->getLHS()))
1182 return true;
1183 return CheckArithmeticConstantExpression(Exp->getRHS());
1184 }
1185 }
1186}
1187
1188bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001189 Init = Init->IgnoreParens();
1190
Eli Friedman02c22ce2008-05-20 13:48:25 +00001191 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1192 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1193 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1194
Nuno Lopese7280452008-07-07 16:46:50 +00001195 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1196 return CheckForConstantInitializer(e->getInitializer(), DclT);
1197
Eli Friedman02c22ce2008-05-20 13:48:25 +00001198 if (Init->getType()->isReferenceType()) {
1199 // FIXME: Work out how the heck reference types work
1200 return false;
1201#if 0
1202 // A reference is constant if the address of the expression
1203 // is constant
1204 // We look through initlists here to simplify
1205 // CheckAddressConstantExpressionLValue.
1206 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1207 assert(Exp->getNumInits() > 0 &&
1208 "Refernce initializer cannot be empty");
1209 Init = Exp->getInit(0);
1210 }
1211 return CheckAddressConstantExpressionLValue(Init);
1212#endif
1213 }
1214
1215 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1216 unsigned numInits = Exp->getNumInits();
1217 for (unsigned i = 0; i < numInits; i++) {
1218 // FIXME: Need to get the type of the declaration for C++,
1219 // because it could be a reference?
1220 if (CheckForConstantInitializer(Exp->getInit(i),
1221 Exp->getInit(i)->getType()))
1222 return true;
1223 }
1224 return false;
1225 }
1226
1227 if (Init->isNullPointerConstant(Context))
1228 return false;
1229 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001230 QualType InitTy = Context.getCanonicalType(Init->getType())
1231 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001232 if (InitTy == Context.BoolTy) {
1233 // Special handling for pointers implicitly cast to bool;
1234 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1235 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1236 Expr* SubE = ICE->getSubExpr();
1237 if (SubE->getType()->isPointerType() ||
1238 SubE->getType()->isArrayType() ||
1239 SubE->getType()->isFunctionType()) {
1240 return CheckAddressConstantExpression(Init);
1241 }
1242 }
1243 } else if (InitTy->isIntegralType()) {
1244 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001245 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001246 SubE = CE->getSubExpr();
1247 // Special check for pointer cast to int; we allow as an extension
1248 // an address constant cast to an integer if the integer
1249 // is of an appropriate width (this sort of code is apparently used
1250 // in some places).
1251 // FIXME: Add pedwarn?
1252 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1253 if (SubE && (SubE->getType()->isPointerType() ||
1254 SubE->getType()->isArrayType() ||
1255 SubE->getType()->isFunctionType())) {
1256 unsigned IntWidth = Context.getTypeSize(Init->getType());
1257 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1258 if (IntWidth >= PointerWidth)
1259 return CheckAddressConstantExpression(Init);
1260 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001261 }
1262
1263 return CheckArithmeticConstantExpression(Init);
1264 }
1265
1266 if (Init->getType()->isPointerType())
1267 return CheckAddressConstantExpression(Init);
1268
Eli Friedman25086f02008-05-30 18:14:48 +00001269 // An array type at the top level that isn't an init-list must
1270 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001271 if (Init->getType()->isArrayType())
1272 return false;
1273
Nuno Lopes1dc26762008-09-01 18:42:41 +00001274 if (Init->getType()->isFunctionType())
1275 return false;
1276
Eli Friedman02c22ce2008-05-20 13:48:25 +00001277 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1278 Init->getSourceRange());
1279 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001280}
1281
Steve Naroff6a0e2092007-09-12 14:07:44 +00001282void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001283 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001284 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001285 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001286
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001287 // If there is no declaration, there was an error parsing it. Just ignore
1288 // the initializer.
1289 if (RealDecl == 0) {
1290 delete Init;
1291 return;
1292 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001293
Steve Naroff420d0f52007-09-12 20:13:48 +00001294 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1295 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001296 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1297 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001298 RealDecl->setInvalidDecl();
1299 return;
1300 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001301 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001302 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001303 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001304 if (VDecl->isBlockVarDecl()) {
1305 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001306 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001307 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001308 VDecl->setInvalidDecl();
1309 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +00001310 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001311 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001312
1313 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1314 if (!getLangOptions().CPlusPlus) {
1315 if (SC == VarDecl::Static) // C99 6.7.8p4.
1316 CheckForConstantInitializer(Init, DclT);
1317 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001318 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001319 } else if (VDecl->isFileVarDecl()) {
1320 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001321 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001322 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +00001323 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001324 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001325
Anders Carlssonea7140a2008-08-22 05:00:02 +00001326 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1327 if (!getLangOptions().CPlusPlus) {
1328 // C99 6.7.8p4. All file scoped initializers need to be constant.
1329 CheckForConstantInitializer(Init, DclT);
1330 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001331 }
1332 // If the type changed, it means we had an incomplete type that was
1333 // completed by the initializer. For example:
1334 // int ary[] = { 1, 3, 5 };
1335 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001336 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001337 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001338 Init->setType(DclT);
1339 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001340
1341 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001342 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001343 return;
1344}
1345
Chris Lattner4b009652007-07-25 00:24:17 +00001346/// The declarators are chained together backwards, reverse the list.
1347Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1348 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001349 Decl *GroupDecl = static_cast<Decl*>(group);
1350 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001351 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001352
1353 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1354 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001355 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001356 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001357 else { // reverse the list.
1358 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001359 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001360 Group->setNextDeclarator(NewGroup);
1361 NewGroup = Group;
1362 Group = Next;
1363 }
1364 }
1365 // Perform semantic analysis that depends on having fully processed both
1366 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001367 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001368 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1369 if (!IDecl)
1370 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001371 QualType T = IDecl->getType();
1372
1373 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1374 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001375 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1376 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001377 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001378 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1379 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001380 }
1381 }
1382 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1383 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001384 if (IDecl->isBlockVarDecl() &&
1385 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001386 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001387 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1388 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001389 IDecl->setInvalidDecl();
1390 }
1391 }
1392 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1393 // object that has file scope without an initializer, and without a
1394 // storage-class specifier or with the storage-class specifier "static",
1395 // constitutes a tentative definition. Note: A tentative definition with
1396 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001397 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001398 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001399 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1400 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001401 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001402 // C99 6.9.2p3: If the declaration of an identifier for an object is
1403 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1404 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001405 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1406 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001407 IDecl->setInvalidDecl();
1408 }
1409 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001410 if (IDecl->isFileVarDecl())
1411 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001412 }
1413 return NewGroup;
1414}
Steve Naroff91b03f72007-08-28 03:03:08 +00001415
Chris Lattner3e254fb2008-04-08 04:40:51 +00001416/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1417/// to introduce parameters into function prototype scope.
1418Sema::DeclTy *
1419Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001420 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001421
1422 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001423 VarDecl::StorageClass StorageClass = VarDecl::None;
1424 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1425 StorageClass = VarDecl::Register;
1426 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001427 Diag(DS.getStorageClassSpecLoc(),
1428 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001429 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001430 }
1431 if (DS.isThreadSpecified()) {
1432 Diag(DS.getThreadSpecLoc(),
1433 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001434 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001435 }
1436
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001437 // Check that there are no default arguments inside the type of this
1438 // parameter (C++ only).
1439 if (getLangOptions().CPlusPlus)
1440 CheckExtraCXXDefaultArguments(D);
1441
Chris Lattner3e254fb2008-04-08 04:40:51 +00001442 // In this context, we *do not* check D.getInvalidType(). If the declarator
1443 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1444 // though it will not reflect the user specified type.
1445 QualType parmDeclType = GetTypeForDeclarator(D, S);
1446
1447 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1448
Chris Lattner4b009652007-07-25 00:24:17 +00001449 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1450 // Can this happen for params? We already checked that they don't conflict
1451 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001452 IdentifierInfo *II = D.getIdentifier();
1453 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1454 if (S->isDeclScope(PrevDecl)) {
1455 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1456 dyn_cast<NamedDecl>(PrevDecl)->getName());
1457
1458 // Recover by removing the name
1459 II = 0;
1460 D.SetIdentifier(0, D.getIdentifierLoc());
1461 }
Chris Lattner4b009652007-07-25 00:24:17 +00001462 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001463
1464 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1465 // Doing the promotion here has a win and a loss. The win is the type for
1466 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1467 // code generator). The loss is the orginal type isn't preserved. For example:
1468 //
1469 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1470 // int blockvardecl[5];
1471 // sizeof(parmvardecl); // size == 4
1472 // sizeof(blockvardecl); // size == 20
1473 // }
1474 //
1475 // For expressions, all implicit conversions are captured using the
1476 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1477 //
1478 // FIXME: If a source translation tool needs to see the original type, then
1479 // we need to consider storing both types (in ParmVarDecl)...
1480 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001481 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001482 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001483 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001484 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001485 parmDeclType = Context.getPointerType(parmDeclType);
1486
Chris Lattner3e254fb2008-04-08 04:40:51 +00001487 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1488 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001489 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001490 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001491
Chris Lattner3e254fb2008-04-08 04:40:51 +00001492 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001493 New->setInvalidDecl();
1494
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001495 if (II)
1496 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001497
Chris Lattner9b384ca2008-06-29 00:02:00 +00001498 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001499 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001500
Chris Lattner4b009652007-07-25 00:24:17 +00001501}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001502
Chris Lattnerea148702007-10-09 17:14:05 +00001503Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001504 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001505 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1506 "Not a function declarator!");
1507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001508
Chris Lattner4b009652007-07-25 00:24:17 +00001509 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1510 // for a K&R function.
1511 if (!FTI.hasPrototype) {
1512 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001513 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001514 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1515 FTI.ArgInfo[i].Ident->getName());
1516 // Implicitly declare the argument as type 'int' for lack of a better
1517 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001518 DeclSpec DS;
1519 const char* PrevSpec; // unused
1520 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1521 PrevSpec);
1522 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1523 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1524 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001525 }
1526 }
Chris Lattner4b009652007-07-25 00:24:17 +00001527 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001528 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001529 }
1530
1531 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001532
1533 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001534 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001535 GlobalScope);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001536 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1537 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1538 const FunctionDecl *Definition;
1539 if (FD->getBody(Definition)) {
1540 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1541 D.getIdentifier()->getName());
1542 Diag(Definition->getLocation(), diag::err_previous_definition);
1543 }
Steve Naroff1d5bd642008-01-14 20:51:29 +00001544 }
1545 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001546
1547 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001548 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001549}
1550
1551Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1552 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001553 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001554 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001555
1556 // Check the validity of our function parameters
1557 CheckParmsForFunctionDef(FD);
1558
1559 // Introduce our parameters into the function scope
1560 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1561 ParmVarDecl *Param = FD->getParamDecl(p);
1562 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001563 if (Param->getIdentifier())
1564 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001565 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001566
Chris Lattner4b009652007-07-25 00:24:17 +00001567 return FD;
1568}
1569
Steve Naroff99ee4302007-11-11 23:20:51 +00001570Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1571 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001572 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001573 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001574 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001575 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001576 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001577 } else
1578 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001579 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001580 // Verify and clean out per-function state.
1581
1582 // Check goto/label use.
1583 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1584 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1585 // Verify that we have no forward references left. If so, there was a goto
1586 // or address of a label taken, but no definition of it. Label fwd
1587 // definitions are indicated with a null substmt.
1588 if (I->second->getSubStmt() == 0) {
1589 LabelStmt *L = I->second;
1590 // Emit error.
1591 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1592
1593 // At this point, we have gotos that use the bogus label. Stitch it into
1594 // the function body so that they aren't leaked and that the AST is well
1595 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001596 if (Body) {
1597 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1598 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1599 } else {
1600 // The whole function wasn't parsed correctly, just delete this.
1601 delete L;
1602 }
Chris Lattner4b009652007-07-25 00:24:17 +00001603 }
1604 }
1605 LabelMap.clear();
1606
Steve Naroff99ee4302007-11-11 23:20:51 +00001607 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001608}
1609
Chris Lattner4b009652007-07-25 00:24:17 +00001610/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1611/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001612ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1613 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001614 // Extension in C99. Legal in C90, but warn about it.
1615 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001616 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001617 else
Chris Lattner4b009652007-07-25 00:24:17 +00001618 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1619
1620 // FIXME: handle stuff like:
1621 // void foo() { extern float X(); }
1622 // void bar() { X(); } <-- implicit decl for X in another scope.
1623
1624 // Set a Declarator for the implicit definition: int foo();
1625 const char *Dummy;
1626 DeclSpec DS;
1627 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1628 Error = Error; // Silence warning.
1629 assert(!Error && "Error setting up implicit decl!");
1630 Declarator D(DS, Declarator::BlockContext);
1631 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1632 D.SetIdentifier(&II, Loc);
1633
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001634 // Insert this function into translation-unit scope.
1635
1636 DeclContext *PrevDC = CurContext;
1637 CurContext = Context.getTranslationUnitDecl();
1638
Steve Naroff9104f3c2008-04-04 14:32:09 +00001639 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001640 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00001641 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001642
1643 CurContext = PrevDC;
1644
Steve Naroff9104f3c2008-04-04 14:32:09 +00001645 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001646}
1647
1648
Chris Lattner82bb4792007-11-14 06:34:38 +00001649TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001650 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001651 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001652 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001653
1654 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001655 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1656 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001657 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001658 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001659 if (D.getInvalidType())
1660 NewTD->setInvalidDecl();
1661 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001662}
1663
Steve Naroff0acc9c92007-09-15 18:49:24 +00001664/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001665/// former case, Name will be non-null. In the later case, Name will be null.
1666/// TagType indicates what kind of tag this is. TK indicates whether this is a
1667/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001668Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001669 SourceLocation KWLoc, IdentifierInfo *Name,
1670 SourceLocation NameLoc, AttributeList *Attr) {
1671 // If this is a use of an existing tag, it must have a name.
1672 assert((Name != 0 || TK == TK_Definition) &&
1673 "Nameless record must be a definition!");
1674
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001675 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00001676 switch (TagType) {
1677 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001678 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1679 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1680 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1681 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001682 }
1683
Ted Kremenek46a837c2008-09-05 17:16:31 +00001684 // Two code paths: a new one for structs/unions/classes where we create
1685 // separate decls for forward declarations, and an old (eventually to
1686 // be removed) code path for enums.
1687 if (Kind != TagDecl::TK_enum)
1688 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1689
Chris Lattner4b009652007-07-25 00:24:17 +00001690 // If this is a named struct, check to see if there was a previous forward
1691 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001692 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenekd4434152008-09-02 21:26:19 +00001693 ScopedDecl *PrevDecl =
1694 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1695
1696 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001697 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1698 "unexpected Decl type");
1699 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001700 // If this is a use of a previous tag, or if the tag is already declared
1701 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001702 // rementions the tag), reuse the decl.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001703 if (TK == TK_Reference ||
1704 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001705 // Make sure that this wasn't declared as an enum and now used as a
1706 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001707 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001708 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1709 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001710 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001711 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001712 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001713 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00001714 // If this is a use or a forward declaration, we're good.
1715 if (TK != TK_Definition)
1716 return PrevDecl;
1717
1718 // Diagnose attempts to redefine a tag.
1719 if (PrevTagDecl->isDefinition()) {
1720 Diag(NameLoc, diag::err_redefinition, Name->getName());
1721 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1722 // If this is a redefinition, recover by making this struct be
1723 // anonymous, which will make any later references get the previous
1724 // definition.
1725 Name = 0;
1726 } else {
1727 // Okay, this is definition of a previously declared or referenced
1728 // tag. Move the location of the decl to be the definition site.
1729 PrevDecl->setLocation(NameLoc);
1730 return PrevDecl;
1731 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001732 }
Chris Lattner4b009652007-07-25 00:24:17 +00001733 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001734 // If we get here, this is a definition of a new struct type in a nested
1735 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1736 // type.
1737 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001738 // PrevDecl is a namespace.
1739 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00001740 // The tag name clashes with a namespace name, issue an error and
1741 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00001742 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1743 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1744 Name = 0;
1745 }
Chris Lattner4b009652007-07-25 00:24:17 +00001746 }
Chris Lattner4b009652007-07-25 00:24:17 +00001747 }
1748
1749 // If there is an identifier, use the location of the identifier as the
1750 // location of the decl, otherwise use the location of the struct/union
1751 // keyword.
1752 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1753
1754 // Otherwise, if this is the first time we've seen this tag, create the decl.
1755 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001756 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00001757 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1758 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001759 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001760 // If this is an undefined enum, warn.
1761 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001762 } else {
1763 // struct/union/class
1764
Chris Lattner4b009652007-07-25 00:24:17 +00001765 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1766 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001767 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001768 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek2c984042008-09-05 01:34:33 +00001769 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001770 else
Ted Kremenek2c984042008-09-05 01:34:33 +00001771 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001772 }
Chris Lattner4b009652007-07-25 00:24:17 +00001773
1774 // If this has an identifier, add it to the scope stack.
1775 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001776 // The scope passed in may not be a decl scope. Zip up the scope tree until
1777 // we find one that is.
1778 while ((S->getFlags() & Scope::DeclScope) == 0)
1779 S = S->getParent();
1780
1781 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001782 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001783 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001784
Chris Lattnerd7e83d82008-06-28 23:58:55 +00001785 if (Attr)
1786 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001787 return New;
1788}
1789
Ted Kremenek46a837c2008-09-05 17:16:31 +00001790/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1791/// the logic for enums, we create separate decls for forward declarations.
1792/// This is called by ActOnTag, but eventually will replace its logic.
1793Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1794 SourceLocation KWLoc, IdentifierInfo *Name,
1795 SourceLocation NameLoc, AttributeList *Attr) {
1796
1797 // If this is a named struct, check to see if there was a previous forward
1798 // declaration or definition.
1799 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1800 ScopedDecl *PrevDecl =
1801 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1802
1803 if (PrevDecl) {
1804 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1805 "unexpected Decl type");
1806
1807 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1808 // If this is a use of a previous tag, or if the tag is already declared
1809 // in the same scope (so that the definition/declaration completes or
1810 // rementions the tag), reuse the decl.
1811 if (TK == TK_Reference ||
1812 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1813 // Make sure that this wasn't declared as an enum and now used as a
1814 // struct or something similar.
1815 if (PrevTagDecl->getTagKind() != Kind) {
1816 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1817 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1818 // Recover by making this an anonymous redefinition.
1819 Name = 0;
1820 PrevDecl = 0;
1821 } else {
1822 // If this is a use, return the original decl.
1823
1824 // FIXME: In the future, return a variant or some other clue
1825 // for the consumer of this Decl to know it doesn't own it.
1826 // For our current ASTs this shouldn't be a problem, but will
1827 // need to be changed with DeclGroups.
1828 if (TK == TK_Reference)
1829 return PrevDecl;
1830
1831 // The new decl is a definition?
1832 if (TK == TK_Definition) {
1833 // Diagnose attempts to redefine a tag.
1834 if (RecordDecl* DefRecord =
1835 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1836 Diag(NameLoc, diag::err_redefinition, Name->getName());
1837 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1838 // If this is a redefinition, recover by making this struct be
1839 // anonymous, which will make any later references get the previous
1840 // definition.
1841 Name = 0;
1842 PrevDecl = 0;
1843 }
1844 // Okay, this is definition of a previously declared or referenced
1845 // tag. We're going to create a new Decl.
1846 }
1847 }
1848 // If we get here we have (another) forward declaration. Just create
1849 // a new decl.
1850 }
1851 else {
1852 // If we get here, this is a definition of a new struct type in a nested
1853 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1854 // new decl/type. We set PrevDecl to NULL so that the Records
1855 // have distinct types.
1856 PrevDecl = 0;
1857 }
1858 } else {
1859 // PrevDecl is a namespace.
1860 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1861 // The tag name clashes with a namespace name, issue an error and
1862 // recover by making this tag be anonymous.
1863 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1864 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1865 Name = 0;
1866 }
1867 }
1868 }
1869
1870 // If there is an identifier, use the location of the identifier as the
1871 // location of the decl, otherwise use the location of the struct/union
1872 // keyword.
1873 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1874
1875 // Otherwise, if this is the first time we've seen this tag, create the decl.
1876 TagDecl *New;
1877
1878 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1879 // struct X { int A; } D; D should chain to X.
1880 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00001881 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek46a837c2008-09-05 17:16:31 +00001882 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1883 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1884 else
1885 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1886 dyn_cast_or_null<RecordDecl>(PrevDecl));
1887
1888 // If this has an identifier, add it to the scope stack.
1889 if ((TK == TK_Definition || !PrevDecl) && Name) {
1890 // The scope passed in may not be a decl scope. Zip up the scope tree until
1891 // we find one that is.
1892 while ((S->getFlags() & Scope::DeclScope) == 0)
1893 S = S->getParent();
1894
1895 // Add it to the decl chain.
1896 PushOnScopeChains(New, S);
1897 }
1898
1899 if (Attr)
1900 ProcessDeclAttributeList(New, Attr);
1901
1902 return New;
1903}
1904
1905
Chris Lattner1bf58f62008-06-21 19:39:06 +00001906/// Collect the instance variables declared in an Objective-C object. Used in
1907/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001908static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001909 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001910 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001911 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1912
1913 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00001914 for (ObjCInterfaceDecl::ivar_iterator
1915 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1916
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001917 ObjCIvarDecl* ID = *I;
1918 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1919 ID->getIdentifier(),
1920 ID->getType(),
1921 ID->getBitWidth()));
1922 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001923}
1924
1925/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1926/// instance variables of ClassName into Decls.
1927void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1928 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00001929 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00001930 // Check that ClassName is a valid class
1931 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1932 if (!Class) {
1933 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1934 return;
1935 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00001936 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00001937 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00001938}
1939
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001940QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1941 // This method tries to turn a variable array into a constant
1942 // array even when the size isn't an ICE. This is necessary
1943 // for compatibility with code that depends on gcc's buggy
1944 // constant expression folding, like struct {char x[(int)(char*)2];}
1945 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00001946 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001947 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00001948 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1949 llvm::APSInt &Res = Result.getInt();
1950 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1951 return Context.getConstantArrayType(VLATy->getElementType(),
1952 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001953 }
1954 }
1955 return QualType();
1956}
1957
Steve Naroff0acc9c92007-09-15 18:49:24 +00001958/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001959/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001960Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001961 SourceLocation DeclStart,
1962 Declarator &D, ExprTy *BitfieldWidth) {
1963 IdentifierInfo *II = D.getIdentifier();
1964 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001965 SourceLocation Loc = DeclStart;
1966 if (II) Loc = D.getIdentifierLoc();
1967
1968 // FIXME: Unnamed fields can be handled in various different ways, for
1969 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00001970
Chris Lattner4b009652007-07-25 00:24:17 +00001971 if (BitWidth) {
1972 // TODO: Validate.
1973 //printf("WARNING: BITFIELDS IGNORED!\n");
1974
1975 // 6.7.2.1p3
1976 // 6.7.2.1p4
1977
1978 } else {
1979 // Not a bitfield.
1980
1981 // validate II.
1982
1983 }
1984
1985 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001986 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1987 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001988
Chris Lattner4b009652007-07-25 00:24:17 +00001989 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1990 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001991 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00001992 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1993 if (!FixedTy.isNull()) {
1994 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1995 T = FixedTy;
1996 } else {
1997 // FIXME: This diagnostic needs work
1998 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1999 InvalidDecl = true;
2000 }
Chris Lattner4b009652007-07-25 00:24:17 +00002001 }
Chris Lattner4b009652007-07-25 00:24:17 +00002002 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002003 FieldDecl *NewFD;
2004
2005 if (getLangOptions().CPlusPlus) {
2006 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2007 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2008 Loc, II, T, BitWidth);
2009 if (II)
2010 PushOnScopeChains(NewFD, S);
2011 }
2012 else
2013 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002014
Chris Lattner9b384ca2008-06-29 00:02:00 +00002015 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002016
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002017 if (D.getInvalidType() || InvalidDecl)
2018 NewFD->setInvalidDecl();
2019 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002020}
2021
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002022/// TranslateIvarVisibility - Translate visibility from a token ID to an
2023/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002024static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002025TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002026 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002027 case tok::objc_private: return ObjCIvarDecl::Private;
2028 case tok::objc_public: return ObjCIvarDecl::Public;
2029 case tok::objc_protected: return ObjCIvarDecl::Protected;
2030 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002031 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00002032 }
2033}
2034
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002035/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2036/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002037Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002038 SourceLocation DeclStart,
2039 Declarator &D, ExprTy *BitfieldWidth,
2040 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002041 IdentifierInfo *II = D.getIdentifier();
2042 Expr *BitWidth = (Expr*)BitfieldWidth;
2043 SourceLocation Loc = DeclStart;
2044 if (II) Loc = D.getIdentifierLoc();
2045
2046 // FIXME: Unnamed fields can be handled in various different ways, for
2047 // example, unnamed unions inject all members into the struct namespace!
2048
2049
2050 if (BitWidth) {
2051 // TODO: Validate.
2052 //printf("WARNING: BITFIELDS IGNORED!\n");
2053
2054 // 6.7.2.1p3
2055 // 6.7.2.1p4
2056
2057 } else {
2058 // Not a bitfield.
2059
2060 // validate II.
2061
2062 }
2063
2064 QualType T = GetTypeForDeclarator(D, S);
2065 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2066 bool InvalidDecl = false;
2067
2068 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2069 // than a variably modified type.
2070 if (T->isVariablyModifiedType()) {
2071 // FIXME: This diagnostic needs work
2072 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2073 InvalidDecl = true;
2074 }
2075
Ted Kremenek173dd312008-07-23 18:04:17 +00002076 // Get the visibility (access control) for this ivar.
2077 ObjCIvarDecl::AccessControl ac =
2078 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2079 : ObjCIvarDecl::None;
2080
2081 // Construct the decl.
2082 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002083 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002084
Ted Kremenek173dd312008-07-23 18:04:17 +00002085 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002086 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002087
2088 if (D.getInvalidType() || InvalidDecl)
2089 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002090
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002091 return NewID;
2092}
2093
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002094void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002095 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002096 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002097 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002098 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2099 assert(EnclosingDecl && "missing record or interface decl");
2100 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2101
Ted Kremenek46a837c2008-09-05 17:16:31 +00002102 if (Record)
2103 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2104 // Diagnose code like:
2105 // struct S { struct S {} X; };
2106 // We discover this when we complete the outer S. Reject and ignore the
2107 // outer S.
2108 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2109 DefRecord->getKindName());
2110 Diag(RecLoc, diag::err_previous_definition);
2111 Record->setInvalidDecl();
2112 return;
2113 }
2114
Chris Lattner4b009652007-07-25 00:24:17 +00002115 // Verify that all the fields are okay.
2116 unsigned NumNamedMembers = 0;
2117 llvm::SmallVector<FieldDecl*, 32> RecFields;
2118 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002119
Chris Lattner4b009652007-07-25 00:24:17 +00002120 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002121
Steve Naroff9bb759f2007-09-14 22:20:54 +00002122 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2123 assert(FD && "missing field decl");
2124
2125 // Remember all fields.
2126 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002127
2128 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002129 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002130
Chris Lattner4b009652007-07-25 00:24:17 +00002131 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002132 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002133 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002134 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002135 FD->setInvalidDecl();
2136 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002137 continue;
2138 }
Chris Lattner4b009652007-07-25 00:24:17 +00002139 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2140 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002141 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002142 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002143 FD->setInvalidDecl();
2144 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002145 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002146 }
Chris Lattner4b009652007-07-25 00:24:17 +00002147 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002148 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002149 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002150 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002151 FD->setInvalidDecl();
2152 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002153 continue;
2154 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002155 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002156 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2157 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002158 FD->setInvalidDecl();
2159 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002160 continue;
2161 }
Chris Lattner4b009652007-07-25 00:24:17 +00002162 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002163 if (Record)
2164 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002165 }
Chris Lattner4b009652007-07-25 00:24:17 +00002166 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2167 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002168 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002169 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2170 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002171 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002172 Record->setHasFlexibleArrayMember(true);
2173 } else {
2174 // If this is a struct/class and this is not the last element, reject
2175 // it. Note that GCC supports variable sized arrays in the middle of
2176 // structures.
2177 if (i != NumFields-1) {
2178 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2179 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002180 FD->setInvalidDecl();
2181 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002182 continue;
2183 }
Chris Lattner4b009652007-07-25 00:24:17 +00002184 // We support flexible arrays at the end of structs in other structs
2185 // as an extension.
2186 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2187 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002188 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002189 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002190 }
2191 }
2192 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002193 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002194 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002195 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2196 FD->getName());
2197 FD->setInvalidDecl();
2198 EnclosingDecl->setInvalidDecl();
2199 continue;
2200 }
Chris Lattner4b009652007-07-25 00:24:17 +00002201 // Keep track of the number of named members.
2202 if (IdentifierInfo *II = FD->getIdentifier()) {
2203 // Detect duplicate member names.
2204 if (!FieldIDs.insert(II)) {
2205 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2206 // Find the previous decl.
2207 SourceLocation PrevLoc;
2208 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2209 assert(i != e && "Didn't find previous def!");
2210 if (RecFields[i]->getIdentifier() == II) {
2211 PrevLoc = RecFields[i]->getLocation();
2212 break;
2213 }
2214 }
2215 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002216 FD->setInvalidDecl();
2217 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002218 continue;
2219 }
2220 ++NumNamedMembers;
2221 }
Chris Lattner4b009652007-07-25 00:24:17 +00002222 }
2223
Chris Lattner4b009652007-07-25 00:24:17 +00002224 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002225 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002226 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002227 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2228 // Sema::ActOnFinishCXXClassDef.
2229 if (!isa<CXXRecordDecl>(Record))
2230 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002231 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002232 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2233 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2234 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2235 else if (ObjCImplementationDecl *IMPDecl =
2236 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002237 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2238 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002239 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002240 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002241 }
Chris Lattner4b009652007-07-25 00:24:17 +00002242}
2243
Steve Naroff0acc9c92007-09-15 18:49:24 +00002244Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002245 DeclTy *lastEnumConst,
2246 SourceLocation IdLoc, IdentifierInfo *Id,
2247 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002248 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002249 EnumConstantDecl *LastEnumConst =
2250 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2251 Expr *Val = static_cast<Expr*>(val);
2252
Chris Lattnera7549902007-08-26 06:24:45 +00002253 // The scope passed in may not be a decl scope. Zip up the scope tree until
2254 // we find one that is.
2255 while ((S->getFlags() & Scope::DeclScope) == 0)
2256 S = S->getParent();
2257
Chris Lattner4b009652007-07-25 00:24:17 +00002258 // Verify that there isn't already something declared with this name in this
2259 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002260 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002261 // When in C++, we may get a TagDecl with the same name; in this case the
2262 // enum constant will 'hide' the tag.
2263 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2264 "Received TagDecl when not in C++!");
2265 if (!isa<TagDecl>(PrevDecl) &&
2266 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002267 if (isa<EnumConstantDecl>(PrevDecl))
2268 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2269 else
2270 Diag(IdLoc, diag::err_redefinition, Id->getName());
2271 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002272 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002273 return 0;
2274 }
2275 }
2276
2277 llvm::APSInt EnumVal(32);
2278 QualType EltTy;
2279 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002280 // Make sure to promote the operand type to int.
2281 UsualUnaryConversions(Val);
2282
Chris Lattner4b009652007-07-25 00:24:17 +00002283 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2284 SourceLocation ExpLoc;
2285 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2286 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2287 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002288 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002289 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002290 } else {
2291 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002292 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002293 }
2294
2295 if (!Val) {
2296 if (LastEnumConst) {
2297 // Assign the last value + 1.
2298 EnumVal = LastEnumConst->getInitVal();
2299 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002300
2301 // Check for overflow on increment.
2302 if (EnumVal < LastEnumConst->getInitVal())
2303 Diag(IdLoc, diag::warn_enum_value_overflow);
2304
Chris Lattnere7f53a42007-08-27 17:37:24 +00002305 EltTy = LastEnumConst->getType();
2306 } else {
2307 // First value, set to zero.
2308 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002309 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002310 }
Chris Lattner4b009652007-07-25 00:24:17 +00002311 }
2312
Chris Lattnere4650482008-03-15 06:12:44 +00002313 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002314 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2315 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002316 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002317
2318 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002319 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002320 return New;
2321}
2322
Steve Naroffb0726b82008-08-07 14:08:16 +00002323// FIXME: For consistency with ActOnFields(), we should have the parser
2324// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002325void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002326 DeclTy **Elements, unsigned NumElements) {
2327 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002328
Steve Naroffb0726b82008-08-07 14:08:16 +00002329 if (Enum && Enum->isDefinition()) {
2330 // Diagnose code like:
2331 // enum e0 {
2332 // E0 = sizeof(enum e0 { E1 })
2333 // };
2334 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2335 Enum->getName());
2336 Diag(EnumLoc, diag::err_previous_definition);
2337 Enum->setInvalidDecl();
2338 return;
2339 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002340 // TODO: If the result value doesn't fit in an int, it must be a long or long
2341 // long value. ISO C does not support this, but GCC does as an extension,
2342 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002343 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002344
Chris Lattner206754a2007-08-28 06:15:15 +00002345 // Verify that all the values are okay, compute the size of the values, and
2346 // reverse the list.
2347 unsigned NumNegativeBits = 0;
2348 unsigned NumPositiveBits = 0;
2349
2350 // Keep track of whether all elements have type int.
2351 bool AllElementsInt = true;
2352
Chris Lattner4b009652007-07-25 00:24:17 +00002353 EnumConstantDecl *EltList = 0;
2354 for (unsigned i = 0; i != NumElements; ++i) {
2355 EnumConstantDecl *ECD =
2356 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2357 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002358
2359 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002360 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002361 assert(InitVal.getBitWidth() >= IntWidth &&
2362 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002363 if (InitVal.getBitWidth() > IntWidth) {
2364 llvm::APSInt V(InitVal);
2365 V.trunc(IntWidth);
2366 V.extend(InitVal.getBitWidth());
2367 if (V != InitVal)
2368 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002369 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002370 }
Chris Lattner206754a2007-08-28 06:15:15 +00002371
2372 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002373 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002374 NumPositiveBits = std::max(NumPositiveBits,
2375 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002376 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002377 NumNegativeBits = std::max(NumNegativeBits,
2378 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002379
Chris Lattner206754a2007-08-28 06:15:15 +00002380 // Keep track of whether every enum element has type int (very commmon).
2381 if (AllElementsInt)
2382 AllElementsInt = ECD->getType() == Context.IntTy;
2383
Chris Lattner4b009652007-07-25 00:24:17 +00002384 ECD->setNextDeclarator(EltList);
2385 EltList = ECD;
2386 }
2387
Chris Lattner206754a2007-08-28 06:15:15 +00002388 // Figure out the type that should be used for this enum.
2389 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2390 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002391 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002392
2393 if (NumNegativeBits) {
2394 // If there is a negative value, figure out the smallest integer type (of
2395 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002396 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002397 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002398 BestWidth = IntWidth;
2399 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002400 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002401
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002402 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002403 BestType = Context.LongTy;
2404 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002405 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002406
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002407 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002408 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2409 BestType = Context.LongLongTy;
2410 }
2411 }
2412 } else {
2413 // If there is no negative value, figure out which of uint, ulong, ulonglong
2414 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002415 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002416 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002417 BestWidth = IntWidth;
2418 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002419 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002420 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002421 } else {
2422 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002423 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002424 "How could an initializer get larger than ULL?");
2425 BestType = Context.UnsignedLongLongTy;
2426 }
2427 }
2428
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002429 // Loop over all of the enumerator constants, changing their types to match
2430 // the type of the enum if needed.
2431 for (unsigned i = 0; i != NumElements; ++i) {
2432 EnumConstantDecl *ECD =
2433 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2434 if (!ECD) continue; // Already issued a diagnostic.
2435
2436 // Standard C says the enumerators have int type, but we allow, as an
2437 // extension, the enumerators to be larger than int size. If each
2438 // enumerator value fits in an int, type it as an int, otherwise type it the
2439 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2440 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002441 if (ECD->getType() == Context.IntTy) {
2442 // Make sure the init value is signed.
2443 llvm::APSInt IV = ECD->getInitVal();
2444 IV.setIsSigned(true);
2445 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002446 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002447 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002448
2449 // Determine whether the value fits into an int.
2450 llvm::APSInt InitVal = ECD->getInitVal();
2451 bool FitsInInt;
2452 if (InitVal.isUnsigned() || !InitVal.isNegative())
2453 FitsInInt = InitVal.getActiveBits() < IntWidth;
2454 else
2455 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2456
2457 // If it fits into an integer type, force it. Otherwise force it to match
2458 // the enum decl type.
2459 QualType NewTy;
2460 unsigned NewWidth;
2461 bool NewSign;
2462 if (FitsInInt) {
2463 NewTy = Context.IntTy;
2464 NewWidth = IntWidth;
2465 NewSign = true;
2466 } else if (ECD->getType() == BestType) {
2467 // Already the right type!
2468 continue;
2469 } else {
2470 NewTy = BestType;
2471 NewWidth = BestWidth;
2472 NewSign = BestType->isSignedIntegerType();
2473 }
2474
2475 // Adjust the APSInt value.
2476 InitVal.extOrTrunc(NewWidth);
2477 InitVal.setIsSigned(NewSign);
2478 ECD->setInitVal(InitVal);
2479
2480 // Adjust the Expr initializer and type.
2481 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2482 ECD->setType(NewTy);
2483 }
Chris Lattner206754a2007-08-28 06:15:15 +00002484
Chris Lattner90a018d2007-08-28 18:24:31 +00002485 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002486 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002487}
2488
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002489Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2490 ExprTy *expr) {
2491 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2492
Chris Lattner81db64a2008-03-16 00:16:02 +00002493 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002494}
2495
Chris Lattner806a5f52008-01-12 07:05:38 +00002496Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002497 SourceLocation LBrace,
2498 SourceLocation RBrace,
2499 const char *Lang,
2500 unsigned StrSize,
2501 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002502 LinkageSpecDecl::LanguageIDs Language;
2503 Decl *dcl = static_cast<Decl *>(D);
2504 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2505 Language = LinkageSpecDecl::lang_c;
2506 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2507 Language = LinkageSpecDecl::lang_cxx;
2508 else {
2509 Diag(Loc, diag::err_bad_language);
2510 return 0;
2511 }
2512
2513 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002514 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002515}