blob: 580c949ddd1f857b8d1b3b9d001a984a044827ba [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 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000107 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000108}
109
Steve Naroffb216c882007-10-09 22:01:59 +0000110void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000111 if (S->decl_empty()) return;
112 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
115 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000116 Decl *TmpD = static_cast<Decl*>(*I);
117 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000118
119 if (isa<CXXFieldDecl>(TmpD)) continue;
120
121 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
122 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000123
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 IdentifierInfo *II = D->getIdentifier();
125 if (!II) continue;
126
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000127 // We only want to remove the decls from the identifier decl chains for local
128 // scopes, when inside a function/method.
129 if (S->getFnParent() != 0)
130 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000131
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000132 // Chain this decl to the containing DeclContext.
133 D->setNext(CurContext->getDeclChain());
134 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 }
136}
137
Steve Naroffe8043c32008-04-01 23:04:06 +0000138/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
139/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000140ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000141 // The third "scope" argument is 0 since we aren't enabling lazy built-in
142 // creation from this context.
143 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000144
Steve Naroffb327ce02008-04-02 14:35:35 +0000145 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000146}
147
Steve Naroffe8043c32008-04-01 23:04:06 +0000148/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000149/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000150Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
151 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000153 unsigned NS = NSI;
154 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
155 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // Scan up the scope chain looking for a decl that matches this identifier
158 // that is in the appropriate namespace. This search should not take long, as
159 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000160 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000161 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000162 if ((*I)->getIdentifierNamespace() & NS)
163 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 // If we didn't find a use of this identifier, and if the identifier
166 // corresponds to a compiler builtin, create the decl object for the builtin
167 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000168 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000169 if (enableLazyBuiltinCreation) {
170 // If this is a builtin on this (or all) targets, create the decl.
171 if (unsigned BuiltinID = II->getBuiltinID())
172 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
173 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000174 if (getLangOptions().ObjC1) {
175 // @interface and @compatibility_alias introduce typedef-like names.
176 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000177 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000178 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000179 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
180 if (IDI != ObjCInterfaceDecls.end())
181 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000182 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
183 if (I != ObjCAliasDecls.end())
184 return I->second->getClassInterface();
185 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 }
187 return 0;
188}
189
Chris Lattner95e2c712008-05-05 22:18:14 +0000190void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000191 if (!Context.getBuiltinVaListType().isNull())
192 return;
193
194 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000195 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000196 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000197 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
198}
199
Reid Spencer5f016e22007-07-11 17:01:13 +0000200/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
201/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000202ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
203 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 Builtin::ID BID = (Builtin::ID)bid;
205
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000206 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000207 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerf8396b62008-07-09 17:26:36 +0000208 BID == Builtin::BI__builtin_va_end ||
209 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000210 InitBuiltinVaListType();
211
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000212 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000213 FunctionDecl *New = FunctionDecl::Create(Context,
214 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000215 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000216 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000217
Chris Lattner95e2c712008-05-05 22:18:14 +0000218 // Create Decl objects for each parameter, adding them to the
219 // FunctionDecl.
220 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
221 llvm::SmallVector<ParmVarDecl*, 16> Params;
222 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
223 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
224 FT->getArgType(i), VarDecl::None, 0,
225 0));
226 New->setParams(&Params[0], Params.size());
227 }
228
229
230
Chris Lattner7f925cc2008-04-11 07:00:53 +0000231 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000232 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 return New;
234}
235
236/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
237/// and scope as a previous declaration 'Old'. Figure out how to resolve this
238/// situation, merging decls or emitting diagnostics as appropriate.
239///
Steve Naroffe8043c32008-04-01 23:04:06 +0000240TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000241 // Verify the old decl was also a typedef.
242 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
243 if (!Old) {
244 Diag(New->getLocation(), diag::err_redefinition_different_kind,
245 New->getName());
246 Diag(OldD->getLocation(), diag::err_previous_definition);
247 return New;
248 }
249
Chris Lattner99cb9972008-07-25 18:44:27 +0000250 // If the typedef types are not identical, reject them in all languages and
251 // with any extensions enabled.
252 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
253 Context.getCanonicalType(Old->getUnderlyingType()) !=
254 Context.getCanonicalType(New->getUnderlyingType())) {
255 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
256 New->getUnderlyingType().getAsString(),
257 Old->getUnderlyingType().getAsString());
258 Diag(Old->getLocation(), diag::err_previous_definition);
259 return Old;
260 }
261
Steve Naroff8ee529b2007-10-31 18:42:27 +0000262 // Allow multiple definitions for ObjC built-in typedefs.
263 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000264 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000265 return Old;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000266
267 if (getLangOptions().Microsoft) return New;
268
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000269 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
270 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
271 // *either* declaration is in a system header. The code below implements
272 // this adhoc compatibility rule. FIXME: The following code will not
273 // work properly when compiling ".i" files (containing preprocessed output).
274 SourceManager &SrcMgr = Context.getSourceManager();
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000275 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
Eli Friedman54ecfce2008-06-11 06:20:39 +0000276 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
277 if (OldDeclFile) {
278 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
279 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
280 if (OldDirType != DirectoryLookup::NormalHeaderDir)
281 return New;
282 }
283 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
284 if (NewDeclFile) {
285 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
286 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
287 if (NewDirType != DirectoryLookup::NormalHeaderDir)
288 return New;
289 }
290
Ted Kremenek2d05c082008-05-23 21:28:18 +0000291 Diag(New->getLocation(), diag::err_redefinition, New->getName());
292 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 return New;
294}
295
Chris Lattner6b6b5372008-06-26 18:38:35 +0000296/// DeclhasAttr - returns true if decl Declaration already has the target
297/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000298static bool DeclHasAttr(const Decl *decl, const Attr *target) {
299 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
300 if (attr->getKind() == target->getKind())
301 return true;
302
303 return false;
304}
305
306/// MergeAttributes - append attributes from the Old decl to the New one.
307static void MergeAttributes(Decl *New, Decl *Old) {
308 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
309
Chris Lattnerddee4232008-03-03 03:28:21 +0000310 while (attr) {
311 tmp = attr;
312 attr = attr->getNext();
313
314 if (!DeclHasAttr(New, tmp)) {
315 New->addAttr(tmp);
316 } else {
317 tmp->setNext(0);
318 delete(tmp);
319 }
320 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000321
322 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000323}
324
Chris Lattner04421082008-04-08 04:40:51 +0000325/// MergeFunctionDecl - We just parsed a function 'New' from
326/// declarator D which has the same name and scope as a previous
327/// declaration 'Old'. Figure out how to resolve this situation,
328/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000329/// Redeclaration will be set true if thisNew is a redeclaration OldD.
330FunctionDecl *
331Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
332 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 // Verify the old decl was also a function.
334 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
335 if (!Old) {
336 Diag(New->getLocation(), diag::err_redefinition_different_kind,
337 New->getName());
338 Diag(OldD->getLocation(), diag::err_previous_definition);
339 return New;
340 }
Chris Lattner04421082008-04-08 04:40:51 +0000341
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000342 QualType OldQType = Context.getCanonicalType(Old->getType());
343 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000344
Chris Lattner04421082008-04-08 04:40:51 +0000345 // C++ [dcl.fct]p3:
346 // All declarations for a function shall agree exactly in both the
347 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000348 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
349 MergeAttributes(New, Old);
350 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000351 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000352 }
Chris Lattner04421082008-04-08 04:40:51 +0000353
354 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000355 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000356 if (!getLangOptions().CPlusPlus &&
357 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000358 MergeAttributes(New, Old);
359 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000360 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000361 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000362
Steve Naroff837618c2008-01-16 15:01:34 +0000363 // A function that has already been declared has been redeclared or defined
364 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000365 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000366 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000367 PrevDiag = diag::err_previous_definition;
368 else if (Old->isImplicit())
369 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000370 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000371 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
374 // TODO: This is totally simplistic. It should handle merging functions
375 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000376 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
377 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 return New;
379}
380
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000381/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000382static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000383 if (VD->isFileVarDecl())
384 return (!VD->getInit() &&
385 (VD->getStorageClass() == VarDecl::None ||
386 VD->getStorageClass() == VarDecl::Static));
387 return false;
388}
389
390/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
391/// when dealing with C "tentative" external object definitions (C99 6.9.2).
392void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
393 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000394 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000395
396 for (IdentifierResolver::iterator
397 I = IdResolver.begin(VD->getIdentifier(),
398 VD->getDeclContext(), false/*LookInParentCtx*/),
399 E = IdResolver.end(); I != E; ++I) {
400 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
401 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
402
Steve Narofff855e6f2008-08-10 15:20:13 +0000403 // Handle the following case:
404 // int a[10];
405 // int a[]; - the code below makes sure we set the correct type.
406 // int a[11]; - this is an error, size isn't 10.
407 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
408 OldDecl->getType()->isConstantArrayType())
409 VD->setType(OldDecl->getType());
410
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000411 // Check for "tentative" definitions. We can't accomplish this in
412 // MergeVarDecl since the initializer hasn't been attached.
413 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
414 continue;
415
416 // Handle __private_extern__ just like extern.
417 if (OldDecl->getStorageClass() != VarDecl::Extern &&
418 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
419 VD->getStorageClass() != VarDecl::Extern &&
420 VD->getStorageClass() != VarDecl::PrivateExtern) {
421 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
422 Diag(OldDecl->getLocation(), diag::err_previous_definition);
423 }
424 }
425 }
426}
427
Reid Spencer5f016e22007-07-11 17:01:13 +0000428/// MergeVarDecl - We just parsed a variable 'New' which has the same name
429/// and scope as a previous declaration 'Old'. Figure out how to resolve this
430/// situation, merging decls or emitting diagnostics as appropriate.
431///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000432/// Tentative definition rules (C99 6.9.2p2) are checked by
433/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
434/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000435///
Steve Naroffe8043c32008-04-01 23:04:06 +0000436VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 // Verify the old decl was also a variable.
438 VarDecl *Old = dyn_cast<VarDecl>(OldD);
439 if (!Old) {
440 Diag(New->getLocation(), diag::err_redefinition_different_kind,
441 New->getName());
442 Diag(OldD->getLocation(), diag::err_previous_definition);
443 return New;
444 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000445
446 MergeAttributes(New, Old);
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000449 QualType OldCType = Context.getCanonicalType(Old->getType());
450 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000451 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000452 Diag(New->getLocation(), diag::err_redefinition, New->getName());
453 Diag(Old->getLocation(), diag::err_previous_definition);
454 return New;
455 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000456 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
457 if (New->getStorageClass() == VarDecl::Static &&
458 (Old->getStorageClass() == VarDecl::None ||
459 Old->getStorageClass() == VarDecl::Extern)) {
460 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
461 Diag(Old->getLocation(), diag::err_previous_definition);
462 return New;
463 }
464 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
465 if (New->getStorageClass() != VarDecl::Static &&
466 Old->getStorageClass() == VarDecl::Static) {
467 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
468 Diag(Old->getLocation(), diag::err_previous_definition);
469 return New;
470 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000471 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
472 if (!New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 Diag(New->getLocation(), diag::err_redefinition, New->getName());
474 Diag(Old->getLocation(), diag::err_previous_definition);
475 }
476 return New;
477}
478
Chris Lattner04421082008-04-08 04:40:51 +0000479/// CheckParmsForFunctionDef - Check that the parameters of the given
480/// function are appropriate for the definition of a function. This
481/// takes care of any checks that cannot be performed on the
482/// declaration itself, e.g., that the types of each of the function
483/// parameters are complete.
484bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
485 bool HasInvalidParm = false;
486 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
487 ParmVarDecl *Param = FD->getParamDecl(p);
488
489 // C99 6.7.5.3p4: the parameters in a parameter type list in a
490 // function declarator that is part of a function definition of
491 // that function shall not have incomplete type.
492 if (Param->getType()->isIncompleteType() &&
493 !Param->isInvalidDecl()) {
494 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
495 Param->getType().getAsString());
496 Param->setInvalidDecl();
497 HasInvalidParm = true;
498 }
499 }
500
501 return HasInvalidParm;
502}
503
504/// CreateImplicitParameter - Creates an implicit function parameter
505/// in the scope S and with the given type. This routine is used, for
506/// example, to create the implicit "self" parameter in an Objective-C
507/// method.
Chris Lattner41110242008-06-17 18:05:57 +0000508ImplicitParamDecl *
Chris Lattner04421082008-04-08 04:40:51 +0000509Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
510 SourceLocation IdLoc, QualType Type) {
Chris Lattner41110242008-06-17 18:05:57 +0000511 ImplicitParamDecl *New = ImplicitParamDecl::Create(Context, CurContext,
512 IdLoc, Id, Type, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000513 if (Id)
514 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000515
516 return New;
517}
518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
520/// no declarator (e.g. "struct foo;") is parsed.
521Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
522 // TODO: emit error on 'int;' or 'const enum foo;'.
523 // TODO: emit error on 'typedef int;'
524 // if (!DS.isMissingDeclaratorOk()) Diag(...);
525
Steve Naroff92199282007-11-17 21:37:36 +0000526 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000527}
528
Steve Naroffd0091aa2008-01-10 22:15:12 +0000529bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000530 // Get the type before calling CheckSingleAssignmentConstraints(), since
531 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000532 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000533
Chris Lattner5cf216b2008-01-04 18:04:52 +0000534 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
535 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
536 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000537}
538
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000539bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000540 const ArrayType *AT = Context.getAsArrayType(DeclT);
541
542 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000543 // C99 6.7.8p14. We have an array of character type with unknown size
544 // being initialized to a string literal.
545 llvm::APSInt ConstVal(32);
546 ConstVal = strLiteral->getByteLength() + 1;
547 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000548 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000549 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000550 } else {
551 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000552 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000553 // FIXME: Avoid truncation for 64-bit length strings.
554 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000555 Diag(strLiteral->getSourceRange().getBegin(),
556 diag::warn_initializer_string_for_char_array_too_long,
557 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000558 }
559 // Set type from "char *" to "constant array of char".
560 strLiteral->setType(DeclT);
561 // For now, we always return false (meaning success).
562 return false;
563}
564
565StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000566 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000567 if (AT && AT->getElementType()->isCharType()) {
568 return dyn_cast<StringLiteral>(Init);
569 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000570 return 0;
571}
572
Steve Naroffa9960332008-01-25 00:51:06 +0000573bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000574 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
575 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000576 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000577 return Diag(VAT->getSizeExpr()->getLocStart(),
578 diag::err_variable_object_no_init,
579 VAT->getSizeExpr()->getSourceRange());
580
Steve Naroff2fdc3742007-12-10 22:44:33 +0000581 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
582 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000583 // FIXME: Handle wide strings
584 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
585 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000586
587 if (DeclType->isArrayType())
588 return Diag(Init->getLocStart(),
589 diag::err_array_init_list_required,
590 Init->getSourceRange());
591
Steve Naroffd0091aa2008-01-10 22:15:12 +0000592 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000593 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000594
Steve Naroff0cca7492008-05-01 22:18:59 +0000595 InitListChecker CheckInitList(this, InitList, DeclType);
596 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000597}
598
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000599Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000600Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000601 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 IdentifierInfo *II = D.getIdentifier();
603
Chris Lattnere80a59c2007-07-25 00:24:17 +0000604 // All of these full declarators require an identifier. If it doesn't have
605 // one, the ParsedFreeStandingDeclSpec action should be used.
606 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000607 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000608 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000609 D.getDeclSpec().getSourceRange(), D.getSourceRange());
610 return 0;
611 }
612
Chris Lattner31e05722007-08-26 06:24:45 +0000613 // The scope passed in may not be a decl scope. Zip up the scope tree until
614 // we find one that is.
615 while ((S->getFlags() & Scope::DeclScope) == 0)
616 S = S->getParent();
617
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000619 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000620 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000621 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000622
623 // In C++, the previous declaration we find might be a tag type
624 // (class or enum). In this case, the new declaration will hide the
625 // tag type.
626 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
627 PrevDecl = 0;
628
Chris Lattner41af0932007-11-14 06:34:38 +0000629 QualType R = GetTypeForDeclarator(D, S);
630 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000633 // Check that there are no default arguments (C++ only).
634 if (getLangOptions().CPlusPlus)
635 CheckExtraCXXDefaultArguments(D);
636
Chris Lattner41af0932007-11-14 06:34:38 +0000637 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 if (!NewTD) return 0;
639
640 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000641 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000642 // Merge the decl with the existing one if appropriate. If the decl is
643 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000644 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
646 if (NewTD == 0) return 0;
647 }
648 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000649 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000650 // C99 6.7.7p2: If a typedef name specifies a variably modified type
651 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000652 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
653 // FIXME: Diagnostic needs to be fixed.
654 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000655 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 }
657 }
Chris Lattner41af0932007-11-14 06:34:38 +0000658 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000659 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 switch (D.getDeclSpec().getStorageClassSpec()) {
661 default: assert(0 && "Unknown storage class!");
662 case DeclSpec::SCS_auto:
663 case DeclSpec::SCS_register:
664 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
665 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000666 InvalidDecl = true;
667 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
669 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
670 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000671 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 }
673
Chris Lattnera98e58d2008-03-15 21:24:04 +0000674 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000675 FunctionDecl *NewFD;
676 if (D.getContext() == Declarator::MemberContext) {
677 // This is a C++ method declaration.
678 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
679 D.getIdentifierLoc(), II, R,
680 (SC == FunctionDecl::Static), isInline,
681 LastDeclarator);
682 } else {
683 NewFD = FunctionDecl::Create(Context, CurContext,
684 D.getIdentifierLoc(),
685 II, R, SC, isInline,
686 LastDeclarator);
687 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000688 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000689 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000690
Daniel Dunbara80f8742008-08-05 01:35:17 +0000691 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000692 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000693 // The parser guarantees this is a string.
694 StringLiteral *SE = cast<StringLiteral>(E);
695 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
696 SE->getByteLength())));
697 }
698
Chris Lattner04421082008-04-08 04:40:51 +0000699 // Copy the parameter declarations from the declarator D to
700 // the function declaration NewFD, if they are available.
701 if (D.getNumTypeObjects() > 0 &&
702 D.getTypeObject(0).Fun.hasPrototype) {
703 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
704
705 // Create Decl objects for each parameter, adding them to the
706 // FunctionDecl.
707 llvm::SmallVector<ParmVarDecl*, 16> Params;
708
709 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
710 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000711 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000712 // We let through "const void" here because Sema::GetTypeForDeclarator
713 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000714 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
715 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000716 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
717 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000718 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
719
Chris Lattnerdef026a2008-04-10 02:26:16 +0000720 // In C++, the empty parameter-type-list must be spelled "void"; a
721 // typedef of void is not permitted.
722 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000723 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000724 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
725 }
726
Chris Lattner04421082008-04-08 04:40:51 +0000727 } else {
728 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
729 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
730 }
731
732 NewFD->setParams(&Params[0], Params.size());
733 }
734
Steve Naroffffce4d52008-01-09 23:34:55 +0000735 // Merge the decl with the existing one if appropriate. Since C functions
736 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000737 if (PrevDecl &&
738 (!getLangOptions().CPlusPlus ||
739 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000740 bool Redeclaration = false;
741 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000743 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000744 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000745 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000748
749 // In C++, check default arguments now that we have merged decls.
750 if (getLangOptions().CPlusPlus)
751 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000753 // Check that there are no default arguments (C++ only).
754 if (getLangOptions().CPlusPlus)
755 CheckExtraCXXDefaultArguments(D);
756
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000757 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000758 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
759 D.getIdentifier()->getName());
760 InvalidDecl = true;
761 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000762
763 VarDecl *NewVD;
764 VarDecl::StorageClass SC;
765 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000766 default: assert(0 && "Unknown storage class!");
767 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
768 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
769 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
770 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
771 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
772 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000774 if (D.getContext() == Declarator::MemberContext) {
775 assert(SC == VarDecl::Static && "Invalid storage class for member!");
776 // This is a static data member for a C++ class.
777 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
778 D.getIdentifierLoc(), II,
779 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000780 } else {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000781 if (S->getFnParent() == 0) {
782 // C99 6.9p2: The storage-class specifiers auto and register shall not
783 // appear in the declaration specifiers in an external declaration.
784 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
785 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
786 R.getAsString());
787 InvalidDecl = true;
788 }
789 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
790 II, R, SC, LastDeclarator);
791 } else {
792 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
793 II, R, SC, LastDeclarator);
794 }
Steve Naroff53a32342007-08-28 18:45:29 +0000795 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000797 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000798
Daniel Dunbara735ad82008-08-06 00:03:29 +0000799 // Handle GNU asm-label extension (encoded as an attribute).
800 if (Expr *E = (Expr*) D.getAsmLabel()) {
801 // The parser guarantees this is a string.
802 StringLiteral *SE = cast<StringLiteral>(E);
803 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
804 SE->getByteLength())));
805 }
806
Nate Begemanc8e89a82008-03-14 18:07:10 +0000807 // Emit an error if an address space was applied to decl with local storage.
808 // This includes arrays of objects with address space qualifiers, but not
809 // automatic variables that point to other address spaces.
810 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000811 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
812 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
813 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000814 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000815 // Merge the decl with the existing one if appropriate. If the decl is
816 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000817 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 NewVD = MergeVarDecl(NewVD, PrevDecl);
819 if (NewVD == 0) return 0;
820 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 New = NewVD;
822 }
823
824 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000825 if (II)
826 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000827 // If any semantic error occurred, mark the decl as invalid.
828 if (D.getInvalidType() || InvalidDecl)
829 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000830
831 return New;
832}
833
Eli Friedmanc594b322008-05-20 13:48:25 +0000834bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
835 switch (Init->getStmtClass()) {
836 default:
837 Diag(Init->getExprLoc(),
838 diag::err_init_element_not_constant, Init->getSourceRange());
839 return true;
840 case Expr::ParenExprClass: {
841 const ParenExpr* PE = cast<ParenExpr>(Init);
842 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
843 }
844 case Expr::CompoundLiteralExprClass:
845 return cast<CompoundLiteralExpr>(Init)->isFileScope();
846 case Expr::DeclRefExprClass: {
847 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000848 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
849 if (VD->hasGlobalStorage())
850 return false;
851 Diag(Init->getExprLoc(),
852 diag::err_init_element_not_constant, Init->getSourceRange());
853 return true;
854 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000855 if (isa<FunctionDecl>(D))
856 return false;
857 Diag(Init->getExprLoc(),
858 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000859 return true;
860 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000861 case Expr::MemberExprClass: {
862 const MemberExpr *M = cast<MemberExpr>(Init);
863 if (M->isArrow())
864 return CheckAddressConstantExpression(M->getBase());
865 return CheckAddressConstantExpressionLValue(M->getBase());
866 }
867 case Expr::ArraySubscriptExprClass: {
868 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
869 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
870 return CheckAddressConstantExpression(ASE->getBase()) ||
871 CheckArithmeticConstantExpression(ASE->getIdx());
872 }
873 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000874 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000875 return false;
876 case Expr::UnaryOperatorClass: {
877 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
878
879 // C99 6.6p9
880 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000881 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000882
883 Diag(Init->getExprLoc(),
884 diag::err_init_element_not_constant, Init->getSourceRange());
885 return true;
886 }
887 }
888}
889
890bool Sema::CheckAddressConstantExpression(const Expr* Init) {
891 switch (Init->getStmtClass()) {
892 default:
893 Diag(Init->getExprLoc(),
894 diag::err_init_element_not_constant, Init->getSourceRange());
895 return true;
896 case Expr::ParenExprClass: {
897 const ParenExpr* PE = cast<ParenExpr>(Init);
898 return CheckAddressConstantExpression(PE->getSubExpr());
899 }
900 case Expr::StringLiteralClass:
901 case Expr::ObjCStringLiteralClass:
902 return false;
903 case Expr::CallExprClass: {
904 const CallExpr *CE = cast<CallExpr>(Init);
905 if (CE->isBuiltinConstantExpr())
906 return false;
907 Diag(Init->getExprLoc(),
908 diag::err_init_element_not_constant, Init->getSourceRange());
909 return true;
910 }
911 case Expr::UnaryOperatorClass: {
912 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
913
914 // C99 6.6p9
915 if (Exp->getOpcode() == UnaryOperator::AddrOf)
916 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
917
918 if (Exp->getOpcode() == UnaryOperator::Extension)
919 return CheckAddressConstantExpression(Exp->getSubExpr());
920
921 Diag(Init->getExprLoc(),
922 diag::err_init_element_not_constant, Init->getSourceRange());
923 return true;
924 }
925 case Expr::BinaryOperatorClass: {
926 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
927 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
928
929 Expr *PExp = Exp->getLHS();
930 Expr *IExp = Exp->getRHS();
931 if (IExp->getType()->isPointerType())
932 std::swap(PExp, IExp);
933
934 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
935 return CheckAddressConstantExpression(PExp) ||
936 CheckArithmeticConstantExpression(IExp);
937 }
938 case Expr::ImplicitCastExprClass: {
939 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
940
941 // Check for implicit promotion
942 if (SubExpr->getType()->isFunctionType() ||
943 SubExpr->getType()->isArrayType())
944 return CheckAddressConstantExpressionLValue(SubExpr);
945
946 // Check for pointer->pointer cast
947 if (SubExpr->getType()->isPointerType())
948 return CheckAddressConstantExpression(SubExpr);
949
950 if (SubExpr->getType()->isArithmeticType())
951 return CheckArithmeticConstantExpression(SubExpr);
952
953 Diag(Init->getExprLoc(),
954 diag::err_init_element_not_constant, Init->getSourceRange());
955 return true;
956 }
957 case Expr::CastExprClass: {
958 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
959
960 // Check for pointer->pointer cast
961 if (SubExpr->getType()->isPointerType())
962 return CheckAddressConstantExpression(SubExpr);
963
964 // FIXME: Should we pedwarn for (int*)(0+0)?
965 if (SubExpr->getType()->isArithmeticType())
966 return CheckArithmeticConstantExpression(SubExpr);
967
968 Diag(Init->getExprLoc(),
969 diag::err_init_element_not_constant, Init->getSourceRange());
970 return true;
971 }
972 case Expr::ConditionalOperatorClass: {
973 // FIXME: Should we pedwarn here?
974 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
975 if (!Exp->getCond()->getType()->isArithmeticType()) {
976 Diag(Init->getExprLoc(),
977 diag::err_init_element_not_constant, Init->getSourceRange());
978 return true;
979 }
980 if (CheckArithmeticConstantExpression(Exp->getCond()))
981 return true;
982 if (Exp->getLHS() &&
983 CheckAddressConstantExpression(Exp->getLHS()))
984 return true;
985 return CheckAddressConstantExpression(Exp->getRHS());
986 }
987 case Expr::AddrLabelExprClass:
988 return false;
989 }
990}
991
Eli Friedman4caf0552008-06-09 05:05:07 +0000992static const Expr* FindExpressionBaseAddress(const Expr* E);
993
994static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
995 switch (E->getStmtClass()) {
996 default:
997 return E;
998 case Expr::ParenExprClass: {
999 const ParenExpr* PE = cast<ParenExpr>(E);
1000 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1001 }
1002 case Expr::MemberExprClass: {
1003 const MemberExpr *M = cast<MemberExpr>(E);
1004 if (M->isArrow())
1005 return FindExpressionBaseAddress(M->getBase());
1006 return FindExpressionBaseAddressLValue(M->getBase());
1007 }
1008 case Expr::ArraySubscriptExprClass: {
1009 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1010 return FindExpressionBaseAddress(ASE->getBase());
1011 }
1012 case Expr::UnaryOperatorClass: {
1013 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1014
1015 if (Exp->getOpcode() == UnaryOperator::Deref)
1016 return FindExpressionBaseAddress(Exp->getSubExpr());
1017
1018 return E;
1019 }
1020 }
1021}
1022
1023static const Expr* FindExpressionBaseAddress(const Expr* E) {
1024 switch (E->getStmtClass()) {
1025 default:
1026 return E;
1027 case Expr::ParenExprClass: {
1028 const ParenExpr* PE = cast<ParenExpr>(E);
1029 return FindExpressionBaseAddress(PE->getSubExpr());
1030 }
1031 case Expr::UnaryOperatorClass: {
1032 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1033
1034 // C99 6.6p9
1035 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1036 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1037
1038 if (Exp->getOpcode() == UnaryOperator::Extension)
1039 return FindExpressionBaseAddress(Exp->getSubExpr());
1040
1041 return E;
1042 }
1043 case Expr::BinaryOperatorClass: {
1044 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1045
1046 Expr *PExp = Exp->getLHS();
1047 Expr *IExp = Exp->getRHS();
1048 if (IExp->getType()->isPointerType())
1049 std::swap(PExp, IExp);
1050
1051 return FindExpressionBaseAddress(PExp);
1052 }
1053 case Expr::ImplicitCastExprClass: {
1054 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1055
1056 // Check for implicit promotion
1057 if (SubExpr->getType()->isFunctionType() ||
1058 SubExpr->getType()->isArrayType())
1059 return FindExpressionBaseAddressLValue(SubExpr);
1060
1061 // Check for pointer->pointer cast
1062 if (SubExpr->getType()->isPointerType())
1063 return FindExpressionBaseAddress(SubExpr);
1064
1065 // We assume that we have an arithmetic expression here;
1066 // if we don't, we'll figure it out later
1067 return 0;
1068 }
1069 case Expr::CastExprClass: {
1070 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1071
1072 // Check for pointer->pointer cast
1073 if (SubExpr->getType()->isPointerType())
1074 return FindExpressionBaseAddress(SubExpr);
1075
1076 // We assume that we have an arithmetic expression here;
1077 // if we don't, we'll figure it out later
1078 return 0;
1079 }
1080 }
1081}
1082
Eli Friedmanc594b322008-05-20 13:48:25 +00001083bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1084 switch (Init->getStmtClass()) {
1085 default:
1086 Diag(Init->getExprLoc(),
1087 diag::err_init_element_not_constant, Init->getSourceRange());
1088 return true;
1089 case Expr::ParenExprClass: {
1090 const ParenExpr* PE = cast<ParenExpr>(Init);
1091 return CheckArithmeticConstantExpression(PE->getSubExpr());
1092 }
1093 case Expr::FloatingLiteralClass:
1094 case Expr::IntegerLiteralClass:
1095 case Expr::CharacterLiteralClass:
1096 case Expr::ImaginaryLiteralClass:
1097 case Expr::TypesCompatibleExprClass:
1098 case Expr::CXXBoolLiteralExprClass:
1099 return false;
1100 case Expr::CallExprClass: {
1101 const CallExpr *CE = cast<CallExpr>(Init);
1102 if (CE->isBuiltinConstantExpr())
1103 return false;
1104 Diag(Init->getExprLoc(),
1105 diag::err_init_element_not_constant, Init->getSourceRange());
1106 return true;
1107 }
1108 case Expr::DeclRefExprClass: {
1109 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1110 if (isa<EnumConstantDecl>(D))
1111 return false;
1112 Diag(Init->getExprLoc(),
1113 diag::err_init_element_not_constant, Init->getSourceRange());
1114 return true;
1115 }
1116 case Expr::CompoundLiteralExprClass:
1117 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1118 // but vectors are allowed to be magic.
1119 if (Init->getType()->isVectorType())
1120 return false;
1121 Diag(Init->getExprLoc(),
1122 diag::err_init_element_not_constant, Init->getSourceRange());
1123 return true;
1124 case Expr::UnaryOperatorClass: {
1125 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1126
1127 switch (Exp->getOpcode()) {
1128 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1129 // See C99 6.6p3.
1130 default:
1131 Diag(Init->getExprLoc(),
1132 diag::err_init_element_not_constant, Init->getSourceRange());
1133 return true;
1134 case UnaryOperator::SizeOf:
1135 case UnaryOperator::AlignOf:
1136 case UnaryOperator::OffsetOf:
1137 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1138 // See C99 6.5.3.4p2 and 6.6p3.
1139 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1140 return false;
1141 Diag(Init->getExprLoc(),
1142 diag::err_init_element_not_constant, Init->getSourceRange());
1143 return true;
1144 case UnaryOperator::Extension:
1145 case UnaryOperator::LNot:
1146 case UnaryOperator::Plus:
1147 case UnaryOperator::Minus:
1148 case UnaryOperator::Not:
1149 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1150 }
1151 }
1152 case Expr::SizeOfAlignOfTypeExprClass: {
1153 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1154 // Special check for void types, which are allowed as an extension
1155 if (Exp->getArgumentType()->isVoidType())
1156 return false;
1157 // alignof always evaluates to a constant.
1158 // FIXME: is sizeof(int[3.0]) a constant expression?
1159 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1160 Diag(Init->getExprLoc(),
1161 diag::err_init_element_not_constant, Init->getSourceRange());
1162 return true;
1163 }
1164 return false;
1165 }
1166 case Expr::BinaryOperatorClass: {
1167 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1168
1169 if (Exp->getLHS()->getType()->isArithmeticType() &&
1170 Exp->getRHS()->getType()->isArithmeticType()) {
1171 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1172 CheckArithmeticConstantExpression(Exp->getRHS());
1173 }
1174
Eli Friedman4caf0552008-06-09 05:05:07 +00001175 if (Exp->getLHS()->getType()->isPointerType() &&
1176 Exp->getRHS()->getType()->isPointerType()) {
1177 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1178 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1179
1180 // Only allow a null (constant integer) base; we could
1181 // allow some additional cases if necessary, but this
1182 // is sufficient to cover offsetof-like constructs.
1183 if (!LHSBase && !RHSBase) {
1184 return CheckAddressConstantExpression(Exp->getLHS()) ||
1185 CheckAddressConstantExpression(Exp->getRHS());
1186 }
1187 }
1188
Eli Friedmanc594b322008-05-20 13:48:25 +00001189 Diag(Init->getExprLoc(),
1190 diag::err_init_element_not_constant, Init->getSourceRange());
1191 return true;
1192 }
1193 case Expr::ImplicitCastExprClass:
1194 case Expr::CastExprClass: {
1195 const Expr *SubExpr;
1196 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) {
1197 SubExpr = C->getSubExpr();
1198 } else {
1199 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr();
1200 }
1201
1202 if (SubExpr->getType()->isArithmeticType())
1203 return CheckArithmeticConstantExpression(SubExpr);
1204
1205 Diag(Init->getExprLoc(),
1206 diag::err_init_element_not_constant, Init->getSourceRange());
1207 return true;
1208 }
1209 case Expr::ConditionalOperatorClass: {
1210 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1211 if (CheckArithmeticConstantExpression(Exp->getCond()))
1212 return true;
1213 if (Exp->getLHS() &&
1214 CheckArithmeticConstantExpression(Exp->getLHS()))
1215 return true;
1216 return CheckArithmeticConstantExpression(Exp->getRHS());
1217 }
1218 }
1219}
1220
1221bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001222 Init = Init->IgnoreParens();
1223
Eli Friedmanc594b322008-05-20 13:48:25 +00001224 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1225 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1226 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1227
Nuno Lopes9a979c32008-07-07 16:46:50 +00001228 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1229 return CheckForConstantInitializer(e->getInitializer(), DclT);
1230
Eli Friedmanc594b322008-05-20 13:48:25 +00001231 if (Init->getType()->isReferenceType()) {
1232 // FIXME: Work out how the heck reference types work
1233 return false;
1234#if 0
1235 // A reference is constant if the address of the expression
1236 // is constant
1237 // We look through initlists here to simplify
1238 // CheckAddressConstantExpressionLValue.
1239 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1240 assert(Exp->getNumInits() > 0 &&
1241 "Refernce initializer cannot be empty");
1242 Init = Exp->getInit(0);
1243 }
1244 return CheckAddressConstantExpressionLValue(Init);
1245#endif
1246 }
1247
1248 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1249 unsigned numInits = Exp->getNumInits();
1250 for (unsigned i = 0; i < numInits; i++) {
1251 // FIXME: Need to get the type of the declaration for C++,
1252 // because it could be a reference?
1253 if (CheckForConstantInitializer(Exp->getInit(i),
1254 Exp->getInit(i)->getType()))
1255 return true;
1256 }
1257 return false;
1258 }
1259
1260 if (Init->isNullPointerConstant(Context))
1261 return false;
1262 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001263 QualType InitTy = Context.getCanonicalType(Init->getType())
1264 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001265 if (InitTy == Context.BoolTy) {
1266 // Special handling for pointers implicitly cast to bool;
1267 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1268 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1269 Expr* SubE = ICE->getSubExpr();
1270 if (SubE->getType()->isPointerType() ||
1271 SubE->getType()->isArrayType() ||
1272 SubE->getType()->isFunctionType()) {
1273 return CheckAddressConstantExpression(Init);
1274 }
1275 }
1276 } else if (InitTy->isIntegralType()) {
1277 Expr* SubE = 0;
1278 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init))
1279 SubE = ICE->getSubExpr();
1280 else if (CastExpr* CE = dyn_cast<CastExpr>(Init))
1281 SubE = CE->getSubExpr();
1282 // Special check for pointer cast to int; we allow as an extension
1283 // an address constant cast to an integer if the integer
1284 // is of an appropriate width (this sort of code is apparently used
1285 // in some places).
1286 // FIXME: Add pedwarn?
1287 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1288 if (SubE && (SubE->getType()->isPointerType() ||
1289 SubE->getType()->isArrayType() ||
1290 SubE->getType()->isFunctionType())) {
1291 unsigned IntWidth = Context.getTypeSize(Init->getType());
1292 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1293 if (IntWidth >= PointerWidth)
1294 return CheckAddressConstantExpression(Init);
1295 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001296 }
1297
1298 return CheckArithmeticConstantExpression(Init);
1299 }
1300
1301 if (Init->getType()->isPointerType())
1302 return CheckAddressConstantExpression(Init);
1303
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001304 // An array type at the top level that isn't an init-list must
1305 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001306 if (Init->getType()->isArrayType())
1307 return false;
1308
1309 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1310 Init->getSourceRange());
1311 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001312}
1313
Steve Naroffbb204692007-09-12 14:07:44 +00001314void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001315 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001316 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001317 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001318
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001319 // If there is no declaration, there was an error parsing it. Just ignore
1320 // the initializer.
1321 if (RealDecl == 0) {
1322 delete Init;
1323 return;
1324 }
Steve Naroffbb204692007-09-12 14:07:44 +00001325
Steve Naroff410e3e22007-09-12 20:13:48 +00001326 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1327 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001328 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1329 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001330 RealDecl->setInvalidDecl();
1331 return;
1332 }
Steve Naroffbb204692007-09-12 14:07:44 +00001333 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001334 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001335 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001336 if (VDecl->isBlockVarDecl()) {
1337 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001338 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001339 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001340 VDecl->setInvalidDecl();
1341 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001342 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001343 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001344 if (SC == VarDecl::Static) // C99 6.7.8p4.
1345 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001346 }
Steve Naroff248a7532008-04-15 22:42:06 +00001347 } else if (VDecl->isFileVarDecl()) {
1348 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001349 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001350 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001351 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001352 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001353
1354 // C99 6.7.8p4. All file scoped initializers need to be constant.
1355 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001356 }
1357 // If the type changed, it means we had an incomplete type that was
1358 // completed by the initializer. For example:
1359 // int ary[] = { 1, 3, 5 };
1360 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001361 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001362 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001363 Init->setType(DclT);
1364 }
Steve Naroffbb204692007-09-12 14:07:44 +00001365
1366 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001367 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001368 return;
1369}
1370
Reid Spencer5f016e22007-07-11 17:01:13 +00001371/// The declarators are chained together backwards, reverse the list.
1372Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1373 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001374 Decl *GroupDecl = static_cast<Decl*>(group);
1375 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001376 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001377
1378 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1379 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001380 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001382 else { // reverse the list.
1383 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001384 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001385 Group->setNextDeclarator(NewGroup);
1386 NewGroup = Group;
1387 Group = Next;
1388 }
1389 }
1390 // Perform semantic analysis that depends on having fully processed both
1391 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001392 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001393 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1394 if (!IDecl)
1395 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001396 QualType T = IDecl->getType();
1397
1398 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1399 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001400 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1401 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001402 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001403 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1404 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001405 }
1406 }
1407 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1408 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001409 if (IDecl->isBlockVarDecl() &&
1410 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001411 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001412 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1413 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001414 IDecl->setInvalidDecl();
1415 }
1416 }
1417 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1418 // object that has file scope without an initializer, and without a
1419 // storage-class specifier or with the storage-class specifier "static",
1420 // constitutes a tentative definition. Note: A tentative definition with
1421 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001422 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001423 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001424 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1425 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001426 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001427 // C99 6.9.2p3: If the declaration of an identifier for an object is
1428 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1429 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001430 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1431 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001432 IDecl->setInvalidDecl();
1433 }
1434 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001435 if (IDecl->isFileVarDecl())
1436 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 }
1438 return NewGroup;
1439}
Steve Naroffe1223f72007-08-28 03:03:08 +00001440
Chris Lattner04421082008-04-08 04:40:51 +00001441/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1442/// to introduce parameters into function prototype scope.
1443Sema::DeclTy *
1444Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001445 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001446
1447 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1448 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1449 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1450 Diag(DS.getStorageClassSpecLoc(),
1451 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001452 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001453 }
1454 if (DS.isThreadSpecified()) {
1455 Diag(DS.getThreadSpecLoc(),
1456 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001457 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001458 }
1459
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001460 // Check that there are no default arguments inside the type of this
1461 // parameter (C++ only).
1462 if (getLangOptions().CPlusPlus)
1463 CheckExtraCXXDefaultArguments(D);
1464
Chris Lattner04421082008-04-08 04:40:51 +00001465 // In this context, we *do not* check D.getInvalidType(). If the declarator
1466 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1467 // though it will not reflect the user specified type.
1468 QualType parmDeclType = GetTypeForDeclarator(D, S);
1469
1470 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1471
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1473 // Can this happen for params? We already checked that they don't conflict
1474 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001475 IdentifierInfo *II = D.getIdentifier();
1476 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1477 if (S->isDeclScope(PrevDecl)) {
1478 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1479 dyn_cast<NamedDecl>(PrevDecl)->getName());
1480
1481 // Recover by removing the name
1482 II = 0;
1483 D.SetIdentifier(0, D.getIdentifierLoc());
1484 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001486
1487 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1488 // Doing the promotion here has a win and a loss. The win is the type for
1489 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1490 // code generator). The loss is the orginal type isn't preserved. For example:
1491 //
1492 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1493 // int blockvardecl[5];
1494 // sizeof(parmvardecl); // size == 4
1495 // sizeof(blockvardecl); // size == 20
1496 // }
1497 //
1498 // For expressions, all implicit conversions are captured using the
1499 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1500 //
1501 // FIXME: If a source translation tool needs to see the original type, then
1502 // we need to consider storing both types (in ParmVarDecl)...
1503 //
Chris Lattnere6327742008-04-02 05:18:44 +00001504 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001505 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001506 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001507 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001508 parmDeclType = Context.getPointerType(parmDeclType);
1509
Chris Lattner04421082008-04-08 04:40:51 +00001510 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1511 D.getIdentifierLoc(), II,
1512 parmDeclType, VarDecl::None,
1513 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001514
Chris Lattner04421082008-04-08 04:40:51 +00001515 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001516 New->setInvalidDecl();
1517
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001518 if (II)
1519 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001520
Chris Lattner3ff30c82008-06-29 00:02:00 +00001521 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001525
Chris Lattnerb652cea2007-10-09 17:14:05 +00001526Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001527 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1529 "Not a function declarator!");
1530 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001531
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1533 // for a K&R function.
1534 if (!FTI.hasPrototype) {
1535 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001536 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1538 FTI.ArgInfo[i].Ident->getName());
1539 // Implicitly declare the argument as type 'int' for lack of a better
1540 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001541 DeclSpec DS;
1542 const char* PrevSpec; // unused
1543 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1544 PrevSpec);
1545 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1546 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1547 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 }
1549 }
Chris Lattner52804082008-02-17 19:31:09 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 // Since this is a function definition, act as though we have information
1552 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001553 if (FTI.NumArgs)
1554 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001556 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 }
1558
1559 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001560
1561 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001562 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001563 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001564 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1565 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1566 const FunctionDecl *Definition;
1567 if (FD->getBody(Definition)) {
1568 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1569 D.getIdentifier()->getName());
1570 Diag(Definition->getLocation(), diag::err_previous_definition);
1571 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001572 }
1573 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001574
1575 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001576 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001577}
1578
1579Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1580 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001581 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001582 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001583
1584 // Check the validity of our function parameters
1585 CheckParmsForFunctionDef(FD);
1586
1587 // Introduce our parameters into the function scope
1588 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1589 ParmVarDecl *Param = FD->getParamDecl(p);
1590 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001591 if (Param->getIdentifier())
1592 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 }
Chris Lattner04421082008-04-08 04:40:51 +00001594
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 return FD;
1596}
1597
Steve Naroffd6d054d2007-11-11 23:20:51 +00001598Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1599 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001600 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001601 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001602 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001603 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001604 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001605 } else
1606 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001607 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // Verify and clean out per-function state.
1609
1610 // Check goto/label use.
1611 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1612 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1613 // Verify that we have no forward references left. If so, there was a goto
1614 // or address of a label taken, but no definition of it. Label fwd
1615 // definitions are indicated with a null substmt.
1616 if (I->second->getSubStmt() == 0) {
1617 LabelStmt *L = I->second;
1618 // Emit error.
1619 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1620
1621 // At this point, we have gotos that use the bogus label. Stitch it into
1622 // the function body so that they aren't leaked and that the AST is well
1623 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001624 if (Body) {
1625 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1626 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1627 } else {
1628 // The whole function wasn't parsed correctly, just delete this.
1629 delete L;
1630 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 }
1632 }
1633 LabelMap.clear();
1634
Steve Naroffd6d054d2007-11-11 23:20:51 +00001635 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001636}
1637
Reid Spencer5f016e22007-07-11 17:01:13 +00001638/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1639/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001640ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1641 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001642 // Extension in C99. Legal in C90, but warn about it.
1643 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001644 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001645 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1647
1648 // FIXME: handle stuff like:
1649 // void foo() { extern float X(); }
1650 // void bar() { X(); } <-- implicit decl for X in another scope.
1651
1652 // Set a Declarator for the implicit definition: int foo();
1653 const char *Dummy;
1654 DeclSpec DS;
1655 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1656 Error = Error; // Silence warning.
1657 assert(!Error && "Error setting up implicit decl!");
1658 Declarator D(DS, Declarator::BlockContext);
1659 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1660 D.SetIdentifier(&II, Loc);
1661
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001662 // Insert this function into translation-unit scope.
1663
1664 DeclContext *PrevDC = CurContext;
1665 CurContext = Context.getTranslationUnitDecl();
1666
Steve Naroffe2ef8152008-04-04 14:32:09 +00001667 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001668 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001669 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001670
1671 CurContext = PrevDC;
1672
Steve Naroffe2ef8152008-04-04 14:32:09 +00001673 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001674}
1675
1676
Chris Lattner41af0932007-11-14 06:34:38 +00001677TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001678 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001679 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001680 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001681
1682 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001683 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1684 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001685 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001686 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001687 if (D.getInvalidType())
1688 NewTD->setInvalidDecl();
1689 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690}
1691
Steve Naroff08d92e42007-09-15 18:49:24 +00001692/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001693/// former case, Name will be non-null. In the later case, Name will be null.
1694/// TagType indicates what kind of tag this is. TK indicates whether this is a
1695/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001696Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 SourceLocation KWLoc, IdentifierInfo *Name,
1698 SourceLocation NameLoc, AttributeList *Attr) {
1699 // If this is a use of an existing tag, it must have a name.
1700 assert((Name != 0 || TK == TK_Definition) &&
1701 "Nameless record must be a definition!");
1702
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001703 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 switch (TagType) {
1705 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001706 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1707 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1708 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1709 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 }
1711
1712 // If this is a named struct, check to see if there was a previous forward
1713 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001714 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1715 if (ScopedDecl *PrevDecl =
1716 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001717
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001718 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1719 "unexpected Decl type");
1720 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001721 // If this is a use of a previous tag, or if the tag is already declared
1722 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001723 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001724 if (TK == TK_Reference ||
1725 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001726 // Make sure that this wasn't declared as an enum and now used as a
1727 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001728 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001729 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1730 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001731 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001732 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001733 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001734 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001735 // If this is a use or a forward declaration, we're good.
1736 if (TK != TK_Definition)
1737 return PrevDecl;
1738
1739 // Diagnose attempts to redefine a tag.
1740 if (PrevTagDecl->isDefinition()) {
1741 Diag(NameLoc, diag::err_redefinition, Name->getName());
1742 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1743 // If this is a redefinition, recover by making this struct be
1744 // anonymous, which will make any later references get the previous
1745 // definition.
1746 Name = 0;
1747 } else {
1748 // Okay, this is definition of a previously declared or referenced
1749 // tag. Move the location of the decl to be the definition site.
1750 PrevDecl->setLocation(NameLoc);
1751 return PrevDecl;
1752 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001753 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001755 // If we get here, this is a definition of a new struct type in a nested
1756 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1757 // type.
1758 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001759 // PrevDecl is a namespace.
1760 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1761 // The tag name clashes with a namespace name, issue an error and recover
1762 // by making this tag be anonymous.
1763 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1764 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1765 Name = 0;
1766 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
1769
1770 // If there is an identifier, use the location of the identifier as the
1771 // location of the decl, otherwise use the location of the struct/union
1772 // keyword.
1773 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1774
1775 // Otherwise, if this is the first time we've seen this tag, create the decl.
1776 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001777 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1779 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001780 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 // If this is an undefined enum, warn.
1782 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001783 } else {
1784 // struct/union/class
1785
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1787 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001788 if (getLangOptions().CPlusPlus)
1789 // FIXME: Look for a way to use RecordDecl for simple structs.
1790 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1791 else
1792 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
1793 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001794
1795 // If this has an identifier, add it to the scope stack.
1796 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001797 // The scope passed in may not be a decl scope. Zip up the scope tree until
1798 // we find one that is.
1799 while ((S->getFlags() & Scope::DeclScope) == 0)
1800 S = S->getParent();
1801
1802 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001803 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001805
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001806 if (Attr)
1807 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 return New;
1809}
1810
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001811/// Collect the instance variables declared in an Objective-C object. Used in
1812/// the creation of structures from objects using the @defs directive.
1813static void CollectIvars(ObjCInterfaceDecl *Class,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001814 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001815 if (Class->getSuperClass())
1816 CollectIvars(Class->getSuperClass(), ivars);
1817 ivars.append(Class->ivar_begin(), Class->ivar_end());
1818}
1819
1820/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1821/// instance variables of ClassName into Decls.
1822void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1823 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001824 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001825 // Check that ClassName is a valid class
1826 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1827 if (!Class) {
1828 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1829 return;
1830 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001831 // Collect the instance variables
1832 CollectIvars(Class, Decls);
1833}
1834
Eli Friedman1b76ada2008-06-03 21:01:11 +00001835QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1836 // This method tries to turn a variable array into a constant
1837 // array even when the size isn't an ICE. This is necessary
1838 // for compatibility with code that depends on gcc's buggy
1839 // constant expression folding, like struct {char x[(int)(char*)2];}
1840 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001841 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001842 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001843 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1844 llvm::APSInt &Res = Result.getInt();
1845 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1846 return Context.getConstantArrayType(VLATy->getElementType(),
1847 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001848 }
1849 }
1850 return QualType();
1851}
1852
Steve Naroff08d92e42007-09-15 18:49:24 +00001853/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001854/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001855Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 SourceLocation DeclStart,
1857 Declarator &D, ExprTy *BitfieldWidth) {
1858 IdentifierInfo *II = D.getIdentifier();
1859 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 SourceLocation Loc = DeclStart;
1861 if (II) Loc = D.getIdentifierLoc();
1862
1863 // FIXME: Unnamed fields can be handled in various different ways, for
1864 // example, unnamed unions inject all members into the struct namespace!
1865
1866
1867 if (BitWidth) {
1868 // TODO: Validate.
1869 //printf("WARNING: BITFIELDS IGNORED!\n");
1870
1871 // 6.7.2.1p3
1872 // 6.7.2.1p4
1873
1874 } else {
1875 // Not a bitfield.
1876
1877 // validate II.
1878
1879 }
1880
1881 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001882 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1883 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001884
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1886 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001887 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00001888 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
1889 if (!FixedTy.isNull()) {
1890 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
1891 T = FixedTy;
1892 } else {
1893 // FIXME: This diagnostic needs work
1894 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1895 InvalidDecl = true;
1896 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001899 FieldDecl *NewFD;
1900
1901 if (getLangOptions().CPlusPlus) {
1902 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
1903 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1904 Loc, II, T, BitWidth);
1905 if (II)
1906 PushOnScopeChains(NewFD, S);
1907 }
1908 else
1909 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001910
Chris Lattner3ff30c82008-06-29 00:02:00 +00001911 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00001912
Steve Naroff5912a352007-08-28 20:14:24 +00001913 if (D.getInvalidType() || InvalidDecl)
1914 NewFD->setInvalidDecl();
1915 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001916}
1917
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001918/// TranslateIvarVisibility - Translate visibility from a token ID to an
1919/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001920static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001921TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001922 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001923 case tok::objc_private: return ObjCIvarDecl::Private;
1924 case tok::objc_public: return ObjCIvarDecl::Public;
1925 case tok::objc_protected: return ObjCIvarDecl::Protected;
1926 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001927 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001928 }
1929}
1930
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001931/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1932/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001933Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001934 SourceLocation DeclStart,
1935 Declarator &D, ExprTy *BitfieldWidth,
1936 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001937 IdentifierInfo *II = D.getIdentifier();
1938 Expr *BitWidth = (Expr*)BitfieldWidth;
1939 SourceLocation Loc = DeclStart;
1940 if (II) Loc = D.getIdentifierLoc();
1941
1942 // FIXME: Unnamed fields can be handled in various different ways, for
1943 // example, unnamed unions inject all members into the struct namespace!
1944
1945
1946 if (BitWidth) {
1947 // TODO: Validate.
1948 //printf("WARNING: BITFIELDS IGNORED!\n");
1949
1950 // 6.7.2.1p3
1951 // 6.7.2.1p4
1952
1953 } else {
1954 // Not a bitfield.
1955
1956 // validate II.
1957
1958 }
1959
1960 QualType T = GetTypeForDeclarator(D, S);
1961 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1962 bool InvalidDecl = false;
1963
1964 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1965 // than a variably modified type.
1966 if (T->isVariablyModifiedType()) {
1967 // FIXME: This diagnostic needs work
1968 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1969 InvalidDecl = true;
1970 }
1971
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001972 // Get the visibility (access control) for this ivar.
1973 ObjCIvarDecl::AccessControl ac =
1974 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
1975 : ObjCIvarDecl::None;
1976
1977 // Construct the decl.
1978 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00001979 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001980
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001981 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001982 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001983
1984 if (D.getInvalidType() || InvalidDecl)
1985 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00001986
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001987 return NewID;
1988}
1989
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001990void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001991 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001992 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001993 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001994 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1995 assert(EnclosingDecl && "missing record or interface decl");
1996 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1997
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001998 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 // Diagnose code like:
2000 // struct S { struct S {} X; };
2001 // We discover this when we complete the outer S. Reject and ignore the
2002 // outer S.
2003 Diag(Record->getLocation(), diag::err_nested_redefinition,
2004 Record->getKindName());
2005 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002006 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 return;
2008 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 // Verify that all the fields are okay.
2010 unsigned NumNamedMembers = 0;
2011 llvm::SmallVector<FieldDecl*, 32> RecFields;
2012 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002013
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002015
Steve Naroff74216642007-09-14 22:20:54 +00002016 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2017 assert(FD && "missing field decl");
2018
2019 // Remember all fields.
2020 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002021
2022 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002023 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002026 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002027 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002029 FD->setInvalidDecl();
2030 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002031 continue;
2032 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2034 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002035 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002036 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002037 FD->setInvalidDecl();
2038 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002039 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002040 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002041 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002042 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002043 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002044 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002045 FD->setInvalidDecl();
2046 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002047 continue;
2048 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002049 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002050 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2051 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002052 FD->setInvalidDecl();
2053 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002054 continue;
2055 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002057 if (Record)
2058 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2061 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002062 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2064 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002065 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 Record->setHasFlexibleArrayMember(true);
2067 } else {
2068 // If this is a struct/class and this is not the last element, reject
2069 // it. Note that GCC supports variable sized arrays in the middle of
2070 // structures.
2071 if (i != NumFields-1) {
2072 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2073 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002074 FD->setInvalidDecl();
2075 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002076 continue;
2077 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 // We support flexible arrays at the end of structs in other structs
2079 // as an extension.
2080 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2081 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002082 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002083 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 }
2085 }
2086 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002087 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002089 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2090 FD->getName());
2091 FD->setInvalidDecl();
2092 EnclosingDecl->setInvalidDecl();
2093 continue;
2094 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 // Keep track of the number of named members.
2096 if (IdentifierInfo *II = FD->getIdentifier()) {
2097 // Detect duplicate member names.
2098 if (!FieldIDs.insert(II)) {
2099 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2100 // Find the previous decl.
2101 SourceLocation PrevLoc;
2102 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2103 assert(i != e && "Didn't find previous def!");
2104 if (RecFields[i]->getIdentifier() == II) {
2105 PrevLoc = RecFields[i]->getLocation();
2106 break;
2107 }
2108 }
2109 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002110 FD->setInvalidDecl();
2111 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 continue;
2113 }
2114 ++NumNamedMembers;
2115 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 }
2117
Reid Spencer5f016e22007-07-11 17:01:13 +00002118 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002119 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002120 Record->defineBody(&RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002121 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2122 // Sema::ActOnFinishCXXClassDef.
2123 if (!isa<CXXRecordDecl>(Record))
2124 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002125 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002126 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2127 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2128 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2129 else if (ObjCImplementationDecl *IMPDecl =
2130 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2132 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002133 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002134 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002135 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002136}
2137
Steve Naroff08d92e42007-09-15 18:49:24 +00002138Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 DeclTy *lastEnumConst,
2140 SourceLocation IdLoc, IdentifierInfo *Id,
2141 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002142 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002143 EnumConstantDecl *LastEnumConst =
2144 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2145 Expr *Val = static_cast<Expr*>(val);
2146
Chris Lattner31e05722007-08-26 06:24:45 +00002147 // The scope passed in may not be a decl scope. Zip up the scope tree until
2148 // we find one that is.
2149 while ((S->getFlags() & Scope::DeclScope) == 0)
2150 S = S->getParent();
2151
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 // Verify that there isn't already something declared with this name in this
2153 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002154 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002155 // When in C++, we may get a TagDecl with the same name; in this case the
2156 // enum constant will 'hide' the tag.
2157 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2158 "Received TagDecl when not in C++!");
2159 if (!isa<TagDecl>(PrevDecl) &&
2160 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 if (isa<EnumConstantDecl>(PrevDecl))
2162 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2163 else
2164 Diag(IdLoc, diag::err_redefinition, Id->getName());
2165 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002166 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 return 0;
2168 }
2169 }
2170
2171 llvm::APSInt EnumVal(32);
2172 QualType EltTy;
2173 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002174 // Make sure to promote the operand type to int.
2175 UsualUnaryConversions(Val);
2176
Reid Spencer5f016e22007-07-11 17:01:13 +00002177 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2178 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002179 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2181 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002182 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002183 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002184 } else {
2185 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002187 }
2188
2189 if (!Val) {
2190 if (LastEnumConst) {
2191 // Assign the last value + 1.
2192 EnumVal = LastEnumConst->getInitVal();
2193 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002194
2195 // Check for overflow on increment.
2196 if (EnumVal < LastEnumConst->getInitVal())
2197 Diag(IdLoc, diag::warn_enum_value_overflow);
2198
Chris Lattnerb7416f92007-08-27 17:37:24 +00002199 EltTy = LastEnumConst->getType();
2200 } else {
2201 // First value, set to zero.
2202 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002203 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002204 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 }
2206
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002207 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002208 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2209 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002210 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002211
2212 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002213 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 return New;
2215}
2216
Steve Naroff02408c62008-08-07 14:08:16 +00002217// FIXME: For consistency with ActOnFields(), we should have the parser
2218// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002219void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 DeclTy **Elements, unsigned NumElements) {
2221 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002222
Steve Naroff02408c62008-08-07 14:08:16 +00002223 if (Enum && Enum->isDefinition()) {
2224 // Diagnose code like:
2225 // enum e0 {
2226 // E0 = sizeof(enum e0 { E1 })
2227 // };
2228 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2229 Enum->getName());
2230 Diag(EnumLoc, diag::err_previous_definition);
2231 Enum->setInvalidDecl();
2232 return;
2233 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002234 // TODO: If the result value doesn't fit in an int, it must be a long or long
2235 // long value. ISO C does not support this, but GCC does as an extension,
2236 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002237 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002238
Chris Lattnerac609682007-08-28 06:15:15 +00002239 // Verify that all the values are okay, compute the size of the values, and
2240 // reverse the list.
2241 unsigned NumNegativeBits = 0;
2242 unsigned NumPositiveBits = 0;
2243
2244 // Keep track of whether all elements have type int.
2245 bool AllElementsInt = true;
2246
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 EnumConstantDecl *EltList = 0;
2248 for (unsigned i = 0; i != NumElements; ++i) {
2249 EnumConstantDecl *ECD =
2250 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2251 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002252
2253 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002254 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002255 assert(InitVal.getBitWidth() >= IntWidth &&
2256 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002257 if (InitVal.getBitWidth() > IntWidth) {
2258 llvm::APSInt V(InitVal);
2259 V.trunc(IntWidth);
2260 V.extend(InitVal.getBitWidth());
2261 if (V != InitVal)
2262 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
2263 InitVal.toString());
2264 }
Chris Lattnerac609682007-08-28 06:15:15 +00002265
2266 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002267 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002268 NumPositiveBits = std::max(NumPositiveBits,
2269 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002270 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002271 NumNegativeBits = std::max(NumNegativeBits,
2272 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002273
Chris Lattnerac609682007-08-28 06:15:15 +00002274 // Keep track of whether every enum element has type int (very commmon).
2275 if (AllElementsInt)
2276 AllElementsInt = ECD->getType() == Context.IntTy;
2277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278 ECD->setNextDeclarator(EltList);
2279 EltList = ECD;
2280 }
2281
Chris Lattnerac609682007-08-28 06:15:15 +00002282 // Figure out the type that should be used for this enum.
2283 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2284 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002285 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002286
2287 if (NumNegativeBits) {
2288 // If there is a negative value, figure out the smallest integer type (of
2289 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002290 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002291 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002292 BestWidth = IntWidth;
2293 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002294 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002295
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002296 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002297 BestType = Context.LongTy;
2298 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002299 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002300
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002301 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002302 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2303 BestType = Context.LongLongTy;
2304 }
2305 }
2306 } else {
2307 // If there is no negative value, figure out which of uint, ulong, ulonglong
2308 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002309 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002310 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002311 BestWidth = IntWidth;
2312 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002313 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002314 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002315 } else {
2316 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002317 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002318 "How could an initializer get larger than ULL?");
2319 BestType = Context.UnsignedLongLongTy;
2320 }
2321 }
2322
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002323 // Loop over all of the enumerator constants, changing their types to match
2324 // the type of the enum if needed.
2325 for (unsigned i = 0; i != NumElements; ++i) {
2326 EnumConstantDecl *ECD =
2327 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2328 if (!ECD) continue; // Already issued a diagnostic.
2329
2330 // Standard C says the enumerators have int type, but we allow, as an
2331 // extension, the enumerators to be larger than int size. If each
2332 // enumerator value fits in an int, type it as an int, otherwise type it the
2333 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2334 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002335 if (ECD->getType() == Context.IntTy) {
2336 // Make sure the init value is signed.
2337 llvm::APSInt IV = ECD->getInitVal();
2338 IV.setIsSigned(true);
2339 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002340 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002341 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002342
2343 // Determine whether the value fits into an int.
2344 llvm::APSInt InitVal = ECD->getInitVal();
2345 bool FitsInInt;
2346 if (InitVal.isUnsigned() || !InitVal.isNegative())
2347 FitsInInt = InitVal.getActiveBits() < IntWidth;
2348 else
2349 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2350
2351 // If it fits into an integer type, force it. Otherwise force it to match
2352 // the enum decl type.
2353 QualType NewTy;
2354 unsigned NewWidth;
2355 bool NewSign;
2356 if (FitsInInt) {
2357 NewTy = Context.IntTy;
2358 NewWidth = IntWidth;
2359 NewSign = true;
2360 } else if (ECD->getType() == BestType) {
2361 // Already the right type!
2362 continue;
2363 } else {
2364 NewTy = BestType;
2365 NewWidth = BestWidth;
2366 NewSign = BestType->isSignedIntegerType();
2367 }
2368
2369 // Adjust the APSInt value.
2370 InitVal.extOrTrunc(NewWidth);
2371 InitVal.setIsSigned(NewSign);
2372 ECD->setInitVal(InitVal);
2373
2374 // Adjust the Expr initializer and type.
2375 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2376 ECD->setType(NewTy);
2377 }
Chris Lattnerac609682007-08-28 06:15:15 +00002378
Chris Lattnere00b18c2007-08-28 18:24:31 +00002379 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002380 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002381}
2382
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002383Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2384 ExprTy *expr) {
2385 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2386
Chris Lattner8e25d862008-03-16 00:16:02 +00002387 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002388}
2389
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002390Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002391 SourceLocation LBrace,
2392 SourceLocation RBrace,
2393 const char *Lang,
2394 unsigned StrSize,
2395 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002396 LinkageSpecDecl::LanguageIDs Language;
2397 Decl *dcl = static_cast<Decl *>(D);
2398 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2399 Language = LinkageSpecDecl::lang_c;
2400 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2401 Language = LinkageSpecDecl::lang_cxx;
2402 else {
2403 Diag(Loc, diag::err_bad_language);
2404 return 0;
2405 }
2406
2407 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002408 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002409}