blob: b513dde4661948c2f5527b7868c97e26a7b77b51 [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
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000038Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000039 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
Chris Lattner99cb9972008-07-25 18:44:27 +0000251 // If the typedef types are not identical, reject them in all languages and
252 // with any extensions enabled.
253 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
254 Context.getCanonicalType(Old->getUnderlyingType()) !=
255 Context.getCanonicalType(New->getUnderlyingType())) {
256 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
257 New->getUnderlyingType().getAsString(),
258 Old->getUnderlyingType().getAsString());
259 Diag(Old->getLocation(), diag::err_previous_definition);
260 return Old;
261 }
262
Steve Naroff8ee529b2007-10-31 18:42:27 +0000263 // Allow multiple definitions for ObjC built-in typedefs.
264 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000266 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000267
268 if (getLangOptions().Microsoft) return New;
269
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000270 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
271 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
272 // *either* declaration is in a system header. The code below implements
273 // this adhoc compatibility rule. FIXME: The following code will not
274 // work properly when compiling ".i" files (containing preprocessed output).
275 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000276 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000277 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
278 if (OldDeclFile) {
279 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
280 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
281 if (OldDirType != DirectoryLookup::NormalHeaderDir)
282 return New;
283 }
284 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
285 if (NewDeclFile) {
286 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
287 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
288 if (NewDirType != DirectoryLookup::NormalHeaderDir)
289 return New;
290 }
291
Ted Kremenek2d05c082008-05-23 21:28:18 +0000292 Diag(New->getLocation(), diag::err_redefinition, New->getName());
293 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 return New;
295}
296
Chris Lattner6b6b5372008-06-26 18:38:35 +0000297/// DeclhasAttr - returns true if decl Declaration already has the target
298/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000299static bool DeclHasAttr(const Decl *decl, const Attr *target) {
300 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
301 if (attr->getKind() == target->getKind())
302 return true;
303
304 return false;
305}
306
307/// MergeAttributes - append attributes from the Old decl to the New one.
308static void MergeAttributes(Decl *New, Decl *Old) {
309 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
310
Chris Lattnerddee4232008-03-03 03:28:21 +0000311 while (attr) {
312 tmp = attr;
313 attr = attr->getNext();
314
315 if (!DeclHasAttr(New, tmp)) {
316 New->addAttr(tmp);
317 } else {
318 tmp->setNext(0);
319 delete(tmp);
320 }
321 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000322
323 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000324}
325
Chris Lattner04421082008-04-08 04:40:51 +0000326/// MergeFunctionDecl - We just parsed a function 'New' from
327/// declarator D which has the same name and scope as a previous
328/// declaration 'Old'. Figure out how to resolve this situation,
329/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000330/// Redeclaration will be set true if thisNew is a redeclaration OldD.
331FunctionDecl *
332Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
333 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 // Verify the old decl was also a function.
335 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
336 if (!Old) {
337 Diag(New->getLocation(), diag::err_redefinition_different_kind,
338 New->getName());
339 Diag(OldD->getLocation(), diag::err_previous_definition);
340 return New;
341 }
Chris Lattner04421082008-04-08 04:40:51 +0000342
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000343 QualType OldQType = Context.getCanonicalType(Old->getType());
344 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000345
Chris Lattner04421082008-04-08 04:40:51 +0000346 // C++ [dcl.fct]p3:
347 // All declarations for a function shall agree exactly in both the
348 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000349 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
350 MergeAttributes(New, Old);
351 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000352 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000353 }
Chris Lattner04421082008-04-08 04:40:51 +0000354
355 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000356 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000357 if (!getLangOptions().CPlusPlus &&
358 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000359 MergeAttributes(New, Old);
360 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000361 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000362 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000363
Steve Naroff837618c2008-01-16 15:01:34 +0000364 // A function that has already been declared has been redeclared or defined
365 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000366 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000367 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000368 PrevDiag = diag::err_previous_definition;
369 else if (Old->isImplicit())
370 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000371 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000372 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000373
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
375 // TODO: This is totally simplistic. It should handle merging functions
376 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000377 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
378 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000379 return New;
380}
381
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000382/// equivalentArrayTypes - Used to determine whether two array types are
383/// equivalent.
384/// We need to check this explicitly as an incomplete array definition is
385/// considered a VariableArrayType, so will not match a complete array
386/// definition that would be otherwise equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000387static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType,
388 ASTContext &Context) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000389 const ArrayType *NewAT = Context.getAsArrayType(NewQType);
390 const ArrayType *OldAT = Context.getAsArrayType(OldQType);
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000391
392 if (!NewAT || !OldAT)
393 return false;
394
395 // If either (or both) array types in incomplete we need to strip off the
396 // outer VariableArrayType. Once the outer VAT is removed the remaining
397 // types must be identical if the array types are to be considered
398 // equivalent.
399 // eg. int[][1] and int[1][1] become
400 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
401 // removing the outermost VAT gives
402 // CAT(1, int) and CAT(1, int)
403 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000404 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000405 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
406 return false;
Chris Lattnerb77792e2008-07-26 22:17:49 +0000407 NewQType = Context.getCanonicalType(NewAT->getElementType());
408 OldQType = Context.getCanonicalType(OldAT->getElementType());
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000409 }
410
411 return NewQType == OldQType;
412}
413
Reid Spencer5f016e22007-07-11 17:01:13 +0000414/// MergeVarDecl - We just parsed a variable 'New' which has the same name
415/// and scope as a previous declaration 'Old'. Figure out how to resolve this
416/// situation, merging decls or emitting diagnostics as appropriate.
417///
418/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
419/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
420///
Steve Naroffe8043c32008-04-01 23:04:06 +0000421VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000422 // Verify the old decl was also a variable.
423 VarDecl *Old = dyn_cast<VarDecl>(OldD);
424 if (!Old) {
425 Diag(New->getLocation(), diag::err_redefinition_different_kind,
426 New->getName());
427 Diag(OldD->getLocation(), diag::err_previous_definition);
428 return New;
429 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000430
431 MergeAttributes(New, Old);
432
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000434 QualType OldCType = Context.getCanonicalType(Old->getType());
435 QualType NewCType = Context.getCanonicalType(New->getType());
Chris Lattnerb77792e2008-07-26 22:17:49 +0000436 if (OldCType != NewCType &&
437 !areEquivalentArrayTypes(NewCType, OldCType, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 Diag(New->getLocation(), diag::err_redefinition, New->getName());
439 Diag(Old->getLocation(), diag::err_previous_definition);
440 return New;
441 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000442 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
443 if (New->getStorageClass() == VarDecl::Static &&
444 (Old->getStorageClass() == VarDecl::None ||
445 Old->getStorageClass() == VarDecl::Extern)) {
446 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
447 Diag(Old->getLocation(), diag::err_previous_definition);
448 return New;
449 }
450 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
451 if (New->getStorageClass() != VarDecl::Static &&
452 Old->getStorageClass() == VarDecl::Static) {
453 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
454 Diag(Old->getLocation(), diag::err_previous_definition);
455 return New;
456 }
457 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000458 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000459 // Handle C "tentative" external object definitions (C99 6.9.2).
460 bool OldIsTentative = false;
461 bool NewIsTentative = false;
462
Steve Naroff248a7532008-04-15 22:42:06 +0000463 if (!Old->getInit() &&
464 (Old->getStorageClass() == VarDecl::None ||
465 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000466 OldIsTentative = true;
467
468 // FIXME: this check doesn't work (since the initializer hasn't been
469 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
470 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
471 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000472 if (!New->getInit() &&
473 (New->getStorageClass() == VarDecl::None ||
474 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000475 ; // change to NewIsTentative = true; once the code is moved.
476
477 if (NewIsTentative || OldIsTentative)
478 return New;
479 }
Steve Naroff235549c2008-05-12 22:36:43 +0000480 // Handle __private_extern__ just like extern.
Steve Naroffb7b032e2008-01-30 00:44:01 +0000481 if (Old->getStorageClass() != VarDecl::Extern &&
Steve Naroff235549c2008-05-12 22:36:43 +0000482 Old->getStorageClass() != VarDecl::PrivateExtern &&
483 New->getStorageClass() != VarDecl::Extern &&
484 New->getStorageClass() != VarDecl::PrivateExtern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 Diag(New->getLocation(), diag::err_redefinition, New->getName());
486 Diag(Old->getLocation(), diag::err_previous_definition);
487 }
488 return New;
489}
490
Chris Lattner04421082008-04-08 04:40:51 +0000491/// CheckParmsForFunctionDef - Check that the parameters of the given
492/// function are appropriate for the definition of a function. This
493/// takes care of any checks that cannot be performed on the
494/// declaration itself, e.g., that the types of each of the function
495/// parameters are complete.
496bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
497 bool HasInvalidParm = false;
498 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
499 ParmVarDecl *Param = FD->getParamDecl(p);
500
501 // C99 6.7.5.3p4: the parameters in a parameter type list in a
502 // function declarator that is part of a function definition of
503 // that function shall not have incomplete type.
504 if (Param->getType()->isIncompleteType() &&
505 !Param->isInvalidDecl()) {
506 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
507 Param->getType().getAsString());
508 Param->setInvalidDecl();
509 HasInvalidParm = true;
510 }
511 }
512
513 return HasInvalidParm;
514}
515
516/// CreateImplicitParameter - Creates an implicit function parameter
517/// in the scope S and with the given type. This routine is used, for
518/// example, to create the implicit "self" parameter in an Objective-C
519/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000520ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000521Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
522 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000523 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
524 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000525 if (Id)
526 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000527
528 return New;
529}
530
Reid Spencer5f016e22007-07-11 17:01:13 +0000531/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
532/// no declarator (e.g. "struct foo;") is parsed.
533Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
534 // TODO: emit error on 'int;' or 'const enum foo;'.
535 // TODO: emit error on 'typedef int;'
536 // if (!DS.isMissingDeclaratorOk()) Diag(...);
537
Steve Naroff92199282007-11-17 21:37:36 +0000538 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000539}
540
Steve Naroffd0091aa2008-01-10 22:15:12 +0000541bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000542 // Get the type before calling CheckSingleAssignmentConstraints(), since
543 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000544 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000545
Chris Lattner5cf216b2008-01-04 18:04:52 +0000546 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
547 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
548 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000549}
550
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000551bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000552 const ArrayType *AT = Context.getAsArrayType(DeclT);
553
554 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000555 // C99 6.7.8p14. We have an array of character type with unknown size
556 // being initialized to a string literal.
557 llvm::APSInt ConstVal(32);
558 ConstVal = strLiteral->getByteLength() + 1;
559 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000560 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000561 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000562 } else {
563 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000564 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000565 // FIXME: Avoid truncation for 64-bit length strings.
566 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000567 Diag(strLiteral->getSourceRange().getBegin(),
568 diag::warn_initializer_string_for_char_array_too_long,
569 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000570 }
571 // Set type from "char *" to "constant array of char".
572 strLiteral->setType(DeclT);
573 // For now, we always return false (meaning success).
574 return false;
575}
576
577StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000578 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000579 if (AT && AT->getElementType()->isCharType()) {
580 return dyn_cast<StringLiteral>(Init);
581 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000582 return 0;
583}
584
Steve Naroffa9960332008-01-25 00:51:06 +0000585bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000586 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
587 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000588 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000589 return Diag(VAT->getSizeExpr()->getLocStart(),
590 diag::err_variable_object_no_init,
591 VAT->getSizeExpr()->getSourceRange());
592
Steve Naroff2fdc3742007-12-10 22:44:33 +0000593 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
594 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000595 // FIXME: Handle wide strings
596 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
597 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000598
599 if (DeclType->isArrayType())
600 return Diag(Init->getLocStart(),
601 diag::err_array_init_list_required,
602 Init->getSourceRange());
603
Steve Naroffd0091aa2008-01-10 22:15:12 +0000604 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000605 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000606
Steve Naroff0cca7492008-05-01 22:18:59 +0000607 InitListChecker CheckInitList(this, InitList, DeclType);
608 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000609}
610
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000611Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000612Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000613 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 IdentifierInfo *II = D.getIdentifier();
615
Chris Lattnere80a59c2007-07-25 00:24:17 +0000616 // All of these full declarators require an identifier. If it doesn't have
617 // one, the ParsedFreeStandingDeclSpec action should be used.
618 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000619 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000620 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000621 D.getDeclSpec().getSourceRange(), D.getSourceRange());
622 return 0;
623 }
624
Chris Lattner31e05722007-08-26 06:24:45 +0000625 // The scope passed in may not be a decl scope. Zip up the scope tree until
626 // we find one that is.
627 while ((S->getFlags() & Scope::DeclScope) == 0)
628 S = S->getParent();
629
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000631 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000632 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000633 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000634
635 // In C++, the previous declaration we find might be a tag type
636 // (class or enum). In this case, the new declaration will hide the
637 // tag type.
638 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
639 PrevDecl = 0;
640
Chris Lattner41af0932007-11-14 06:34:38 +0000641 QualType R = GetTypeForDeclarator(D, S);
642 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
643
Reid Spencer5f016e22007-07-11 17:01:13 +0000644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000645 // Check that there are no default arguments (C++ only).
646 if (getLangOptions().CPlusPlus)
647 CheckExtraCXXDefaultArguments(D);
648
Chris Lattner41af0932007-11-14 06:34:38 +0000649 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 if (!NewTD) return 0;
651
652 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000653 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000654 // Merge the decl with the existing one if appropriate. If the decl is
655 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000656 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000657 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
658 if (NewTD == 0) return 0;
659 }
660 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000661 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000662 // C99 6.7.7p2: If a typedef name specifies a variably modified type
663 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000664 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
665 // FIXME: Diagnostic needs to be fixed.
666 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000667 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 }
669 }
Chris Lattner41af0932007-11-14 06:34:38 +0000670 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000671 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 switch (D.getDeclSpec().getStorageClassSpec()) {
673 default: assert(0 && "Unknown storage class!");
674 case DeclSpec::SCS_auto:
675 case DeclSpec::SCS_register:
676 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
677 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000678 InvalidDecl = true;
679 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000680 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
681 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
682 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000683 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 }
685
Chris Lattnera98e58d2008-03-15 21:24:04 +0000686 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000687 FunctionDecl *NewFD;
688 if (D.getContext() == Declarator::MemberContext) {
689 // This is a C++ method declaration.
690 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
691 D.getIdentifierLoc(), II, R,
692 (SC == FunctionDecl::Static), isInline,
693 LastDeclarator);
694 } else {
695 NewFD = FunctionDecl::Create(Context, CurContext,
696 D.getIdentifierLoc(),
697 II, R, SC, isInline,
698 LastDeclarator);
699 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000700 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000701 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000702
Daniel Dunbara80f8742008-08-05 01:35:17 +0000703 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000704 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000705 // The parser guarantees this is a string.
706 StringLiteral *SE = cast<StringLiteral>(E);
707 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
708 SE->getByteLength())));
709 }
710
Chris Lattner04421082008-04-08 04:40:51 +0000711 // Copy the parameter declarations from the declarator D to
712 // the function declaration NewFD, if they are available.
713 if (D.getNumTypeObjects() > 0 &&
714 D.getTypeObject(0).Fun.hasPrototype) {
715 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
716
717 // Create Decl objects for each parameter, adding them to the
718 // FunctionDecl.
719 llvm::SmallVector<ParmVarDecl*, 16> Params;
720
721 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
722 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000723 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000724 // We let through "const void" here because Sema::GetTypeForDeclarator
725 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000726 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
727 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000728 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
729 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000730 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
731
Chris Lattnerdef026a2008-04-10 02:26:16 +0000732 // In C++, the empty parameter-type-list must be spelled "void"; a
733 // typedef of void is not permitted.
734 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000735 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000736 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
737 }
738
Chris Lattner04421082008-04-08 04:40:51 +0000739 } else {
740 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
741 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
742 }
743
744 NewFD->setParams(&Params[0], Params.size());
745 }
746
Steve Naroffffce4d52008-01-09 23:34:55 +0000747 // Merge the decl with the existing one if appropriate. Since C functions
748 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000749 if (PrevDecl &&
750 (!getLangOptions().CPlusPlus ||
751 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000752 bool Redeclaration = false;
753 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000755 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000756 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000757 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 }
759 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000760
761 // In C++, check default arguments now that we have merged decls.
762 if (getLangOptions().CPlusPlus)
763 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000765 // Check that there are no default arguments (C++ only).
766 if (getLangOptions().CPlusPlus)
767 CheckExtraCXXDefaultArguments(D);
768
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000770 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
771 D.getIdentifier()->getName());
772 InvalidDecl = true;
773 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000774
775 VarDecl *NewVD;
776 VarDecl::StorageClass SC;
777 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000778 default: assert(0 && "Unknown storage class!");
779 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
780 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
781 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
782 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
783 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
784 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000786 if (D.getContext() == Declarator::MemberContext) {
787 assert(SC == VarDecl::Static && "Invalid storage class for member!");
788 // This is a static data member for a C++ class.
789 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
790 D.getIdentifierLoc(), II,
791 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000792 } else {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000793 if (S->getFnParent() == 0) {
794 // C99 6.9p2: The storage-class specifiers auto and register shall not
795 // appear in the declaration specifiers in an external declaration.
796 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
797 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
798 R.getAsString());
799 InvalidDecl = true;
800 }
801 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
802 II, R, SC, LastDeclarator);
803 } else {
804 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
805 II, R, SC, LastDeclarator);
806 }
Steve Naroff53a32342007-08-28 18:45:29 +0000807 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000809 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000810
Daniel Dunbara735ad82008-08-06 00:03:29 +0000811 // Handle GNU asm-label extension (encoded as an attribute).
812 if (Expr *E = (Expr*) D.getAsmLabel()) {
813 // The parser guarantees this is a string.
814 StringLiteral *SE = cast<StringLiteral>(E);
815 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
816 SE->getByteLength())));
817 }
818
Nate Begemanc8e89a82008-03-14 18:07:10 +0000819 // Emit an error if an address space was applied to decl with local storage.
820 // This includes arrays of objects with address space qualifiers, but not
821 // automatic variables that point to other address spaces.
822 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000823 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
824 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
825 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000826 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000827 // Merge the decl with the existing one if appropriate. If the decl is
828 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000829 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 NewVD = MergeVarDecl(NewVD, PrevDecl);
831 if (NewVD == 0) return 0;
832 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 New = NewVD;
834 }
835
836 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000837 if (II)
838 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000839 // If any semantic error occurred, mark the decl as invalid.
840 if (D.getInvalidType() || InvalidDecl)
841 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000842
843 return New;
844}
845
Eli Friedmanc594b322008-05-20 13:48:25 +0000846bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
847 switch (Init->getStmtClass()) {
848 default:
849 Diag(Init->getExprLoc(),
850 diag::err_init_element_not_constant, Init->getSourceRange());
851 return true;
852 case Expr::ParenExprClass: {
853 const ParenExpr* PE = cast<ParenExpr>(Init);
854 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
855 }
856 case Expr::CompoundLiteralExprClass:
857 return cast<CompoundLiteralExpr>(Init)->isFileScope();
858 case Expr::DeclRefExprClass: {
859 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000860 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
861 if (VD->hasGlobalStorage())
862 return false;
863 Diag(Init->getExprLoc(),
864 diag::err_init_element_not_constant, Init->getSourceRange());
865 return true;
866 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000867 if (isa<FunctionDecl>(D))
868 return false;
869 Diag(Init->getExprLoc(),
870 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000871 return true;
872 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000873 case Expr::MemberExprClass: {
874 const MemberExpr *M = cast<MemberExpr>(Init);
875 if (M->isArrow())
876 return CheckAddressConstantExpression(M->getBase());
877 return CheckAddressConstantExpressionLValue(M->getBase());
878 }
879 case Expr::ArraySubscriptExprClass: {
880 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
881 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
882 return CheckAddressConstantExpression(ASE->getBase()) ||
883 CheckArithmeticConstantExpression(ASE->getIdx());
884 }
885 case Expr::StringLiteralClass:
886 case Expr::PreDefinedExprClass:
887 return false;
888 case Expr::UnaryOperatorClass: {
889 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
890
891 // C99 6.6p9
892 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000893 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000894
895 Diag(Init->getExprLoc(),
896 diag::err_init_element_not_constant, Init->getSourceRange());
897 return true;
898 }
899 }
900}
901
902bool Sema::CheckAddressConstantExpression(const Expr* Init) {
903 switch (Init->getStmtClass()) {
904 default:
905 Diag(Init->getExprLoc(),
906 diag::err_init_element_not_constant, Init->getSourceRange());
907 return true;
908 case Expr::ParenExprClass: {
909 const ParenExpr* PE = cast<ParenExpr>(Init);
910 return CheckAddressConstantExpression(PE->getSubExpr());
911 }
912 case Expr::StringLiteralClass:
913 case Expr::ObjCStringLiteralClass:
914 return false;
915 case Expr::CallExprClass: {
916 const CallExpr *CE = cast<CallExpr>(Init);
917 if (CE->isBuiltinConstantExpr())
918 return false;
919 Diag(Init->getExprLoc(),
920 diag::err_init_element_not_constant, Init->getSourceRange());
921 return true;
922 }
923 case Expr::UnaryOperatorClass: {
924 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
925
926 // C99 6.6p9
927 if (Exp->getOpcode() == UnaryOperator::AddrOf)
928 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
929
930 if (Exp->getOpcode() == UnaryOperator::Extension)
931 return CheckAddressConstantExpression(Exp->getSubExpr());
932
933 Diag(Init->getExprLoc(),
934 diag::err_init_element_not_constant, Init->getSourceRange());
935 return true;
936 }
937 case Expr::BinaryOperatorClass: {
938 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
939 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
940
941 Expr *PExp = Exp->getLHS();
942 Expr *IExp = Exp->getRHS();
943 if (IExp->getType()->isPointerType())
944 std::swap(PExp, IExp);
945
946 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
947 return CheckAddressConstantExpression(PExp) ||
948 CheckArithmeticConstantExpression(IExp);
949 }
950 case Expr::ImplicitCastExprClass: {
951 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
952
953 // Check for implicit promotion
954 if (SubExpr->getType()->isFunctionType() ||
955 SubExpr->getType()->isArrayType())
956 return CheckAddressConstantExpressionLValue(SubExpr);
957
958 // Check for pointer->pointer cast
959 if (SubExpr->getType()->isPointerType())
960 return CheckAddressConstantExpression(SubExpr);
961
962 if (SubExpr->getType()->isArithmeticType())
963 return CheckArithmeticConstantExpression(SubExpr);
964
965 Diag(Init->getExprLoc(),
966 diag::err_init_element_not_constant, Init->getSourceRange());
967 return true;
968 }
969 case Expr::CastExprClass: {
970 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
971
972 // Check for pointer->pointer cast
973 if (SubExpr->getType()->isPointerType())
974 return CheckAddressConstantExpression(SubExpr);
975
976 // FIXME: Should we pedwarn for (int*)(0+0)?
977 if (SubExpr->getType()->isArithmeticType())
978 return CheckArithmeticConstantExpression(SubExpr);
979
980 Diag(Init->getExprLoc(),
981 diag::err_init_element_not_constant, Init->getSourceRange());
982 return true;
983 }
984 case Expr::ConditionalOperatorClass: {
985 // FIXME: Should we pedwarn here?
986 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
987 if (!Exp->getCond()->getType()->isArithmeticType()) {
988 Diag(Init->getExprLoc(),
989 diag::err_init_element_not_constant, Init->getSourceRange());
990 return true;
991 }
992 if (CheckArithmeticConstantExpression(Exp->getCond()))
993 return true;
994 if (Exp->getLHS() &&
995 CheckAddressConstantExpression(Exp->getLHS()))
996 return true;
997 return CheckAddressConstantExpression(Exp->getRHS());
998 }
999 case Expr::AddrLabelExprClass:
1000 return false;
1001 }
1002}
1003
Eli Friedman4caf0552008-06-09 05:05:07 +00001004static const Expr* FindExpressionBaseAddress(const Expr* E);
1005
1006static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1007 switch (E->getStmtClass()) {
1008 default:
1009 return E;
1010 case Expr::ParenExprClass: {
1011 const ParenExpr* PE = cast<ParenExpr>(E);
1012 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1013 }
1014 case Expr::MemberExprClass: {
1015 const MemberExpr *M = cast<MemberExpr>(E);
1016 if (M->isArrow())
1017 return FindExpressionBaseAddress(M->getBase());
1018 return FindExpressionBaseAddressLValue(M->getBase());
1019 }
1020 case Expr::ArraySubscriptExprClass: {
1021 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1022 return FindExpressionBaseAddress(ASE->getBase());
1023 }
1024 case Expr::UnaryOperatorClass: {
1025 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1026
1027 if (Exp->getOpcode() == UnaryOperator::Deref)
1028 return FindExpressionBaseAddress(Exp->getSubExpr());
1029
1030 return E;
1031 }
1032 }
1033}
1034
1035static const Expr* FindExpressionBaseAddress(const Expr* E) {
1036 switch (E->getStmtClass()) {
1037 default:
1038 return E;
1039 case Expr::ParenExprClass: {
1040 const ParenExpr* PE = cast<ParenExpr>(E);
1041 return FindExpressionBaseAddress(PE->getSubExpr());
1042 }
1043 case Expr::UnaryOperatorClass: {
1044 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1045
1046 // C99 6.6p9
1047 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1048 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1049
1050 if (Exp->getOpcode() == UnaryOperator::Extension)
1051 return FindExpressionBaseAddress(Exp->getSubExpr());
1052
1053 return E;
1054 }
1055 case Expr::BinaryOperatorClass: {
1056 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1057
1058 Expr *PExp = Exp->getLHS();
1059 Expr *IExp = Exp->getRHS();
1060 if (IExp->getType()->isPointerType())
1061 std::swap(PExp, IExp);
1062
1063 return FindExpressionBaseAddress(PExp);
1064 }
1065 case Expr::ImplicitCastExprClass: {
1066 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1067
1068 // Check for implicit promotion
1069 if (SubExpr->getType()->isFunctionType() ||
1070 SubExpr->getType()->isArrayType())
1071 return FindExpressionBaseAddressLValue(SubExpr);
1072
1073 // Check for pointer->pointer cast
1074 if (SubExpr->getType()->isPointerType())
1075 return FindExpressionBaseAddress(SubExpr);
1076
1077 // We assume that we have an arithmetic expression here;
1078 // if we don't, we'll figure it out later
1079 return 0;
1080 }
1081 case Expr::CastExprClass: {
1082 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1083
1084 // Check for pointer->pointer cast
1085 if (SubExpr->getType()->isPointerType())
1086 return FindExpressionBaseAddress(SubExpr);
1087
1088 // We assume that we have an arithmetic expression here;
1089 // if we don't, we'll figure it out later
1090 return 0;
1091 }
1092 }
1093}
1094
Eli Friedmanc594b322008-05-20 13:48:25 +00001095bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1096 switch (Init->getStmtClass()) {
1097 default:
1098 Diag(Init->getExprLoc(),
1099 diag::err_init_element_not_constant, Init->getSourceRange());
1100 return true;
1101 case Expr::ParenExprClass: {
1102 const ParenExpr* PE = cast<ParenExpr>(Init);
1103 return CheckArithmeticConstantExpression(PE->getSubExpr());
1104 }
1105 case Expr::FloatingLiteralClass:
1106 case Expr::IntegerLiteralClass:
1107 case Expr::CharacterLiteralClass:
1108 case Expr::ImaginaryLiteralClass:
1109 case Expr::TypesCompatibleExprClass:
1110 case Expr::CXXBoolLiteralExprClass:
1111 return false;
1112 case Expr::CallExprClass: {
1113 const CallExpr *CE = cast<CallExpr>(Init);
1114 if (CE->isBuiltinConstantExpr())
1115 return false;
1116 Diag(Init->getExprLoc(),
1117 diag::err_init_element_not_constant, Init->getSourceRange());
1118 return true;
1119 }
1120 case Expr::DeclRefExprClass: {
1121 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1122 if (isa<EnumConstantDecl>(D))
1123 return false;
1124 Diag(Init->getExprLoc(),
1125 diag::err_init_element_not_constant, Init->getSourceRange());
1126 return true;
1127 }
1128 case Expr::CompoundLiteralExprClass:
1129 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1130 // but vectors are allowed to be magic.
1131 if (Init->getType()->isVectorType())
1132 return false;
1133 Diag(Init->getExprLoc(),
1134 diag::err_init_element_not_constant, Init->getSourceRange());
1135 return true;
1136 case Expr::UnaryOperatorClass: {
1137 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1138
1139 switch (Exp->getOpcode()) {
1140 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1141 // See C99 6.6p3.
1142 default:
1143 Diag(Init->getExprLoc(),
1144 diag::err_init_element_not_constant, Init->getSourceRange());
1145 return true;
1146 case UnaryOperator::SizeOf:
1147 case UnaryOperator::AlignOf:
1148 case UnaryOperator::OffsetOf:
1149 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1150 // See C99 6.5.3.4p2 and 6.6p3.
1151 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1152 return false;
1153 Diag(Init->getExprLoc(),
1154 diag::err_init_element_not_constant, Init->getSourceRange());
1155 return true;
1156 case UnaryOperator::Extension:
1157 case UnaryOperator::LNot:
1158 case UnaryOperator::Plus:
1159 case UnaryOperator::Minus:
1160 case UnaryOperator::Not:
1161 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1162 }
1163 }
1164 case Expr::SizeOfAlignOfTypeExprClass: {
1165 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1166 // Special check for void types, which are allowed as an extension
1167 if (Exp->getArgumentType()->isVoidType())
1168 return false;
1169 // alignof always evaluates to a constant.
1170 // FIXME: is sizeof(int[3.0]) a constant expression?
1171 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1172 Diag(Init->getExprLoc(),
1173 diag::err_init_element_not_constant, Init->getSourceRange());
1174 return true;
1175 }
1176 return false;
1177 }
1178 case Expr::BinaryOperatorClass: {
1179 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1180
1181 if (Exp->getLHS()->getType()->isArithmeticType() &&
1182 Exp->getRHS()->getType()->isArithmeticType()) {
1183 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1184 CheckArithmeticConstantExpression(Exp->getRHS());
1185 }
1186
Eli Friedman4caf0552008-06-09 05:05:07 +00001187 if (Exp->getLHS()->getType()->isPointerType() &&
1188 Exp->getRHS()->getType()->isPointerType()) {
1189 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1190 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1191
1192 // Only allow a null (constant integer) base; we could
1193 // allow some additional cases if necessary, but this
1194 // is sufficient to cover offsetof-like constructs.
1195 if (!LHSBase && !RHSBase) {
1196 return CheckAddressConstantExpression(Exp->getLHS()) ||
1197 CheckAddressConstantExpression(Exp->getRHS());
1198 }
1199 }
1200
Eli Friedmanc594b322008-05-20 13:48:25 +00001201 Diag(Init->getExprLoc(),
1202 diag::err_init_element_not_constant, Init->getSourceRange());
1203 return true;
1204 }
1205 case Expr::ImplicitCastExprClass:
1206 case Expr::CastExprClass: {
1207 const Expr *SubExpr;
1208 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1209 SubExpr = C->getSubExpr();
1210 } else {
1211 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1212 }
1213
1214 if (SubExpr->getType()->isArithmeticType())
1215 return CheckArithmeticConstantExpression(SubExpr);
1216
1217 Diag(Init->getExprLoc(),
1218 diag::err_init_element_not_constant, Init->getSourceRange());
1219 return true;
1220 }
1221 case Expr::ConditionalOperatorClass: {
1222 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1223 if (CheckArithmeticConstantExpression(Exp->getCond()))
1224 return true;
1225 if (Exp->getLHS() &&
1226 CheckArithmeticConstantExpression(Exp->getLHS()))
1227 return true;
1228 return CheckArithmeticConstantExpression(Exp->getRHS());
1229 }
1230 }
1231}
1232
1233bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001234 Init = Init->IgnoreParens();
1235
Eli Friedmanc594b322008-05-20 13:48:25 +00001236 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1237 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1238 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1239
Nuno Lopes9a979c32008-07-07 16:46:50 +00001240 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1241 return CheckForConstantInitializer(e->getInitializer(), DclT);
1242
Eli Friedmanc594b322008-05-20 13:48:25 +00001243 if (Init->getType()->isReferenceType()) {
1244 // FIXME: Work out how the heck reference types work
1245 return false;
1246#if 0
1247 // A reference is constant if the address of the expression
1248 // is constant
1249 // We look through initlists here to simplify
1250 // CheckAddressConstantExpressionLValue.
1251 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1252 assert(Exp->getNumInits() > 0 &&
1253 "Refernce initializer cannot be empty");
1254 Init = Exp->getInit(0);
1255 }
1256 return CheckAddressConstantExpressionLValue(Init);
1257#endif
1258 }
1259
1260 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1261 unsigned numInits = Exp->getNumInits();
1262 for (unsigned i = 0; i < numInits; i++) {
1263 // FIXME: Need to get the type of the declaration for C++,
1264 // because it could be a reference?
1265 if (CheckForConstantInitializer(Exp->getInit(i),
1266 Exp->getInit(i)->getType()))
1267 return true;
1268 }
1269 return false;
1270 }
1271
1272 if (Init->isNullPointerConstant(Context))
1273 return false;
1274 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001275 QualType InitTy = Context.getCanonicalType(Init->getType())
1276 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001277 if (InitTy == Context.BoolTy) {
1278 // Special handling for pointers implicitly cast to bool;
1279 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1280 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1281 Expr* SubE = ICE->getSubExpr();
1282 if (SubE->getType()->isPointerType() ||
1283 SubE->getType()->isArrayType() ||
1284 SubE->getType()->isFunctionType()) {
1285 return CheckAddressConstantExpression(Init);
1286 }
1287 }
1288 } else if (InitTy->isIntegralType()) {
1289 Expr* SubE = 0;
1290 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1291 SubE = ICE->getSubExpr();
1292 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1293 SubE = CE->getSubExpr();
1294 // Special check for pointer cast to int; we allow as an extension
1295 // an address constant cast to an integer if the integer
1296 // is of an appropriate width (this sort of code is apparently used
1297 // in some places).
1298 // FIXME: Add pedwarn?
1299 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1300 if (SubE && (SubE->getType()->isPointerType() ||
1301 SubE->getType()->isArrayType() ||
1302 SubE->getType()->isFunctionType())) {
1303 unsigned IntWidth = Context.getTypeSize(Init->getType());
1304 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1305 if (IntWidth >= PointerWidth)
1306 return CheckAddressConstantExpression(Init);
1307 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001308 }
1309
1310 return CheckArithmeticConstantExpression(Init);
1311 }
1312
1313 if (Init->getType()->isPointerType())
1314 return CheckAddressConstantExpression(Init);
1315
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001316 // An array type at the top level that isn't an init-list must
1317 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001318 if (Init->getType()->isArrayType())
1319 return false;
1320
1321 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1322 Init->getSourceRange());
1323 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001324}
1325
Steve Naroffbb204692007-09-12 14:07:44 +00001326void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001327 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001328 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001329 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001330
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001331 // If there is no declaration, there was an error parsing it. Just ignore
1332 // the initializer.
1333 if (RealDecl == 0) {
1334 delete Init;
1335 return;
1336 }
Steve Naroffbb204692007-09-12 14:07:44 +00001337
Steve Naroff410e3e22007-09-12 20:13:48 +00001338 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1339 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001340 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1341 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001342 RealDecl->setInvalidDecl();
1343 return;
1344 }
Steve Naroffbb204692007-09-12 14:07:44 +00001345 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001346 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001347 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001348 if (VDecl->isBlockVarDecl()) {
1349 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001350 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001351 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001352 VDecl->setInvalidDecl();
1353 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001354 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001355 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001356 if (SC == VarDecl::Static) // C99 6.7.8p4.
1357 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001358 }
Steve Naroff248a7532008-04-15 22:42:06 +00001359 } else if (VDecl->isFileVarDecl()) {
1360 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001361 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001362 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001363 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001364 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001365
1366 // C99 6.7.8p4. All file scoped initializers need to be constant.
1367 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001368 }
1369 // If the type changed, it means we had an incomplete type that was
1370 // completed by the initializer. For example:
1371 // int ary[] = { 1, 3, 5 };
1372 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001373 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001374 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001375 Init->setType(DclT);
1376 }
Steve Naroffbb204692007-09-12 14:07:44 +00001377
1378 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001379 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001380 return;
1381}
1382
Reid Spencer5f016e22007-07-11 17:01:13 +00001383/// The declarators are chained together backwards, reverse the list.
1384Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1385 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001386 Decl *GroupDecl = static_cast<Decl*>(group);
1387 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001388 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001389
1390 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1391 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001392 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001394 else { // reverse the list.
1395 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001396 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001397 Group->setNextDeclarator(NewGroup);
1398 NewGroup = Group;
1399 Group = Next;
1400 }
1401 }
1402 // Perform semantic analysis that depends on having fully processed both
1403 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001404 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001405 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1406 if (!IDecl)
1407 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001408 QualType T = IDecl->getType();
1409
1410 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1411 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001412 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1413 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001414 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001415 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1416 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001417 }
1418 }
1419 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1420 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001421 if (IDecl->isBlockVarDecl() &&
1422 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001423 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001424 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1425 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001426 IDecl->setInvalidDecl();
1427 }
1428 }
1429 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1430 // object that has file scope without an initializer, and without a
1431 // storage-class specifier or with the storage-class specifier "static",
1432 // constitutes a tentative definition. Note: A tentative definition with
1433 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001434 if (IDecl && !IDecl->getInit() &&
1435 (IDecl->getStorageClass() == VarDecl::Static ||
1436 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001437 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001438 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1439 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001440 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001441 // C99 6.9.2p3: If the declaration of an identifier for an object is
1442 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1443 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001444 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1445 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001446 IDecl->setInvalidDecl();
1447 }
1448 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 }
1450 return NewGroup;
1451}
Steve Naroffe1223f72007-08-28 03:03:08 +00001452
Chris Lattner04421082008-04-08 04:40:51 +00001453/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1454/// to introduce parameters into function prototype scope.
1455Sema::DeclTy *
1456Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001457 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001458
1459 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1460 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1461 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1462 Diag(DS.getStorageClassSpecLoc(),
1463 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001464 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001465 }
1466 if (DS.isThreadSpecified()) {
1467 Diag(DS.getThreadSpecLoc(),
1468 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001469 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001470 }
1471
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001472 // Check that there are no default arguments inside the type of this
1473 // parameter (C++ only).
1474 if (getLangOptions().CPlusPlus)
1475 CheckExtraCXXDefaultArguments(D);
1476
Chris Lattner04421082008-04-08 04:40:51 +00001477 // In this context, we *do not* check D.getInvalidType(). If the declarator
1478 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1479 // though it will not reflect the user specified type.
1480 QualType parmDeclType = GetTypeForDeclarator(D, S);
1481
1482 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1485 // Can this happen for params? We already checked that they don't conflict
1486 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001487 IdentifierInfo *II = D.getIdentifier();
1488 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1489 if (S->isDeclScope(PrevDecl)) {
1490 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1491 dyn_cast<NamedDecl>(PrevDecl)->getName());
1492
1493 // Recover by removing the name
1494 II = 0;
1495 D.SetIdentifier(0, D.getIdentifierLoc());
1496 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001498
1499 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1500 // Doing the promotion here has a win and a loss. The win is the type for
1501 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1502 // code generator). The loss is the orginal type isn't preserved. For example:
1503 //
1504 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1505 // int blockvardecl[5];
1506 // sizeof(parmvardecl); // size == 4
1507 // sizeof(blockvardecl); // size == 20
1508 // }
1509 //
1510 // For expressions, all implicit conversions are captured using the
1511 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1512 //
1513 // FIXME: If a source translation tool needs to see the original type, then
1514 // we need to consider storing both types (in ParmVarDecl)...
1515 //
Chris Lattnere6327742008-04-02 05:18:44 +00001516 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001517 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001518 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001519 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001520 parmDeclType = Context.getPointerType(parmDeclType);
1521
Chris Lattner04421082008-04-08 04:40:51 +00001522 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1523 D.getIdentifierLoc(), II,
1524 parmDeclType, VarDecl::None,
1525 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001526
Chris Lattner04421082008-04-08 04:40:51 +00001527 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001528 New->setInvalidDecl();
1529
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001530 if (II)
1531 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001532
Chris Lattner3ff30c82008-06-29 00:02:00 +00001533 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001535
Reid Spencer5f016e22007-07-11 17:01:13 +00001536}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001537
Chris Lattnerb652cea2007-10-09 17:14:05 +00001538Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001539 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1541 "Not a function declarator!");
1542 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001543
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1545 // for a K&R function.
1546 if (!FTI.hasPrototype) {
1547 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001548 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1550 FTI.ArgInfo[i].Ident->getName());
1551 // Implicitly declare the argument as type 'int' for lack of a better
1552 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001553 DeclSpec DS;
1554 const char* PrevSpec; // unused
1555 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1556 PrevSpec);
1557 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1558 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1559 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 }
1561 }
Chris Lattner52804082008-02-17 19:31:09 +00001562
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 // Since this is a function definition, act as though we have information
1564 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001565 if (FTI.NumArgs)
1566 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001568 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 }
1570
1571 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001572
1573 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001574 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001575 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001576 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1577 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1578 const FunctionDecl *Definition;
1579 if (FD->getBody(Definition)) {
1580 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1581 D.getIdentifier()->getName());
1582 Diag(Definition->getLocation(), diag::err_previous_definition);
1583 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001584 }
1585 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001586
1587 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001588 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001589}
1590
1591Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1592 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001593 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001594 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001595
1596 // Check the validity of our function parameters
1597 CheckParmsForFunctionDef(FD);
1598
1599 // Introduce our parameters into the function scope
1600 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1601 ParmVarDecl *Param = FD->getParamDecl(p);
1602 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001603 if (Param->getIdentifier())
1604 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 }
Chris Lattner04421082008-04-08 04:40:51 +00001606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 return FD;
1608}
1609
Steve Naroffd6d054d2007-11-11 23:20:51 +00001610Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1611 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001612 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001613 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001614 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001615 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001616 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001617 } else
1618 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001619 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001620 // Verify and clean out per-function state.
1621
1622 // Check goto/label use.
1623 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1624 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1625 // Verify that we have no forward references left. If so, there was a goto
1626 // or address of a label taken, but no definition of it. Label fwd
1627 // definitions are indicated with a null substmt.
1628 if (I->second->getSubStmt() == 0) {
1629 LabelStmt *L = I->second;
1630 // Emit error.
1631 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1632
1633 // At this point, we have gotos that use the bogus label. Stitch it into
1634 // the function body so that they aren't leaked and that the AST is well
1635 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001636 if (Body) {
1637 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1638 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1639 } else {
1640 // The whole function wasn't parsed correctly, just delete this.
1641 delete L;
1642 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 }
1644 }
1645 LabelMap.clear();
1646
Steve Naroffd6d054d2007-11-11 23:20:51 +00001647 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001648}
1649
Reid Spencer5f016e22007-07-11 17:01:13 +00001650/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1651/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001652ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1653 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001654 // Extension in C99. Legal in C90, but warn about it.
1655 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001657 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1659
1660 // FIXME: handle stuff like:
1661 // void foo() { extern float X(); }
1662 // void bar() { X(); } <-- implicit decl for X in another scope.
1663
1664 // Set a Declarator for the implicit definition: int foo();
1665 const char *Dummy;
1666 DeclSpec DS;
1667 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1668 Error = Error; // Silence warning.
1669 assert(!Error && "Error setting up implicit decl!");
1670 Declarator D(DS, Declarator::BlockContext);
1671 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1672 D.SetIdentifier(&II, Loc);
1673
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001674 // Insert this function into translation-unit scope.
1675
1676 DeclContext *PrevDC = CurContext;
1677 CurContext = Context.getTranslationUnitDecl();
1678
Steve Naroffe2ef8152008-04-04 14:32:09 +00001679 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001680 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001681 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001682
1683 CurContext = PrevDC;
1684
Steve Naroffe2ef8152008-04-04 14:32:09 +00001685 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001686}
1687
1688
Chris Lattner41af0932007-11-14 06:34:38 +00001689TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001690 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001692 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001693
1694 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001695 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1696 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001697 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001698 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001699 if (D.getInvalidType())
1700 NewTD->setInvalidDecl();
1701 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001702}
1703
Steve Naroff08d92e42007-09-15 18:49:24 +00001704/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001705/// former case, Name will be non-null. In the later case, Name will be null.
1706/// TagType indicates what kind of tag this is. TK indicates whether this is a
1707/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001708Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001709 SourceLocation KWLoc, IdentifierInfo *Name,
1710 SourceLocation NameLoc, AttributeList *Attr) {
1711 // If this is a use of an existing tag, it must have a name.
1712 assert((Name != 0 || TK == TK_Definition) &&
1713 "Nameless record must be a definition!");
1714
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001715 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 switch (TagType) {
1717 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001718 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1719 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1720 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1721 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 }
1723
1724 // If this is a named struct, check to see if there was a previous forward
1725 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001726 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1727 if (ScopedDecl *PrevDecl =
1728 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001729
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001730 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1731 "unexpected Decl type");
1732 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001733 // If this is a use of a previous tag, or if the tag is already declared
1734 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001735 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001736 if (TK == TK_Reference ||
1737 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001738 // Make sure that this wasn't declared as an enum and now used as a
1739 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001740 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001741 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1742 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001743 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001744 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001745 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001746 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001747 // If this is a use or a forward declaration, we're good.
1748 if (TK != TK_Definition)
1749 return PrevDecl;
1750
1751 // Diagnose attempts to redefine a tag.
1752 if (PrevTagDecl->isDefinition()) {
1753 Diag(NameLoc, diag::err_redefinition, Name->getName());
1754 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1755 // If this is a redefinition, recover by making this struct be
1756 // anonymous, which will make any later references get the previous
1757 // definition.
1758 Name = 0;
1759 } else {
1760 // Okay, this is definition of a previously declared or referenced
1761 // tag. Move the location of the decl to be the definition site.
1762 PrevDecl->setLocation(NameLoc);
1763 return PrevDecl;
1764 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001765 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001766 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001767 // If we get here, this is a definition of a new struct type in a nested
1768 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1769 // type.
1770 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001771 // PrevDecl is a namespace.
1772 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1773 // The tag name clashes with a namespace name, issue an error and recover
1774 // by making this tag be anonymous.
1775 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1776 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1777 Name = 0;
1778 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 }
1781
1782 // If there is an identifier, use the location of the identifier as the
1783 // location of the decl, otherwise use the location of the struct/union
1784 // keyword.
1785 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1786
1787 // Otherwise, if this is the first time we've seen this tag, create the decl.
1788 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001789 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1791 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001792 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001793 // If this is an undefined enum, warn.
1794 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001795 } else {
1796 // struct/union/class
1797
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1799 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001800 if (getLangOptions().CPlusPlus)
1801 // FIXME: Look for a way to use RecordDecl for simple structs.
1802 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1803 else
1804 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1805 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001806
1807 // If this has an identifier, add it to the scope stack.
1808 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001809 // The scope passed in may not be a decl scope. Zip up the scope tree until
1810 // we find one that is.
1811 while ((S->getFlags() & Scope::DeclScope) == 0)
1812 S = S->getParent();
1813
1814 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001815 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001817
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001818 if (Attr)
1819 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 return New;
1821}
1822
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001823/// Collect the instance variables declared in an Objective-C object. Used in
1824/// the creation of structures from objects using the @defs directive.
1825static void CollectIvars(ObjCInterfaceDecl *Class,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001826 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001827 if (Class->getSuperClass())
1828 CollectIvars(Class->getSuperClass(), ivars);
1829 ivars.append(Class->ivar_begin(), Class->ivar_end());
1830}
1831
1832/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1833/// instance variables of ClassName into Decls.
1834void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1835 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001836 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001837 // Check that ClassName is a valid class
1838 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1839 if (!Class) {
1840 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1841 return;
1842 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001843 // Collect the instance variables
1844 CollectIvars(Class, Decls);
1845}
1846
Eli Friedman1b76ada2008-06-03 21:01:11 +00001847QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1848 // This method tries to turn a variable array into a constant
1849 // array even when the size isn't an ICE. This is necessary
1850 // for compatibility with code that depends on gcc's buggy
1851 // constant expression folding, like struct {char x[(int)(char*)2];}
1852 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001853 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001854 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001855 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1856 llvm::APSInt &Res = Result.getInt();
1857 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1858 return Context.getConstantArrayType(VLATy->getElementType(),
1859 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001860 }
1861 }
1862 return QualType();
1863}
1864
Steve Naroff08d92e42007-09-15 18:49:24 +00001865/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001866/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001867Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001868 SourceLocation DeclStart,
1869 Declarator &D, ExprTy *BitfieldWidth) {
1870 IdentifierInfo *II = D.getIdentifier();
1871 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001872 SourceLocation Loc = DeclStart;
1873 if (II) Loc = D.getIdentifierLoc();
1874
1875 // FIXME: Unnamed fields can be handled in various different ways, for
1876 // example, unnamed unions inject all members into the struct namespace!
1877
1878
1879 if (BitWidth) {
1880 // TODO: Validate.
1881 //printf("WARNING: BITFIELDS IGNORED!\n");
1882
1883 // 6.7.2.1p3
1884 // 6.7.2.1p4
1885
1886 } else {
1887 // Not a bitfield.
1888
1889 // validate II.
1890
1891 }
1892
1893 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001894 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1895 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001896
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1898 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001899 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001900 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1901 if (!FixedTy.isNull()) {
1902 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1903 T = FixedTy;
1904 } else {
1905 // FIXME: This diagnostic needs work
1906 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1907 InvalidDecl = true;
1908 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001911 FieldDecl *NewFD;
1912
1913 if (getLangOptions().CPlusPlus) {
1914 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1915 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1916 Loc, II, T, BitWidth);
1917 if (II)
1918 PushOnScopeChains(NewFD, S);
1919 }
1920 else
1921 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001922
Chris Lattner3ff30c82008-06-29 00:02:00 +00001923 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00001924
Steve Naroff5912a352007-08-28 20:14:24 +00001925 if (D.getInvalidType() || InvalidDecl)
1926 NewFD->setInvalidDecl();
1927 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001928}
1929
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001930/// TranslateIvarVisibility - Translate visibility from a token ID to an
1931/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001933TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001934 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001935 case tok::objc_private: return ObjCIvarDecl::Private;
1936 case tok::objc_public: return ObjCIvarDecl::Public;
1937 case tok::objc_protected: return ObjCIvarDecl::Protected;
1938 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001939 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001940 }
1941}
1942
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001943/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1944/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001945Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001946 SourceLocation DeclStart,
1947 Declarator &D, ExprTy *BitfieldWidth,
1948 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001949 IdentifierInfo *II = D.getIdentifier();
1950 Expr *BitWidth = (Expr*)BitfieldWidth;
1951 SourceLocation Loc = DeclStart;
1952 if (II) Loc = D.getIdentifierLoc();
1953
1954 // FIXME: Unnamed fields can be handled in various different ways, for
1955 // example, unnamed unions inject all members into the struct namespace!
1956
1957
1958 if (BitWidth) {
1959 // TODO: Validate.
1960 //printf("WARNING: BITFIELDS IGNORED!\n");
1961
1962 // 6.7.2.1p3
1963 // 6.7.2.1p4
1964
1965 } else {
1966 // Not a bitfield.
1967
1968 // validate II.
1969
1970 }
1971
1972 QualType T = GetTypeForDeclarator(D, S);
1973 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1974 bool InvalidDecl = false;
1975
1976 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1977 // than a variably modified type.
1978 if (T->isVariablyModifiedType()) {
1979 // FIXME: This diagnostic needs work
1980 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1981 InvalidDecl = true;
1982 }
1983
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001984 // Get the visibility (access control) for this ivar.
1985 ObjCIvarDecl::AccessControl ac =
1986 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1987 : ObjCIvarDecl::None;
1988
1989 // Construct the decl.
1990 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00001991 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001992
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001993 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001994 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001995
1996 if (D.getInvalidType() || InvalidDecl)
1997 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001998
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001999 return NewID;
2000}
2001
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002002void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002003 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002004 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002005 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00002006 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2007 assert(EnclosingDecl && "missing record or interface decl");
2008 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2009
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002010 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002011 // Diagnose code like:
2012 // struct S { struct S {} X; };
2013 // We discover this when we complete the outer S. Reject and ignore the
2014 // outer S.
2015 Diag(Record->getLocation(), diag::err_nested_redefinition,
2016 Record->getKindName());
2017 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002018 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 return;
2020 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002021 // Verify that all the fields are okay.
2022 unsigned NumNamedMembers = 0;
2023 llvm::SmallVector<FieldDecl*, 32> RecFields;
2024 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002027
Steve Naroff74216642007-09-14 22:20:54 +00002028 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2029 assert(FD && "missing field decl");
2030
2031 // Remember all fields.
2032 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002033
2034 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002035 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002036
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002038 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002039 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002040 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002041 FD->setInvalidDecl();
2042 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 continue;
2044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2046 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002047 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002048 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002049 FD->setInvalidDecl();
2050 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002051 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002052 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002054 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002055 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002057 FD->setInvalidDecl();
2058 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 continue;
2060 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002061 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2063 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002064 FD->setInvalidDecl();
2065 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 continue;
2067 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002068 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002069 if (Record)
2070 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002071 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002072 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2073 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002074 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2076 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002077 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 Record->setHasFlexibleArrayMember(true);
2079 } else {
2080 // If this is a struct/class and this is not the last element, reject
2081 // it. Note that GCC supports variable sized arrays in the middle of
2082 // structures.
2083 if (i != NumFields-1) {
2084 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2085 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002086 FD->setInvalidDecl();
2087 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 continue;
2089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // We support flexible arrays at the end of structs in other structs
2091 // as an extension.
2092 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2093 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002094 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002095 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 }
2097 }
2098 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002099 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002101 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2102 FD->getName());
2103 FD->setInvalidDecl();
2104 EnclosingDecl->setInvalidDecl();
2105 continue;
2106 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 // Keep track of the number of named members.
2108 if (IdentifierInfo *II = FD->getIdentifier()) {
2109 // Detect duplicate member names.
2110 if (!FieldIDs.insert(II)) {
2111 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2112 // Find the previous decl.
2113 SourceLocation PrevLoc;
2114 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2115 assert(i != e && "Didn't find previous def!");
2116 if (RecFields[i]->getIdentifier() == II) {
2117 PrevLoc = RecFields[i]->getLocation();
2118 break;
2119 }
2120 }
2121 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002122 FD->setInvalidDecl();
2123 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002124 continue;
2125 }
2126 ++NumNamedMembers;
2127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 }
2129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002131 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002132 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00002133 Consumer.HandleTagDeclDefinition(Record);
2134 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002135 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2136 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2137 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2138 else if (ObjCImplementationDecl *IMPDecl =
2139 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002140 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2141 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002142 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002143 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002144 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002145}
2146
Steve Naroff08d92e42007-09-15 18:49:24 +00002147Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 DeclTy *lastEnumConst,
2149 SourceLocation IdLoc, IdentifierInfo *Id,
2150 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002151 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 EnumConstantDecl *LastEnumConst =
2153 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2154 Expr *Val = static_cast<Expr*>(val);
2155
Chris Lattner31e05722007-08-26 06:24:45 +00002156 // The scope passed in may not be a decl scope. Zip up the scope tree until
2157 // we find one that is.
2158 while ((S->getFlags() & Scope::DeclScope) == 0)
2159 S = S->getParent();
2160
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 // Verify that there isn't already something declared with this name in this
2162 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002163 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002164 // When in C++, we may get a TagDecl with the same name; in this case the
2165 // enum constant will 'hide' the tag.
2166 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2167 "Received TagDecl when not in C++!");
2168 if (!isa<TagDecl>(PrevDecl) &&
2169 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 if (isa<EnumConstantDecl>(PrevDecl))
2171 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2172 else
2173 Diag(IdLoc, diag::err_redefinition, Id->getName());
2174 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002175 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 return 0;
2177 }
2178 }
2179
2180 llvm::APSInt EnumVal(32);
2181 QualType EltTy;
2182 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002183 // Make sure to promote the operand type to int.
2184 UsualUnaryConversions(Val);
2185
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2187 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002188 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002189 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2190 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002191 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002192 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002193 } else {
2194 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002196 }
2197
2198 if (!Val) {
2199 if (LastEnumConst) {
2200 // Assign the last value + 1.
2201 EnumVal = LastEnumConst->getInitVal();
2202 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002203
2204 // Check for overflow on increment.
2205 if (EnumVal < LastEnumConst->getInitVal())
2206 Diag(IdLoc, diag::warn_enum_value_overflow);
2207
Chris Lattnerb7416f92007-08-27 17:37:24 +00002208 EltTy = LastEnumConst->getType();
2209 } else {
2210 // First value, set to zero.
2211 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002212 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 }
2215
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002216 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002217 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2218 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002219 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002220
2221 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002222 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002223 return New;
2224}
2225
Steve Naroff08d92e42007-09-15 18:49:24 +00002226void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 DeclTy **Elements, unsigned NumElements) {
2228 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
2229 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
2230
Chris Lattnere37f0be2007-08-28 05:10:31 +00002231 // TODO: If the result value doesn't fit in an int, it must be a long or long
2232 // long value. ISO C does not support this, but GCC does as an extension,
2233 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002234 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002235
Chris Lattnerac609682007-08-28 06:15:15 +00002236 // Verify that all the values are okay, compute the size of the values, and
2237 // reverse the list.
2238 unsigned NumNegativeBits = 0;
2239 unsigned NumPositiveBits = 0;
2240
2241 // Keep track of whether all elements have type int.
2242 bool AllElementsInt = true;
2243
Reid Spencer5f016e22007-07-11 17:01:13 +00002244 EnumConstantDecl *EltList = 0;
2245 for (unsigned i = 0; i != NumElements; ++i) {
2246 EnumConstantDecl *ECD =
2247 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2248 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002249
2250 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002251 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002252 assert(InitVal.getBitWidth() >= IntWidth &&
2253 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002254 if (InitVal.getBitWidth() > IntWidth) {
2255 llvm::APSInt V(InitVal);
2256 V.trunc(IntWidth);
2257 V.extend(InitVal.getBitWidth());
2258 if (V != InitVal)
2259 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2260 InitVal.toString());
2261 }
Chris Lattnerac609682007-08-28 06:15:15 +00002262
2263 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002264 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002265 NumPositiveBits = std::max(NumPositiveBits,
2266 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002267 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002268 NumNegativeBits = std::max(NumNegativeBits,
2269 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002270
Chris Lattnerac609682007-08-28 06:15:15 +00002271 // Keep track of whether every enum element has type int (very commmon).
2272 if (AllElementsInt)
2273 AllElementsInt = ECD->getType() == Context.IntTy;
2274
Reid Spencer5f016e22007-07-11 17:01:13 +00002275 ECD->setNextDeclarator(EltList);
2276 EltList = ECD;
2277 }
2278
Chris Lattnerac609682007-08-28 06:15:15 +00002279 // Figure out the type that should be used for this enum.
2280 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2281 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002282 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002283
2284 if (NumNegativeBits) {
2285 // If there is a negative value, figure out the smallest integer type (of
2286 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002287 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002288 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002289 BestWidth = IntWidth;
2290 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002291 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002292
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002293 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002294 BestType = Context.LongTy;
2295 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002296 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002297
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002298 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002299 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2300 BestType = Context.LongLongTy;
2301 }
2302 }
2303 } else {
2304 // If there is no negative value, figure out which of uint, ulong, ulonglong
2305 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002306 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002307 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002308 BestWidth = IntWidth;
2309 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002310 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002311 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002312 } else {
2313 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002314 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002315 "How could an initializer get larger than ULL?");
2316 BestType = Context.UnsignedLongLongTy;
2317 }
2318 }
2319
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002320 // Loop over all of the enumerator constants, changing their types to match
2321 // the type of the enum if needed.
2322 for (unsigned i = 0; i != NumElements; ++i) {
2323 EnumConstantDecl *ECD =
2324 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2325 if (!ECD) continue; // Already issued a diagnostic.
2326
2327 // Standard C says the enumerators have int type, but we allow, as an
2328 // extension, the enumerators to be larger than int size. If each
2329 // enumerator value fits in an int, type it as an int, otherwise type it the
2330 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2331 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002332 if (ECD->getType() == Context.IntTy) {
2333 // Make sure the init value is signed.
2334 llvm::APSInt IV = ECD->getInitVal();
2335 IV.setIsSigned(true);
2336 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002337 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002338 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002339
2340 // Determine whether the value fits into an int.
2341 llvm::APSInt InitVal = ECD->getInitVal();
2342 bool FitsInInt;
2343 if (InitVal.isUnsigned() || !InitVal.isNegative())
2344 FitsInInt = InitVal.getActiveBits() < IntWidth;
2345 else
2346 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2347
2348 // If it fits into an integer type, force it. Otherwise force it to match
2349 // the enum decl type.
2350 QualType NewTy;
2351 unsigned NewWidth;
2352 bool NewSign;
2353 if (FitsInInt) {
2354 NewTy = Context.IntTy;
2355 NewWidth = IntWidth;
2356 NewSign = true;
2357 } else if (ECD->getType() == BestType) {
2358 // Already the right type!
2359 continue;
2360 } else {
2361 NewTy = BestType;
2362 NewWidth = BestWidth;
2363 NewSign = BestType->isSignedIntegerType();
2364 }
2365
2366 // Adjust the APSInt value.
2367 InitVal.extOrTrunc(NewWidth);
2368 InitVal.setIsSigned(NewSign);
2369 ECD->setInitVal(InitVal);
2370
2371 // Adjust the Expr initializer and type.
2372 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2373 ECD->setType(NewTy);
2374 }
Chris Lattnerac609682007-08-28 06:15:15 +00002375
Chris Lattnere00b18c2007-08-28 18:24:31 +00002376 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002377 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002378}
2379
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002380Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2381 ExprTy *expr) {
2382 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2383
Chris Lattner8e25d862008-03-16 00:16:02 +00002384 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002385}
2386
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002387Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002388 SourceLocation LBrace,
2389 SourceLocation RBrace,
2390 const char *Lang,
2391 unsigned StrSize,
2392 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002393 LinkageSpecDecl::LanguageIDs Language;
2394 Decl *dcl = static_cast<Decl *>(D);
2395 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2396 Language = LinkageSpecDecl::lang_c;
2397 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2398 Language = LinkageSpecDecl::lang_cxx;
2399 else {
2400 Diag(Loc, diag::err_bad_language);
2401 return 0;
2402 }
2403
2404 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002405 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002406}