blob: 4d726cf0a8573f6d9b87a1d2fadeca48aff6ca33 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000018#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Builtins.h"
20#include "clang/AST/Decl.h"
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +000021#include "clang/AST/DeclCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/AST/Expr.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000023#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/AST/Type.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Basic/SourceManager.h"
30// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000031#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000032#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000033#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000035#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Steve Naroffb327ce02008-04-02 14:35:35 +000038Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
40
Douglas Gregor2ce52f32008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000045 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000046}
47
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000048DeclContext *Sema::getDCParent(DeclContext *DC) {
49 // If CurContext is a ObjC method, getParent() will return NULL.
50 if (isa<ObjCMethodDecl>(DC))
51 return Context.getTranslationUnitDecl();
52
53 // A C++ inline method is parsed *after* the topmost class it was declared in
54 // is fully parsed (it's "complete").
55 // The parsing of a C++ inline method happens at the declaration context of
56 // the topmost (non-nested) class it is declared in.
57 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
58 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
60 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
68 return DC->getParent();
69}
70
Chris Lattner9fdf9c62008-04-22 18:39:57 +000071void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000072 assert(getDCParent(DC) == CurContext &&
73 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000074 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000075}
76
Chris Lattnerb048c982008-04-06 04:47:34 +000077void Sema::PopDeclContext() {
78 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000080}
81
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000082/// Add this decl to the scope shadowed decl chains.
83void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000084 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000085
86 // C++ [basic.scope]p4:
87 // -- exactly one declaration shall declare a class name or
88 // enumeration name that is not a typedef name and the other
89 // declarations shall all refer to the same object or
90 // enumerator, or all refer to functions and function templates;
91 // in this case the class name or enumeration name is hidden.
92 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
93 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000094 IdentifierResolver::iterator
95 I = IdResolver.begin(TD->getIdentifier(),
96 TD->getDeclContext(), false/*LookInParentCtx*/);
97 if (I != IdResolver.end() &&
98 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000099 // There is already a declaration with the same name in the same
100 // scope. It must be found before we find the new declaration,
101 // so swap the order on the shadowed declaration chain.
102
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000103 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104 return;
105 }
106 }
107
108 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000109}
110
Steve Naroffb216c882007-10-09 22:01:59 +0000111void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000112 if (S->decl_empty()) return;
113 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
116 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000117 Decl *TmpD = static_cast<Decl*>(*I);
118 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000119
120 if (isa<CXXFieldDecl>(TmpD)) continue;
121
122 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
123 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000124
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 IdentifierInfo *II = D->getIdentifier();
126 if (!II) continue;
127
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000128 // We only want to remove the decls from the identifier decl chains for local
129 // scopes, when inside a function/method.
130 if (S->getFnParent() != 0)
131 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000132
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000133 // Chain this decl to the containing DeclContext.
134 D->setNext(CurContext->getDeclChain());
135 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 }
137}
138
Steve Naroffe8043c32008-04-01 23:04:06 +0000139/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
140/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000141ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000142 // The third "scope" argument is 0 since we aren't enabling lazy built-in
143 // creation from this context.
144 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000145
Steve Naroffb327ce02008-04-02 14:35:35 +0000146 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000147}
148
Steve Naroffe8043c32008-04-01 23:04:06 +0000149/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000150/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000151Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
152 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000154 unsigned NS = NSI;
155 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
156 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 // Scan up the scope chain looking for a decl that matches this identifier
159 // that is in the appropriate namespace. This search should not take long, as
160 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000161 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000162 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000163 if ((*I)->getIdentifierNamespace() & NS)
164 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 // If we didn't find a use of this identifier, and if the identifier
167 // corresponds to a compiler builtin, create the decl object for the builtin
168 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000169 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000170 if (enableLazyBuiltinCreation) {
171 // If this is a builtin on this (or all) targets, create the decl.
172 if (unsigned BuiltinID = II->getBuiltinID())
173 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
174 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000175 if (getLangOptions().ObjC1) {
176 // @interface and @compatibility_alias introduce typedef-like names.
177 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000178 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000179 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000180 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
181 if (IDI != ObjCInterfaceDecls.end())
182 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000183 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
184 if (I != ObjCAliasDecls.end())
185 return I->second->getClassInterface();
186 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 }
188 return 0;
189}
190
Chris Lattner95e2c712008-05-05 22:18:14 +0000191void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000192 if (!Context.getBuiltinVaListType().isNull())
193 return;
194
195 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000196 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000197 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000198 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
199}
200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
202/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000203ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
204 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 Builtin::ID BID = (Builtin::ID)bid;
206
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000207 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000208 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerf8396b62008-07-09 17:26:36 +0000209 BID == Builtin::BI__builtin_va_end ||
210 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000211 InitBuiltinVaListType();
212
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000213 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000214 FunctionDecl *New = FunctionDecl::Create(Context,
215 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000216 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000217 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000218
Chris Lattner95e2c712008-05-05 22:18:14 +0000219 // Create Decl objects for each parameter, adding them to the
220 // FunctionDecl.
221 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
222 llvm::SmallVector<ParmVarDecl*, 16> Params;
223 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
224 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
225 FT->getArgType(i), VarDecl::None, 0,
226 0));
227 New->setParams(&Params[0], Params.size());
228 }
229
230
231
Chris Lattner7f925cc2008-04-11 07:00:53 +0000232 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000233 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 return New;
235}
236
237/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
238/// and scope as a previous declaration 'Old'. Figure out how to resolve this
239/// situation, merging decls or emitting diagnostics as appropriate.
240///
Steve Naroffe8043c32008-04-01 23:04:06 +0000241TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 // Verify the old decl was also a typedef.
243 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
244 if (!Old) {
245 Diag(New->getLocation(), diag::err_redefinition_different_kind,
246 New->getName());
247 Diag(OldD->getLocation(), diag::err_previous_definition);
248 return New;
249 }
250
Steve Naroff8ee529b2007-10-31 18:42:27 +0000251 // Allow multiple definitions for ObjC built-in typedefs.
252 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000254 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000255
256 if (getLangOptions().Microsoft) return New;
257
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000258 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
259 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
260 // *either* declaration is in a system header. The code below implements
261 // this adhoc compatibility rule. FIXME: The following code will not
262 // work properly when compiling ".i" files (containing preprocessed output).
263 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000264 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000265 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
266 if (OldDeclFile) {
267 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
268 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
269 if (OldDirType != DirectoryLookup::NormalHeaderDir)
270 return New;
271 }
272 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
273 if (NewDeclFile) {
274 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
275 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
276 if (NewDirType != DirectoryLookup::NormalHeaderDir)
277 return New;
278 }
279
Ted Kremenek2d05c082008-05-23 21:28:18 +0000280 Diag(New->getLocation(), diag::err_redefinition, New->getName());
281 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 return New;
283}
284
Chris Lattner6b6b5372008-06-26 18:38:35 +0000285/// DeclhasAttr - returns true if decl Declaration already has the target
286/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000287static bool DeclHasAttr(const Decl *decl, const Attr *target) {
288 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
289 if (attr->getKind() == target->getKind())
290 return true;
291
292 return false;
293}
294
295/// MergeAttributes - append attributes from the Old decl to the New one.
296static void MergeAttributes(Decl *New, Decl *Old) {
297 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
298
Chris Lattnerddee4232008-03-03 03:28:21 +0000299 while (attr) {
300 tmp = attr;
301 attr = attr->getNext();
302
303 if (!DeclHasAttr(New, tmp)) {
304 New->addAttr(tmp);
305 } else {
306 tmp->setNext(0);
307 delete(tmp);
308 }
309 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000310
311 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000312}
313
Chris Lattner04421082008-04-08 04:40:51 +0000314/// MergeFunctionDecl - We just parsed a function 'New' from
315/// declarator D which has the same name and scope as a previous
316/// declaration 'Old'. Figure out how to resolve this situation,
317/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000318/// Redeclaration will be set true if thisNew is a redeclaration OldD.
319FunctionDecl *
320Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
321 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 // Verify the old decl was also a function.
323 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
324 if (!Old) {
325 Diag(New->getLocation(), diag::err_redefinition_different_kind,
326 New->getName());
327 Diag(OldD->getLocation(), diag::err_previous_definition);
328 return New;
329 }
Chris Lattner04421082008-04-08 04:40:51 +0000330
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000331 QualType OldQType = Context.getCanonicalType(Old->getType());
332 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000333
Chris Lattner04421082008-04-08 04:40:51 +0000334 // C++ [dcl.fct]p3:
335 // All declarations for a function shall agree exactly in both the
336 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000337 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
338 MergeAttributes(New, Old);
339 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000340 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000341 }
Chris Lattner04421082008-04-08 04:40:51 +0000342
343 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000344 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000345 if (!getLangOptions().CPlusPlus &&
346 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000347 MergeAttributes(New, Old);
348 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000349 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000350 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000351
Steve Naroff837618c2008-01-16 15:01:34 +0000352 // A function that has already been declared has been redeclared or defined
353 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000354 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000355 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000356 PrevDiag = diag::err_previous_definition;
357 else if (Old->isImplicit())
358 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000359 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000360 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
363 // TODO: This is totally simplistic. It should handle merging functions
364 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000365 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
366 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 return New;
368}
369
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000370/// equivalentArrayTypes - Used to determine whether two array types are
371/// equivalent.
372/// We need to check this explicitly as an incomplete array definition is
373/// considered a VariableArrayType, so will not match a complete array
374/// definition that would be otherwise equivalent.
375static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
376 const ArrayType *NewAT = NewQType->getAsArrayType();
377 const ArrayType *OldAT = OldQType->getAsArrayType();
378
379 if (!NewAT || !OldAT)
380 return false;
381
382 // If either (or both) array types in incomplete we need to strip off the
383 // outer VariableArrayType. Once the outer VAT is removed the remaining
384 // types must be identical if the array types are to be considered
385 // equivalent.
386 // eg. int[][1] and int[1][1] become
387 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
388 // removing the outermost VAT gives
389 // CAT(1, int) and CAT(1, int)
390 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000391 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000392 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
393 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000394 NewQType = NewAT->getElementType().getCanonicalType();
395 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000396 }
397
398 return NewQType == OldQType;
399}
400
Reid Spencer5f016e22007-07-11 17:01:13 +0000401/// MergeVarDecl - We just parsed a variable 'New' which has the same name
402/// and scope as a previous declaration 'Old'. Figure out how to resolve this
403/// situation, merging decls or emitting diagnostics as appropriate.
404///
405/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
406/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
407///
Steve Naroffe8043c32008-04-01 23:04:06 +0000408VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 // Verify the old decl was also a variable.
410 VarDecl *Old = dyn_cast<VarDecl>(OldD);
411 if (!Old) {
412 Diag(New->getLocation(), diag::err_redefinition_different_kind,
413 New->getName());
414 Diag(OldD->getLocation(), diag::err_previous_definition);
415 return New;
416 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000417
418 MergeAttributes(New, Old);
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000421 QualType OldCType = Context.getCanonicalType(Old->getType());
422 QualType NewCType = Context.getCanonicalType(New->getType());
423 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000424 Diag(New->getLocation(), diag::err_redefinition, New->getName());
425 Diag(Old->getLocation(), diag::err_previous_definition);
426 return New;
427 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000428 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
429 if (New->getStorageClass() == VarDecl::Static &&
430 (Old->getStorageClass() == VarDecl::None ||
431 Old->getStorageClass() == VarDecl::Extern)) {
432 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
433 Diag(Old->getLocation(), diag::err_previous_definition);
434 return New;
435 }
436 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
437 if (New->getStorageClass() != VarDecl::Static &&
438 Old->getStorageClass() == VarDecl::Static) {
439 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
440 Diag(Old->getLocation(), diag::err_previous_definition);
441 return New;
442 }
443 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000444 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000445 // Handle C "tentative" external object definitions (C99 6.9.2).
446 bool OldIsTentative = false;
447 bool NewIsTentative = false;
448
Steve Naroff248a7532008-04-15 22:42:06 +0000449 if (!Old->getInit() &&
450 (Old->getStorageClass() == VarDecl::None ||
451 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000452 OldIsTentative = true;
453
454 // FIXME: this check doesn't work (since the initializer hasn't been
455 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
456 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
457 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000458 if (!New->getInit() &&
459 (New->getStorageClass() == VarDecl::None ||
460 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000461 ; // change to NewIsTentative = true; once the code is moved.
462
463 if (NewIsTentative || OldIsTentative)
464 return New;
465 }
Steve Naroff235549c2008-05-12 22:36:43 +0000466 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000467 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000468 Old->getStorageClass() != VarDecl::PrivateExtern &&
469 New->getStorageClass() != VarDecl::Extern &&
470 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 Diag(New->getLocation(), diag::err_redefinition, New->getName());
472 Diag(Old->getLocation(), diag::err_previous_definition);
473 }
474 return New;
475}
476
Chris Lattner04421082008-04-08 04:40:51 +0000477/// CheckParmsForFunctionDef - Check that the parameters of the given
478/// function are appropriate for the definition of a function. This
479/// takes care of any checks that cannot be performed on the
480/// declaration itself, e.g., that the types of each of the function
481/// parameters are complete.
482bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
483 bool HasInvalidParm = false;
484 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
485 ParmVarDecl *Param = FD->getParamDecl(p);
486
487 // C99 6.7.5.3p4: the parameters in a parameter type list in a
488 // function declarator that is part of a function definition of
489 // that function shall not have incomplete type.
490 if (Param->getType()->isIncompleteType() &&
491 !Param->isInvalidDecl()) {
492 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
493 Param->getType().getAsString());
494 Param->setInvalidDecl();
495 HasInvalidParm = true;
496 }
497 }
498
499 return HasInvalidParm;
500}
501
502/// CreateImplicitParameter - Creates an implicit function parameter
503/// in the scope S and with the given type. This routine is used, for
504/// example, to create the implicit "self" parameter in an Objective-C
505/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000506ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000507Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
508 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000509 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
510 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000511 if (Id)
512 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000513
514 return New;
515}
516
Reid Spencer5f016e22007-07-11 17:01:13 +0000517/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
518/// no declarator (e.g. "struct foo;") is parsed.
519Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
520 // TODO: emit error on 'int;' or 'const enum foo;'.
521 // TODO: emit error on 'typedef int;'
522 // if (!DS.isMissingDeclaratorOk()) Diag(...);
523
Steve Naroff92199282007-11-17 21:37:36 +0000524 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000525}
526
Steve Naroffd0091aa2008-01-10 22:15:12 +0000527bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000528 // Get the type before calling CheckSingleAssignmentConstraints(), since
529 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000530 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000531
Chris Lattner5cf216b2008-01-04 18:04:52 +0000532 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
533 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
534 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000535}
536
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000537bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000538 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000539 // C99 6.7.8p14. We have an array of character type with unknown size
540 // being initialized to a string literal.
541 llvm::APSInt ConstVal(32);
542 ConstVal = strLiteral->getByteLength() + 1;
543 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000544 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000545 ArrayType::Normal, 0);
546 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
547 // C99 6.7.8p14. We have an array of character type with known size.
548 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
549 Diag(strLiteral->getSourceRange().getBegin(),
550 diag::warn_initializer_string_for_char_array_too_long,
551 strLiteral->getSourceRange());
552 } else {
553 assert(0 && "HandleStringLiteralInit(): Invalid array type");
554 }
555 // Set type from "char *" to "constant array of char".
556 strLiteral->setType(DeclT);
557 // For now, we always return false (meaning success).
558 return false;
559}
560
561StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000562 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000563 if (AT && AT->getElementType()->isCharType()) {
564 return dyn_cast<StringLiteral>(Init);
565 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000566 return 0;
567}
568
Steve Naroffa9960332008-01-25 00:51:06 +0000569bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000570 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
571 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000572 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000573 return Diag(VAT->getSizeExpr()->getLocStart(),
574 diag::err_variable_object_no_init,
575 VAT->getSizeExpr()->getSourceRange());
576
Steve Naroff2fdc3742007-12-10 22:44:33 +0000577 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
578 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000579 // FIXME: Handle wide strings
580 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
581 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000582
583 if (DeclType->isArrayType())
584 return Diag(Init->getLocStart(),
585 diag::err_array_init_list_required,
586 Init->getSourceRange());
587
Steve Naroffd0091aa2008-01-10 22:15:12 +0000588 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000589 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000590
Steve Naroff0cca7492008-05-01 22:18:59 +0000591 InitListChecker CheckInitList(this, InitList, DeclType);
592 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000593}
594
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000595Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000596Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000597 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 IdentifierInfo *II = D.getIdentifier();
599
Chris Lattnere80a59c2007-07-25 00:24:17 +0000600 // All of these full declarators require an identifier. If it doesn't have
601 // one, the ParsedFreeStandingDeclSpec action should be used.
602 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000603 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000604 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000605 D.getDeclSpec().getSourceRange(), D.getSourceRange());
606 return 0;
607 }
608
Chris Lattner31e05722007-08-26 06:24:45 +0000609 // The scope passed in may not be a decl scope. Zip up the scope tree until
610 // we find one that is.
611 while ((S->getFlags() & Scope::DeclScope) == 0)
612 S = S->getParent();
613
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000615 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000616 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000617 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000618
619 // In C++, the previous declaration we find might be a tag type
620 // (class or enum). In this case, the new declaration will hide the
621 // tag type.
622 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
623 PrevDecl = 0;
624
Chris Lattner41af0932007-11-14 06:34:38 +0000625 QualType R = GetTypeForDeclarator(D, S);
626 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000629 // Check that there are no default arguments (C++ only).
630 if (getLangOptions().CPlusPlus)
631 CheckExtraCXXDefaultArguments(D);
632
Chris Lattner41af0932007-11-14 06:34:38 +0000633 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 if (!NewTD) return 0;
635
636 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000637 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000638 // Merge the decl with the existing one if appropriate. If the decl is
639 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000640 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
642 if (NewTD == 0) return 0;
643 }
644 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000645 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 // C99 6.7.7p2: If a typedef name specifies a variably modified type
647 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000648 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
649 // FIXME: Diagnostic needs to be fixed.
650 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000651 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 }
653 }
Chris Lattner41af0932007-11-14 06:34:38 +0000654 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000655 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 switch (D.getDeclSpec().getStorageClassSpec()) {
657 default: assert(0 && "Unknown storage class!");
658 case DeclSpec::SCS_auto:
659 case DeclSpec::SCS_register:
660 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
661 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000662 InvalidDecl = true;
663 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
665 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
666 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000667 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 }
669
Chris Lattnera98e58d2008-03-15 21:24:04 +0000670 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000671 FunctionDecl *NewFD;
672 if (D.getContext() == Declarator::MemberContext) {
673 // This is a C++ method declaration.
674 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
675 D.getIdentifierLoc(), II, R,
676 (SC == FunctionDecl::Static), isInline,
677 LastDeclarator);
678 } else {
679 NewFD = FunctionDecl::Create(Context, CurContext,
680 D.getIdentifierLoc(),
681 II, R, SC, isInline,
682 LastDeclarator);
683 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000684 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000685 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000686
687 // Copy the parameter declarations from the declarator D to
688 // the function declaration NewFD, if they are available.
689 if (D.getNumTypeObjects() > 0 &&
690 D.getTypeObject(0).Fun.hasPrototype) {
691 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
692
693 // Create Decl objects for each parameter, adding them to the
694 // FunctionDecl.
695 llvm::SmallVector<ParmVarDecl*, 16> Params;
696
697 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
698 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000699 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000700 // We let through "const void" here because Sema::GetTypeForDeclarator
701 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000702 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
703 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000704 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
705 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000706 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
707
Chris Lattnerdef026a2008-04-10 02:26:16 +0000708 // In C++, the empty parameter-type-list must be spelled "void"; a
709 // typedef of void is not permitted.
710 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000711 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000712 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
713 }
714
Chris Lattner04421082008-04-08 04:40:51 +0000715 } else {
716 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
717 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
718 }
719
720 NewFD->setParams(&Params[0], Params.size());
721 }
722
Steve Naroffffce4d52008-01-09 23:34:55 +0000723 // Merge the decl with the existing one if appropriate. Since C functions
724 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000725 if (PrevDecl &&
726 (!getLangOptions().CPlusPlus ||
727 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000728 bool Redeclaration = false;
729 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000731 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000732 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000733 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
735 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000736
737 // In C++, check default arguments now that we have merged decls.
738 if (getLangOptions().CPlusPlus)
739 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000741 // Check that there are no default arguments (C++ only).
742 if (getLangOptions().CPlusPlus)
743 CheckExtraCXXDefaultArguments(D);
744
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000745 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000746 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
747 D.getIdentifier()->getName());
748 InvalidDecl = true;
749 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000750
751 VarDecl *NewVD;
752 VarDecl::StorageClass SC;
753 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000754 default: assert(0 && "Unknown storage class!");
755 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
756 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
757 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
758 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
759 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
760 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000762 if (D.getContext() == Declarator::MemberContext) {
763 assert(SC == VarDecl::Static && "Invalid storage class for member!");
764 // This is a static data member for a C++ class.
765 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
766 D.getIdentifierLoc(), II,
767 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000768 } else {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000769 if (S->getFnParent() == 0) {
770 // C99 6.9p2: The storage-class specifiers auto and register shall not
771 // appear in the declaration specifiers in an external declaration.
772 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
773 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
774 R.getAsString());
775 InvalidDecl = true;
776 }
777 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
778 II, R, SC, LastDeclarator);
779 } else {
780 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
781 II, R, SC, LastDeclarator);
782 }
Steve Naroff53a32342007-08-28 18:45:29 +0000783 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000785 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000786
787 // Emit an error if an address space was applied to decl with local storage.
788 // This includes arrays of objects with address space qualifiers, but not
789 // automatic variables that point to other address spaces.
790 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000791 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
792 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
793 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000794 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000795 // Merge the decl with the existing one if appropriate. If the decl is
796 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000797 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 NewVD = MergeVarDecl(NewVD, PrevDecl);
799 if (NewVD == 0) return 0;
800 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 New = NewVD;
802 }
803
804 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000805 if (II)
806 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000807 // If any semantic error occurred, mark the decl as invalid.
808 if (D.getInvalidType() || InvalidDecl)
809 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 return New;
812}
813
Eli Friedmanc594b322008-05-20 13:48:25 +0000814bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
815 switch (Init->getStmtClass()) {
816 default:
817 Diag(Init->getExprLoc(),
818 diag::err_init_element_not_constant, Init->getSourceRange());
819 return true;
820 case Expr::ParenExprClass: {
821 const ParenExpr* PE = cast<ParenExpr>(Init);
822 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
823 }
824 case Expr::CompoundLiteralExprClass:
825 return cast<CompoundLiteralExpr>(Init)->isFileScope();
826 case Expr::DeclRefExprClass: {
827 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000828 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
829 if (VD->hasGlobalStorage())
830 return false;
831 Diag(Init->getExprLoc(),
832 diag::err_init_element_not_constant, Init->getSourceRange());
833 return true;
834 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000835 if (isa<FunctionDecl>(D))
836 return false;
837 Diag(Init->getExprLoc(),
838 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000839 return true;
840 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000841 case Expr::MemberExprClass: {
842 const MemberExpr *M = cast<MemberExpr>(Init);
843 if (M->isArrow())
844 return CheckAddressConstantExpression(M->getBase());
845 return CheckAddressConstantExpressionLValue(M->getBase());
846 }
847 case Expr::ArraySubscriptExprClass: {
848 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
849 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
850 return CheckAddressConstantExpression(ASE->getBase()) ||
851 CheckArithmeticConstantExpression(ASE->getIdx());
852 }
853 case Expr::StringLiteralClass:
854 case Expr::PreDefinedExprClass:
855 return false;
856 case Expr::UnaryOperatorClass: {
857 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
858
859 // C99 6.6p9
860 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000861 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000862
863 Diag(Init->getExprLoc(),
864 diag::err_init_element_not_constant, Init->getSourceRange());
865 return true;
866 }
867 }
868}
869
870bool Sema::CheckAddressConstantExpression(const Expr* Init) {
871 switch (Init->getStmtClass()) {
872 default:
873 Diag(Init->getExprLoc(),
874 diag::err_init_element_not_constant, Init->getSourceRange());
875 return true;
876 case Expr::ParenExprClass: {
877 const ParenExpr* PE = cast<ParenExpr>(Init);
878 return CheckAddressConstantExpression(PE->getSubExpr());
879 }
880 case Expr::StringLiteralClass:
881 case Expr::ObjCStringLiteralClass:
882 return false;
883 case Expr::CallExprClass: {
884 const CallExpr *CE = cast<CallExpr>(Init);
885 if (CE->isBuiltinConstantExpr())
886 return false;
887 Diag(Init->getExprLoc(),
888 diag::err_init_element_not_constant, Init->getSourceRange());
889 return true;
890 }
891 case Expr::UnaryOperatorClass: {
892 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
893
894 // C99 6.6p9
895 if (Exp->getOpcode() == UnaryOperator::AddrOf)
896 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
897
898 if (Exp->getOpcode() == UnaryOperator::Extension)
899 return CheckAddressConstantExpression(Exp->getSubExpr());
900
901 Diag(Init->getExprLoc(),
902 diag::err_init_element_not_constant, Init->getSourceRange());
903 return true;
904 }
905 case Expr::BinaryOperatorClass: {
906 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
907 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
908
909 Expr *PExp = Exp->getLHS();
910 Expr *IExp = Exp->getRHS();
911 if (IExp->getType()->isPointerType())
912 std::swap(PExp, IExp);
913
914 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
915 return CheckAddressConstantExpression(PExp) ||
916 CheckArithmeticConstantExpression(IExp);
917 }
918 case Expr::ImplicitCastExprClass: {
919 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
920
921 // Check for implicit promotion
922 if (SubExpr->getType()->isFunctionType() ||
923 SubExpr->getType()->isArrayType())
924 return CheckAddressConstantExpressionLValue(SubExpr);
925
926 // Check for pointer->pointer cast
927 if (SubExpr->getType()->isPointerType())
928 return CheckAddressConstantExpression(SubExpr);
929
930 if (SubExpr->getType()->isArithmeticType())
931 return CheckArithmeticConstantExpression(SubExpr);
932
933 Diag(Init->getExprLoc(),
934 diag::err_init_element_not_constant, Init->getSourceRange());
935 return true;
936 }
937 case Expr::CastExprClass: {
938 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
939
940 // Check for pointer->pointer cast
941 if (SubExpr->getType()->isPointerType())
942 return CheckAddressConstantExpression(SubExpr);
943
944 // FIXME: Should we pedwarn for (int*)(0+0)?
945 if (SubExpr->getType()->isArithmeticType())
946 return CheckArithmeticConstantExpression(SubExpr);
947
948 Diag(Init->getExprLoc(),
949 diag::err_init_element_not_constant, Init->getSourceRange());
950 return true;
951 }
952 case Expr::ConditionalOperatorClass: {
953 // FIXME: Should we pedwarn here?
954 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
955 if (!Exp->getCond()->getType()->isArithmeticType()) {
956 Diag(Init->getExprLoc(),
957 diag::err_init_element_not_constant, Init->getSourceRange());
958 return true;
959 }
960 if (CheckArithmeticConstantExpression(Exp->getCond()))
961 return true;
962 if (Exp->getLHS() &&
963 CheckAddressConstantExpression(Exp->getLHS()))
964 return true;
965 return CheckAddressConstantExpression(Exp->getRHS());
966 }
967 case Expr::AddrLabelExprClass:
968 return false;
969 }
970}
971
Eli Friedman4caf0552008-06-09 05:05:07 +0000972static const Expr* FindExpressionBaseAddress(const Expr* E);
973
974static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
975 switch (E->getStmtClass()) {
976 default:
977 return E;
978 case Expr::ParenExprClass: {
979 const ParenExpr* PE = cast<ParenExpr>(E);
980 return FindExpressionBaseAddressLValue(PE->getSubExpr());
981 }
982 case Expr::MemberExprClass: {
983 const MemberExpr *M = cast<MemberExpr>(E);
984 if (M->isArrow())
985 return FindExpressionBaseAddress(M->getBase());
986 return FindExpressionBaseAddressLValue(M->getBase());
987 }
988 case Expr::ArraySubscriptExprClass: {
989 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
990 return FindExpressionBaseAddress(ASE->getBase());
991 }
992 case Expr::UnaryOperatorClass: {
993 const UnaryOperator *Exp = cast<UnaryOperator>(E);
994
995 if (Exp->getOpcode() == UnaryOperator::Deref)
996 return FindExpressionBaseAddress(Exp->getSubExpr());
997
998 return E;
999 }
1000 }
1001}
1002
1003static const Expr* FindExpressionBaseAddress(const Expr* E) {
1004 switch (E->getStmtClass()) {
1005 default:
1006 return E;
1007 case Expr::ParenExprClass: {
1008 const ParenExpr* PE = cast<ParenExpr>(E);
1009 return FindExpressionBaseAddress(PE->getSubExpr());
1010 }
1011 case Expr::UnaryOperatorClass: {
1012 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1013
1014 // C99 6.6p9
1015 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1016 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1017
1018 if (Exp->getOpcode() == UnaryOperator::Extension)
1019 return FindExpressionBaseAddress(Exp->getSubExpr());
1020
1021 return E;
1022 }
1023 case Expr::BinaryOperatorClass: {
1024 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1025
1026 Expr *PExp = Exp->getLHS();
1027 Expr *IExp = Exp->getRHS();
1028 if (IExp->getType()->isPointerType())
1029 std::swap(PExp, IExp);
1030
1031 return FindExpressionBaseAddress(PExp);
1032 }
1033 case Expr::ImplicitCastExprClass: {
1034 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1035
1036 // Check for implicit promotion
1037 if (SubExpr->getType()->isFunctionType() ||
1038 SubExpr->getType()->isArrayType())
1039 return FindExpressionBaseAddressLValue(SubExpr);
1040
1041 // Check for pointer->pointer cast
1042 if (SubExpr->getType()->isPointerType())
1043 return FindExpressionBaseAddress(SubExpr);
1044
1045 // We assume that we have an arithmetic expression here;
1046 // if we don't, we'll figure it out later
1047 return 0;
1048 }
1049 case Expr::CastExprClass: {
1050 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1051
1052 // Check for pointer->pointer cast
1053 if (SubExpr->getType()->isPointerType())
1054 return FindExpressionBaseAddress(SubExpr);
1055
1056 // We assume that we have an arithmetic expression here;
1057 // if we don't, we'll figure it out later
1058 return 0;
1059 }
1060 }
1061}
1062
Eli Friedmanc594b322008-05-20 13:48:25 +00001063bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1064 switch (Init->getStmtClass()) {
1065 default:
1066 Diag(Init->getExprLoc(),
1067 diag::err_init_element_not_constant, Init->getSourceRange());
1068 return true;
1069 case Expr::ParenExprClass: {
1070 const ParenExpr* PE = cast<ParenExpr>(Init);
1071 return CheckArithmeticConstantExpression(PE->getSubExpr());
1072 }
1073 case Expr::FloatingLiteralClass:
1074 case Expr::IntegerLiteralClass:
1075 case Expr::CharacterLiteralClass:
1076 case Expr::ImaginaryLiteralClass:
1077 case Expr::TypesCompatibleExprClass:
1078 case Expr::CXXBoolLiteralExprClass:
1079 return false;
1080 case Expr::CallExprClass: {
1081 const CallExpr *CE = cast<CallExpr>(Init);
1082 if (CE->isBuiltinConstantExpr())
1083 return false;
1084 Diag(Init->getExprLoc(),
1085 diag::err_init_element_not_constant, Init->getSourceRange());
1086 return true;
1087 }
1088 case Expr::DeclRefExprClass: {
1089 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1090 if (isa<EnumConstantDecl>(D))
1091 return false;
1092 Diag(Init->getExprLoc(),
1093 diag::err_init_element_not_constant, Init->getSourceRange());
1094 return true;
1095 }
1096 case Expr::CompoundLiteralExprClass:
1097 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1098 // but vectors are allowed to be magic.
1099 if (Init->getType()->isVectorType())
1100 return false;
1101 Diag(Init->getExprLoc(),
1102 diag::err_init_element_not_constant, Init->getSourceRange());
1103 return true;
1104 case Expr::UnaryOperatorClass: {
1105 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1106
1107 switch (Exp->getOpcode()) {
1108 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1109 // See C99 6.6p3.
1110 default:
1111 Diag(Init->getExprLoc(),
1112 diag::err_init_element_not_constant, Init->getSourceRange());
1113 return true;
1114 case UnaryOperator::SizeOf:
1115 case UnaryOperator::AlignOf:
1116 case UnaryOperator::OffsetOf:
1117 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1118 // See C99 6.5.3.4p2 and 6.6p3.
1119 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1120 return false;
1121 Diag(Init->getExprLoc(),
1122 diag::err_init_element_not_constant, Init->getSourceRange());
1123 return true;
1124 case UnaryOperator::Extension:
1125 case UnaryOperator::LNot:
1126 case UnaryOperator::Plus:
1127 case UnaryOperator::Minus:
1128 case UnaryOperator::Not:
1129 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1130 }
1131 }
1132 case Expr::SizeOfAlignOfTypeExprClass: {
1133 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1134 // Special check for void types, which are allowed as an extension
1135 if (Exp->getArgumentType()->isVoidType())
1136 return false;
1137 // alignof always evaluates to a constant.
1138 // FIXME: is sizeof(int[3.0]) a constant expression?
1139 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1140 Diag(Init->getExprLoc(),
1141 diag::err_init_element_not_constant, Init->getSourceRange());
1142 return true;
1143 }
1144 return false;
1145 }
1146 case Expr::BinaryOperatorClass: {
1147 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1148
1149 if (Exp->getLHS()->getType()->isArithmeticType() &&
1150 Exp->getRHS()->getType()->isArithmeticType()) {
1151 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1152 CheckArithmeticConstantExpression(Exp->getRHS());
1153 }
1154
Eli Friedman4caf0552008-06-09 05:05:07 +00001155 if (Exp->getLHS()->getType()->isPointerType() &&
1156 Exp->getRHS()->getType()->isPointerType()) {
1157 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1158 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1159
1160 // Only allow a null (constant integer) base; we could
1161 // allow some additional cases if necessary, but this
1162 // is sufficient to cover offsetof-like constructs.
1163 if (!LHSBase && !RHSBase) {
1164 return CheckAddressConstantExpression(Exp->getLHS()) ||
1165 CheckAddressConstantExpression(Exp->getRHS());
1166 }
1167 }
1168
Eli Friedmanc594b322008-05-20 13:48:25 +00001169 Diag(Init->getExprLoc(),
1170 diag::err_init_element_not_constant, Init->getSourceRange());
1171 return true;
1172 }
1173 case Expr::ImplicitCastExprClass:
1174 case Expr::CastExprClass: {
1175 const Expr *SubExpr;
1176 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1177 SubExpr = C->getSubExpr();
1178 } else {
1179 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1180 }
1181
1182 if (SubExpr->getType()->isArithmeticType())
1183 return CheckArithmeticConstantExpression(SubExpr);
1184
1185 Diag(Init->getExprLoc(),
1186 diag::err_init_element_not_constant, Init->getSourceRange());
1187 return true;
1188 }
1189 case Expr::ConditionalOperatorClass: {
1190 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1191 if (CheckArithmeticConstantExpression(Exp->getCond()))
1192 return true;
1193 if (Exp->getLHS() &&
1194 CheckArithmeticConstantExpression(Exp->getLHS()))
1195 return true;
1196 return CheckArithmeticConstantExpression(Exp->getRHS());
1197 }
1198 }
1199}
1200
1201bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001202 Init = Init->IgnoreParens();
1203
Eli Friedmanc594b322008-05-20 13:48:25 +00001204 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1205 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1206 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1207
Nuno Lopes9a979c32008-07-07 16:46:50 +00001208 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1209 return CheckForConstantInitializer(e->getInitializer(), DclT);
1210
Eli Friedmanc594b322008-05-20 13:48:25 +00001211 if (Init->getType()->isReferenceType()) {
1212 // FIXME: Work out how the heck reference types work
1213 return false;
1214#if 0
1215 // A reference is constant if the address of the expression
1216 // is constant
1217 // We look through initlists here to simplify
1218 // CheckAddressConstantExpressionLValue.
1219 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1220 assert(Exp->getNumInits() > 0 &&
1221 "Refernce initializer cannot be empty");
1222 Init = Exp->getInit(0);
1223 }
1224 return CheckAddressConstantExpressionLValue(Init);
1225#endif
1226 }
1227
1228 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1229 unsigned numInits = Exp->getNumInits();
1230 for (unsigned i = 0; i < numInits; i++) {
1231 // FIXME: Need to get the type of the declaration for C++,
1232 // because it could be a reference?
1233 if (CheckForConstantInitializer(Exp->getInit(i),
1234 Exp->getInit(i)->getType()))
1235 return true;
1236 }
1237 return false;
1238 }
1239
1240 if (Init->isNullPointerConstant(Context))
1241 return false;
1242 if (Init->getType()->isArithmeticType()) {
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001243 QualType InitTy = Init->getType().getCanonicalType().getUnqualifiedType();
1244 if (InitTy == Context.BoolTy) {
1245 // Special handling for pointers implicitly cast to bool;
1246 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1247 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1248 Expr* SubE = ICE->getSubExpr();
1249 if (SubE->getType()->isPointerType() ||
1250 SubE->getType()->isArrayType() ||
1251 SubE->getType()->isFunctionType()) {
1252 return CheckAddressConstantExpression(Init);
1253 }
1254 }
1255 } else if (InitTy->isIntegralType()) {
1256 Expr* SubE = 0;
1257 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1258 SubE = ICE->getSubExpr();
1259 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1260 SubE = CE->getSubExpr();
1261 // Special check for pointer cast to int; we allow as an extension
1262 // an address constant cast to an integer if the integer
1263 // is of an appropriate width (this sort of code is apparently used
1264 // in some places).
1265 // FIXME: Add pedwarn?
1266 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1267 if (SubE && (SubE->getType()->isPointerType() ||
1268 SubE->getType()->isArrayType() ||
1269 SubE->getType()->isFunctionType())) {
1270 unsigned IntWidth = Context.getTypeSize(Init->getType());
1271 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1272 if (IntWidth >= PointerWidth)
1273 return CheckAddressConstantExpression(Init);
1274 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001275 }
1276
1277 return CheckArithmeticConstantExpression(Init);
1278 }
1279
1280 if (Init->getType()->isPointerType())
1281 return CheckAddressConstantExpression(Init);
1282
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001283 // An array type at the top level that isn't an init-list must
1284 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001285 if (Init->getType()->isArrayType())
1286 return false;
1287
1288 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1289 Init->getSourceRange());
1290 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001291}
1292
Steve Naroffbb204692007-09-12 14:07:44 +00001293void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001294 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001295 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001296 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001297
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001298 // If there is no declaration, there was an error parsing it. Just ignore
1299 // the initializer.
1300 if (RealDecl == 0) {
1301 delete Init;
1302 return;
1303 }
Steve Naroffbb204692007-09-12 14:07:44 +00001304
Steve Naroff410e3e22007-09-12 20:13:48 +00001305 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1306 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001307 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1308 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001309 RealDecl->setInvalidDecl();
1310 return;
1311 }
Steve Naroffbb204692007-09-12 14:07:44 +00001312 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001313 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001314 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001315 if (VDecl->isBlockVarDecl()) {
1316 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001317 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001318 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001319 VDecl->setInvalidDecl();
1320 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001321 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001322 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001323 if (SC == VarDecl::Static) // C99 6.7.8p4.
1324 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001325 }
Steve Naroff248a7532008-04-15 22:42:06 +00001326 } else if (VDecl->isFileVarDecl()) {
1327 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001328 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001329 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001330 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001331 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001332
1333 // C99 6.7.8p4. All file scoped initializers need to be constant.
1334 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001335 }
1336 // If the type changed, it means we had an incomplete type that was
1337 // completed by the initializer. For example:
1338 // int ary[] = { 1, 3, 5 };
1339 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001340 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001341 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001342 Init->setType(DclT);
1343 }
Steve Naroffbb204692007-09-12 14:07:44 +00001344
1345 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001346 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001347 return;
1348}
1349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350/// The declarators are chained together backwards, reverse the list.
1351Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1352 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001353 Decl *GroupDecl = static_cast<Decl*>(group);
1354 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001355 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001356
1357 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1358 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001359 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001361 else { // reverse the list.
1362 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001363 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001364 Group->setNextDeclarator(NewGroup);
1365 NewGroup = Group;
1366 Group = Next;
1367 }
1368 }
1369 // Perform semantic analysis that depends on having fully processed both
1370 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001371 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001372 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1373 if (!IDecl)
1374 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001375 QualType T = IDecl->getType();
1376
1377 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1378 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001379 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1380 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001381 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001382 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1383 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001384 }
1385 }
1386 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1387 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001388 if (IDecl->isBlockVarDecl() &&
1389 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001390 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001391 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1392 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001393 IDecl->setInvalidDecl();
1394 }
1395 }
1396 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1397 // object that has file scope without an initializer, and without a
1398 // storage-class specifier or with the storage-class specifier "static",
1399 // constitutes a tentative definition. Note: A tentative definition with
1400 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001401 if (IDecl && !IDecl->getInit() &&
1402 (IDecl->getStorageClass() == VarDecl::Static ||
1403 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001404 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001405 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1406 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001407 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001408 // C99 6.9.2p3: If the declaration of an identifier for an object is
1409 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1410 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001411 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1412 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001413 IDecl->setInvalidDecl();
1414 }
1415 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 }
1417 return NewGroup;
1418}
Steve Naroffe1223f72007-08-28 03:03:08 +00001419
Chris Lattner04421082008-04-08 04:40:51 +00001420/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1421/// to introduce parameters into function prototype scope.
1422Sema::DeclTy *
1423Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001424 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001425
1426 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1427 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1428 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1429 Diag(DS.getStorageClassSpecLoc(),
1430 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001431 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001432 }
1433 if (DS.isThreadSpecified()) {
1434 Diag(DS.getThreadSpecLoc(),
1435 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001436 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001437 }
1438
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001439 // Check that there are no default arguments inside the type of this
1440 // parameter (C++ only).
1441 if (getLangOptions().CPlusPlus)
1442 CheckExtraCXXDefaultArguments(D);
1443
Chris Lattner04421082008-04-08 04:40:51 +00001444 // In this context, we *do not* check D.getInvalidType(). If the declarator
1445 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1446 // though it will not reflect the user specified type.
1447 QualType parmDeclType = GetTypeForDeclarator(D, S);
1448
1449 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1450
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1452 // Can this happen for params? We already checked that they don't conflict
1453 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001454 IdentifierInfo *II = D.getIdentifier();
1455 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1456 if (S->isDeclScope(PrevDecl)) {
1457 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1458 dyn_cast<NamedDecl>(PrevDecl)->getName());
1459
1460 // Recover by removing the name
1461 II = 0;
1462 D.SetIdentifier(0, D.getIdentifierLoc());
1463 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001465
1466 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1467 // Doing the promotion here has a win and a loss. The win is the type for
1468 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1469 // code generator). The loss is the orginal type isn't preserved. For example:
1470 //
1471 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1472 // int blockvardecl[5];
1473 // sizeof(parmvardecl); // size == 4
1474 // sizeof(blockvardecl); // size == 20
1475 // }
1476 //
1477 // For expressions, all implicit conversions are captured using the
1478 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1479 //
1480 // FIXME: If a source translation tool needs to see the original type, then
1481 // we need to consider storing both types (in ParmVarDecl)...
1482 //
Chris Lattnere6327742008-04-02 05:18:44 +00001483 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001484 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001485 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001486 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001487 parmDeclType = Context.getPointerType(parmDeclType);
1488
Chris Lattner04421082008-04-08 04:40:51 +00001489 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1490 D.getIdentifierLoc(), II,
1491 parmDeclType, VarDecl::None,
1492 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001493
Chris Lattner04421082008-04-08 04:40:51 +00001494 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001495 New->setInvalidDecl();
1496
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001497 if (II)
1498 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001499
Chris Lattner3ff30c82008-06-29 00:02:00 +00001500 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001502
Reid Spencer5f016e22007-07-11 17:01:13 +00001503}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001504
Chris Lattnerb652cea2007-10-09 17:14:05 +00001505Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001506 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001507 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1508 "Not a function declarator!");
1509 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001510
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1512 // for a K&R function.
1513 if (!FTI.hasPrototype) {
1514 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001515 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1517 FTI.ArgInfo[i].Ident->getName());
1518 // Implicitly declare the argument as type 'int' for lack of a better
1519 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001520 DeclSpec DS;
1521 const char* PrevSpec; // unused
1522 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1523 PrevSpec);
1524 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1525 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1526 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 }
1528 }
Chris Lattner52804082008-02-17 19:31:09 +00001529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // Since this is a function definition, act as though we have information
1531 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001532 if (FTI.NumArgs)
1533 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001535 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 }
1537
1538 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001539
1540 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001541 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001542 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001543 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1544 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1545 const FunctionDecl *Definition;
1546 if (FD->getBody(Definition)) {
1547 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1548 D.getIdentifier()->getName());
1549 Diag(Definition->getLocation(), diag::err_previous_definition);
1550 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001551 }
1552 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001553
1554 return ActOnStartOfFunctionDef(FnBodyScope,
1555 ActOnDeclarator(GlobalScope, D, 0));
1556}
1557
1558Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1559 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001560 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001561 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001562
1563 // Check the validity of our function parameters
1564 CheckParmsForFunctionDef(FD);
1565
1566 // Introduce our parameters into the function scope
1567 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1568 ParmVarDecl *Param = FD->getParamDecl(p);
1569 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001570 if (Param->getIdentifier())
1571 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
Chris Lattner04421082008-04-08 04:40:51 +00001573
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 return FD;
1575}
1576
Steve Naroffd6d054d2007-11-11 23:20:51 +00001577Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1578 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001579 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001580 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001581 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001582 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001583 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001584 } else
1585 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001586 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Verify and clean out per-function state.
1588
1589 // Check goto/label use.
1590 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1591 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1592 // Verify that we have no forward references left. If so, there was a goto
1593 // or address of a label taken, but no definition of it. Label fwd
1594 // definitions are indicated with a null substmt.
1595 if (I->second->getSubStmt() == 0) {
1596 LabelStmt *L = I->second;
1597 // Emit error.
1598 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1599
1600 // At this point, we have gotos that use the bogus label. Stitch it into
1601 // the function body so that they aren't leaked and that the AST is well
1602 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001603 if (Body) {
1604 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1605 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1606 } else {
1607 // The whole function wasn't parsed correctly, just delete this.
1608 delete L;
1609 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 }
1611 }
1612 LabelMap.clear();
1613
Steve Naroffd6d054d2007-11-11 23:20:51 +00001614 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001615}
1616
Reid Spencer5f016e22007-07-11 17:01:13 +00001617/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1618/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001619ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1620 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001621 // Extension in C99. Legal in C90, but warn about it.
1622 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001624 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1626
1627 // FIXME: handle stuff like:
1628 // void foo() { extern float X(); }
1629 // void bar() { X(); } <-- implicit decl for X in another scope.
1630
1631 // Set a Declarator for the implicit definition: int foo();
1632 const char *Dummy;
1633 DeclSpec DS;
1634 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1635 Error = Error; // Silence warning.
1636 assert(!Error && "Error setting up implicit decl!");
1637 Declarator D(DS, Declarator::BlockContext);
1638 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1639 D.SetIdentifier(&II, Loc);
1640
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001641 // Insert this function into translation-unit scope.
1642
1643 DeclContext *PrevDC = CurContext;
1644 CurContext = Context.getTranslationUnitDecl();
1645
Steve Naroffe2ef8152008-04-04 14:32:09 +00001646 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001647 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001648 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001649
1650 CurContext = PrevDC;
1651
Steve Naroffe2ef8152008-04-04 14:32:09 +00001652 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001653}
1654
1655
Chris Lattner41af0932007-11-14 06:34:38 +00001656TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001657 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001659 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001660
1661 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001662 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1663 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001664 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001665 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001666 if (D.getInvalidType())
1667 NewTD->setInvalidDecl();
1668 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001669}
1670
Steve Naroff08d92e42007-09-15 18:49:24 +00001671/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001672/// former case, Name will be non-null. In the later case, Name will be null.
1673/// TagType indicates what kind of tag this is. TK indicates whether this is a
1674/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001675Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 SourceLocation KWLoc, IdentifierInfo *Name,
1677 SourceLocation NameLoc, AttributeList *Attr) {
1678 // If this is a use of an existing tag, it must have a name.
1679 assert((Name != 0 || TK == TK_Definition) &&
1680 "Nameless record must be a definition!");
1681
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001682 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 switch (TagType) {
1684 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001685 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1686 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1687 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1688 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 }
1690
1691 // If this is a named struct, check to see if there was a previous forward
1692 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001693 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1694 if (ScopedDecl *PrevDecl =
1695 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001696
Argyrios Kyrtzidis2d1c5d32008-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 Lattner14943b92008-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
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001702 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001703 if (TK == TK_Reference ||
1704 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-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.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001707 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-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 Lattner14943b92008-07-03 03:30:58 +00001710 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001711 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001712 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001713 } else {
Chris Lattner14943b92008-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 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001732 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 }
Argyrios Kyrtzidis2d1c5d32008-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 {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001738 // PrevDecl is a namespace.
1739 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1740 // The tag name clashes with a namespace name, issue an error and recover
1741 // by making this tag be anonymous.
1742 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1743 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1744 Name = 0;
1745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 }
Reid Spencer5f016e22007-07-11 17:01:13 +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;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001756 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner0ed844b2008-04-04 06:12:32 +00001759 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 // If this is an undefined enum, warn.
1761 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001762 } else {
1763 // struct/union/class
1764
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1766 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001767 if (getLangOptions().CPlusPlus)
1768 // FIXME: Look for a way to use RecordDecl for simple structs.
1769 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1770 else
1771 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1772 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001773
1774 // If this has an identifier, add it to the scope stack.
1775 if (Name) {
Chris Lattner31e05722007-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.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001782 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001784
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001785 if (Attr)
1786 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001787 return New;
1788}
1789
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001790/// Collect the instance variables declared in an Objective-C object. Used in
1791/// the creation of structures from objects using the @defs directive.
1792static void CollectIvars(ObjCInterfaceDecl *Class,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001793 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001794 if (Class->getSuperClass())
1795 CollectIvars(Class->getSuperClass(), ivars);
1796 ivars.append(Class->ivar_begin(), Class->ivar_end());
1797}
1798
1799/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1800/// instance variables of ClassName into Decls.
1801void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1802 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001803 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001804 // Check that ClassName is a valid class
1805 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1806 if (!Class) {
1807 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1808 return;
1809 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001810 // Collect the instance variables
1811 CollectIvars(Class, Decls);
1812}
1813
Eli Friedman1b76ada2008-06-03 21:01:11 +00001814QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1815 // This method tries to turn a variable array into a constant
1816 // array even when the size isn't an ICE. This is necessary
1817 // for compatibility with code that depends on gcc's buggy
1818 // constant expression folding, like struct {char x[(int)(char*)2];}
1819 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001820 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001821 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001822 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1823 llvm::APSInt &Res = Result.getInt();
1824 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1825 return Context.getConstantArrayType(VLATy->getElementType(),
1826 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001827 }
1828 }
1829 return QualType();
1830}
1831
Steve Naroff08d92e42007-09-15 18:49:24 +00001832/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001833/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001834Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 SourceLocation DeclStart,
1836 Declarator &D, ExprTy *BitfieldWidth) {
1837 IdentifierInfo *II = D.getIdentifier();
1838 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 SourceLocation Loc = DeclStart;
1840 if (II) Loc = D.getIdentifierLoc();
1841
1842 // FIXME: Unnamed fields can be handled in various different ways, for
1843 // example, unnamed unions inject all members into the struct namespace!
1844
1845
1846 if (BitWidth) {
1847 // TODO: Validate.
1848 //printf("WARNING: BITFIELDS IGNORED!\n");
1849
1850 // 6.7.2.1p3
1851 // 6.7.2.1p4
1852
1853 } else {
1854 // Not a bitfield.
1855
1856 // validate II.
1857
1858 }
1859
1860 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001861 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1862 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001863
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1865 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001866 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001867 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1868 if (!FixedTy.isNull()) {
1869 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1870 T = FixedTy;
1871 } else {
1872 // FIXME: This diagnostic needs work
1873 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1874 InvalidDecl = true;
1875 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001877 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001878 FieldDecl *NewFD;
1879
1880 if (getLangOptions().CPlusPlus) {
1881 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1882 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1883 Loc, II, T, BitWidth);
1884 if (II)
1885 PushOnScopeChains(NewFD, S);
1886 }
1887 else
1888 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001889
Chris Lattner3ff30c82008-06-29 00:02:00 +00001890 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00001891
Steve Naroff5912a352007-08-28 20:14:24 +00001892 if (D.getInvalidType() || InvalidDecl)
1893 NewFD->setInvalidDecl();
1894 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001895}
1896
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001897/// TranslateIvarVisibility - Translate visibility from a token ID to an
1898/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001899static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001900TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001901 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001902 case tok::objc_private: return ObjCIvarDecl::Private;
1903 case tok::objc_public: return ObjCIvarDecl::Public;
1904 case tok::objc_protected: return ObjCIvarDecl::Protected;
1905 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001906 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001907 }
1908}
1909
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001910/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1911/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001912Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001913 SourceLocation DeclStart,
1914 Declarator &D, ExprTy *BitfieldWidth,
1915 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001916 IdentifierInfo *II = D.getIdentifier();
1917 Expr *BitWidth = (Expr*)BitfieldWidth;
1918 SourceLocation Loc = DeclStart;
1919 if (II) Loc = D.getIdentifierLoc();
1920
1921 // FIXME: Unnamed fields can be handled in various different ways, for
1922 // example, unnamed unions inject all members into the struct namespace!
1923
1924
1925 if (BitWidth) {
1926 // TODO: Validate.
1927 //printf("WARNING: BITFIELDS IGNORED!\n");
1928
1929 // 6.7.2.1p3
1930 // 6.7.2.1p4
1931
1932 } else {
1933 // Not a bitfield.
1934
1935 // validate II.
1936
1937 }
1938
1939 QualType T = GetTypeForDeclarator(D, S);
1940 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1941 bool InvalidDecl = false;
1942
1943 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1944 // than a variably modified type.
1945 if (T->isVariablyModifiedType()) {
1946 // FIXME: This diagnostic needs work
1947 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1948 InvalidDecl = true;
1949 }
1950
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001951 // Get the visibility (access control) for this ivar.
1952 ObjCIvarDecl::AccessControl ac =
1953 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1954 : ObjCIvarDecl::None;
1955
1956 // Construct the decl.
1957 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00001958 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001959
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001960 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001961 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001962
1963 if (D.getInvalidType() || InvalidDecl)
1964 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001965
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001966 return NewID;
1967}
1968
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001969void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001970 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001971 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001972 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001973 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1974 assert(EnclosingDecl && "missing record or interface decl");
1975 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1976
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001977 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Diagnose code like:
1979 // struct S { struct S {} X; };
1980 // We discover this when we complete the outer S. Reject and ignore the
1981 // outer S.
1982 Diag(Record->getLocation(), diag::err_nested_redefinition,
1983 Record->getKindName());
1984 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001985 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 return;
1987 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 // Verify that all the fields are okay.
1989 unsigned NumNamedMembers = 0;
1990 llvm::SmallVector<FieldDecl*, 32> RecFields;
1991 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001994
Steve Naroff74216642007-09-14 22:20:54 +00001995 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1996 assert(FD && "missing field decl");
1997
1998 // Remember all fields.
1999 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002000
2001 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002002 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002003
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002005 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002006 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002008 FD->setInvalidDecl();
2009 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 continue;
2011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2013 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002014 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002015 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002016 FD->setInvalidDecl();
2017 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002018 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002019 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002020 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002021 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002022 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002023 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002024 FD->setInvalidDecl();
2025 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 continue;
2027 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002028 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2030 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002031 FD->setInvalidDecl();
2032 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 continue;
2034 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002036 if (Record)
2037 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2040 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002041 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2043 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002044 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 Record->setHasFlexibleArrayMember(true);
2046 } else {
2047 // If this is a struct/class and this is not the last element, reject
2048 // it. Note that GCC supports variable sized arrays in the middle of
2049 // structures.
2050 if (i != NumFields-1) {
2051 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2052 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002053 FD->setInvalidDecl();
2054 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 continue;
2056 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 // We support flexible arrays at the end of structs in other structs
2058 // as an extension.
2059 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2060 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002061 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002062 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 }
2064 }
2065 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002066 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002068 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2069 FD->getName());
2070 FD->setInvalidDecl();
2071 EnclosingDecl->setInvalidDecl();
2072 continue;
2073 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002074 // Keep track of the number of named members.
2075 if (IdentifierInfo *II = FD->getIdentifier()) {
2076 // Detect duplicate member names.
2077 if (!FieldIDs.insert(II)) {
2078 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2079 // Find the previous decl.
2080 SourceLocation PrevLoc;
2081 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2082 assert(i != e && "Didn't find previous def!");
2083 if (RecFields[i]->getIdentifier() == II) {
2084 PrevLoc = RecFields[i]->getLocation();
2085 break;
2086 }
2087 }
2088 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002089 FD->setInvalidDecl();
2090 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 continue;
2092 }
2093 ++NumNamedMembers;
2094 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 }
2096
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002098 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002099 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002100 Consumer.HandleTagDeclDefinition(Record);
2101 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002102 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2103 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2104 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2105 else if (ObjCImplementationDecl *IMPDecl =
2106 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002107 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2108 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002109 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002110 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002111 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002112}
2113
Steve Naroff08d92e42007-09-15 18:49:24 +00002114Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 DeclTy *lastEnumConst,
2116 SourceLocation IdLoc, IdentifierInfo *Id,
2117 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002118 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 EnumConstantDecl *LastEnumConst =
2120 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2121 Expr *Val = static_cast<Expr*>(val);
2122
Chris Lattner31e05722007-08-26 06:24:45 +00002123 // The scope passed in may not be a decl scope. Zip up the scope tree until
2124 // we find one that is.
2125 while ((S->getFlags() & Scope::DeclScope) == 0)
2126 S = S->getParent();
2127
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // Verify that there isn't already something declared with this name in this
2129 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002130 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002131 // When in C++, we may get a TagDecl with the same name; in this case the
2132 // enum constant will 'hide' the tag.
2133 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2134 "Received TagDecl when not in C++!");
2135 if (!isa<TagDecl>(PrevDecl) &&
2136 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002137 if (isa<EnumConstantDecl>(PrevDecl))
2138 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2139 else
2140 Diag(IdLoc, diag::err_redefinition, Id->getName());
2141 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002142 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 return 0;
2144 }
2145 }
2146
2147 llvm::APSInt EnumVal(32);
2148 QualType EltTy;
2149 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002150 // Make sure to promote the operand type to int.
2151 UsualUnaryConversions(Val);
2152
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2154 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002155 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002156 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2157 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002158 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002159 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002160 } else {
2161 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002162 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002163 }
2164
2165 if (!Val) {
2166 if (LastEnumConst) {
2167 // Assign the last value + 1.
2168 EnumVal = LastEnumConst->getInitVal();
2169 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002170
2171 // Check for overflow on increment.
2172 if (EnumVal < LastEnumConst->getInitVal())
2173 Diag(IdLoc, diag::warn_enum_value_overflow);
2174
Chris Lattnerb7416f92007-08-27 17:37:24 +00002175 EltTy = LastEnumConst->getType();
2176 } else {
2177 // First value, set to zero.
2178 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002179 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002180 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002181 }
2182
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002183 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002184 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2185 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002186 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002187
2188 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002189 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002190 return New;
2191}
2192
Steve Naroff08d92e42007-09-15 18:49:24 +00002193void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002194 DeclTy **Elements, unsigned NumElements) {
2195 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2196 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2197
Chris Lattnere37f0be2007-08-28 05:10:31 +00002198 // TODO: If the result value doesn't fit in an int, it must be a long or long
2199 // long value. ISO C does not support this, but GCC does as an extension,
2200 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002201 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002202
Chris Lattnerac609682007-08-28 06:15:15 +00002203 // Verify that all the values are okay, compute the size of the values, and
2204 // reverse the list.
2205 unsigned NumNegativeBits = 0;
2206 unsigned NumPositiveBits = 0;
2207
2208 // Keep track of whether all elements have type int.
2209 bool AllElementsInt = true;
2210
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 EnumConstantDecl *EltList = 0;
2212 for (unsigned i = 0; i != NumElements; ++i) {
2213 EnumConstantDecl *ECD =
2214 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2215 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002216
2217 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002218 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002219 assert(InitVal.getBitWidth() >= IntWidth &&
2220 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002221 if (InitVal.getBitWidth() > IntWidth) {
2222 llvm::APSInt V(InitVal);
2223 V.trunc(IntWidth);
2224 V.extend(InitVal.getBitWidth());
2225 if (V != InitVal)
2226 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2227 InitVal.toString());
2228 }
Chris Lattnerac609682007-08-28 06:15:15 +00002229
2230 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002231 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002232 NumPositiveBits = std::max(NumPositiveBits,
2233 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002234 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002235 NumNegativeBits = std::max(NumNegativeBits,
2236 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002237
Chris Lattnerac609682007-08-28 06:15:15 +00002238 // Keep track of whether every enum element has type int (very commmon).
2239 if (AllElementsInt)
2240 AllElementsInt = ECD->getType() == Context.IntTy;
2241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 ECD->setNextDeclarator(EltList);
2243 EltList = ECD;
2244 }
2245
Chris Lattnerac609682007-08-28 06:15:15 +00002246 // Figure out the type that should be used for this enum.
2247 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2248 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002249 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002250
2251 if (NumNegativeBits) {
2252 // If there is a negative value, figure out the smallest integer type (of
2253 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002254 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002255 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002256 BestWidth = IntWidth;
2257 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002258 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002259
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002260 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002261 BestType = Context.LongTy;
2262 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002263 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002264
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002265 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002266 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2267 BestType = Context.LongLongTy;
2268 }
2269 }
2270 } else {
2271 // If there is no negative value, figure out which of uint, ulong, ulonglong
2272 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002273 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002274 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002275 BestWidth = IntWidth;
2276 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002277 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002278 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002279 } else {
2280 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002281 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002282 "How could an initializer get larger than ULL?");
2283 BestType = Context.UnsignedLongLongTy;
2284 }
2285 }
2286
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002287 // Loop over all of the enumerator constants, changing their types to match
2288 // the type of the enum if needed.
2289 for (unsigned i = 0; i != NumElements; ++i) {
2290 EnumConstantDecl *ECD =
2291 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2292 if (!ECD) continue; // Already issued a diagnostic.
2293
2294 // Standard C says the enumerators have int type, but we allow, as an
2295 // extension, the enumerators to be larger than int size. If each
2296 // enumerator value fits in an int, type it as an int, otherwise type it the
2297 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2298 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002299 if (ECD->getType() == Context.IntTy) {
2300 // Make sure the init value is signed.
2301 llvm::APSInt IV = ECD->getInitVal();
2302 IV.setIsSigned(true);
2303 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002304 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002305 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002306
2307 // Determine whether the value fits into an int.
2308 llvm::APSInt InitVal = ECD->getInitVal();
2309 bool FitsInInt;
2310 if (InitVal.isUnsigned() || !InitVal.isNegative())
2311 FitsInInt = InitVal.getActiveBits() < IntWidth;
2312 else
2313 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2314
2315 // If it fits into an integer type, force it. Otherwise force it to match
2316 // the enum decl type.
2317 QualType NewTy;
2318 unsigned NewWidth;
2319 bool NewSign;
2320 if (FitsInInt) {
2321 NewTy = Context.IntTy;
2322 NewWidth = IntWidth;
2323 NewSign = true;
2324 } else if (ECD->getType() == BestType) {
2325 // Already the right type!
2326 continue;
2327 } else {
2328 NewTy = BestType;
2329 NewWidth = BestWidth;
2330 NewSign = BestType->isSignedIntegerType();
2331 }
2332
2333 // Adjust the APSInt value.
2334 InitVal.extOrTrunc(NewWidth);
2335 InitVal.setIsSigned(NewSign);
2336 ECD->setInitVal(InitVal);
2337
2338 // Adjust the Expr initializer and type.
2339 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2340 ECD->setType(NewTy);
2341 }
Chris Lattnerac609682007-08-28 06:15:15 +00002342
Chris Lattnere00b18c2007-08-28 18:24:31 +00002343 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002344 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002345}
2346
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002347Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2348 ExprTy *expr) {
2349 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2350
Chris Lattner8e25d862008-03-16 00:16:02 +00002351 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002352}
2353
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002354Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002355 SourceLocation LBrace,
2356 SourceLocation RBrace,
2357 const char *Lang,
2358 unsigned StrSize,
2359 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002360 LinkageSpecDecl::LanguageIDs Language;
2361 Decl *dcl = static_cast<Decl *>(D);
2362 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2363 Language = LinkageSpecDecl::lang_c;
2364 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2365 Language = LinkageSpecDecl::lang_cxx;
2366 else {
2367 Diag(Loc, diag::err_bad_language);
2368 return 0;
2369 }
2370
2371 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002372 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002373}