blob: 6d8308a882f44bdb99d266dd033b3da598bc79d9 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
Reid Spencer5f016e22007-07-11 17:01:13 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
29 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
30}
31
32void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
38 Decl *D = static_cast<Decl*>(*I);
39 assert(D && "This decl didn't get pushed??");
40 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
42
43 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
59
60 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
70 }
71}
72
73/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
75Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
77 if (II == 0) return 0;
78 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
79
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
86
87 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
104 return 0;
105}
106
107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
180 return New;
181 }
182
183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Narofffb22d962007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
225 if (Old->getStorageClass() != VarDecl::Extern) {
226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
229 return New;
230}
231
232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
Steve Narofff0090632007-09-02 02:04:30 +0000242bool Sema::CheckSingleInitializer(Expr *Init, QualType DeclType) {
243 AssignmentCheckResult result;
244 SourceLocation loc = Init->getLocStart();
245 // Get the type before calling CheckSingleAssignmentConstraints(), since
246 // it can promote the expression.
247 QualType rhsType = Init->getType();
248
249 result = CheckSingleAssignmentConstraints(DeclType, Init);
250
251 // decode the result (notice that extensions still return a type).
252 switch (result) {
253 case Compatible:
254 break;
255 case Incompatible:
256 Diag(loc, diag::err_typecheck_assign_incompatible,
257 DeclType.getAsString(), rhsType.getAsString(),
258 Init->getSourceRange());
259 return true;
260 case PointerFromInt:
261 // check for null pointer constant (C99 6.3.2.3p3)
262 if (!Init->isNullPointerConstant(Context)) {
263 Diag(loc, diag::ext_typecheck_assign_pointer_int,
264 DeclType.getAsString(), rhsType.getAsString(),
265 Init->getSourceRange());
266 return true;
267 }
268 break;
269 case IntFromPointer:
270 Diag(loc, diag::ext_typecheck_assign_pointer_int,
271 DeclType.getAsString(), rhsType.getAsString(),
272 Init->getSourceRange());
273 break;
274 case IncompatiblePointer:
275 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
276 DeclType.getAsString(), rhsType.getAsString(),
277 Init->getSourceRange());
278 break;
279 case CompatiblePointerDiscardsQualifiers:
280 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
281 DeclType.getAsString(), rhsType.getAsString(),
282 Init->getSourceRange());
283 break;
284 }
285 return false;
286}
287
288QualType Sema::CheckInitializer(Expr *Init, QualType DeclType) {
289 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
290 if (!InitList) {
291 return CheckSingleInitializer(Init, DeclType) ? QualType() : DeclType;
292 }
293 // We have an InitListExpr, make sure we set the type.
294 Init->setType(DeclType);
295 // FIXME: Lot of checking still to do...
296 return DeclType;
297}
298
Reid Spencer5f016e22007-07-11 17:01:13 +0000299Sema::DeclTy *
Chris Lattner24c39902007-07-12 00:36:32 +0000300Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 DeclTy *lastDeclarator) {
302 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000303 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000304 IdentifierInfo *II = D.getIdentifier();
305
Chris Lattnere80a59c2007-07-25 00:24:17 +0000306 // All of these full declarators require an identifier. If it doesn't have
307 // one, the ParsedFreeStandingDeclSpec action should be used.
308 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000309 Diag(D.getDeclSpec().getSourceRange().Begin(),
310 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000311 D.getDeclSpec().getSourceRange(), D.getSourceRange());
312 return 0;
313 }
314
Chris Lattner31e05722007-08-26 06:24:45 +0000315 // The scope passed in may not be a decl scope. Zip up the scope tree until
316 // we find one that is.
317 while ((S->getFlags() & Scope::DeclScope) == 0)
318 S = S->getParent();
319
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 // See if this is a redefinition of a variable in the same scope.
321 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
322 D.getIdentifierLoc(), S);
323 if (PrevDecl && !S->isDeclScope(PrevDecl))
324 PrevDecl = 0; // If in outer scope, it isn't the same thing.
325
326 Decl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000327 bool InvalidDecl = false;
328
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000330 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000331 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
332 if (!NewTD) return 0;
333
334 // Handle attributes prior to checking for duplicates in MergeVarDecl
335 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
336 D.getAttributes());
337 // Merge the decl with the existing one if appropriate.
338 if (PrevDecl) {
339 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
340 if (NewTD == 0) return 0;
341 }
342 New = NewTD;
343 if (S->getParent() == 0) {
344 // C99 6.7.7p2: If a typedef name specifies a variably modified type
345 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000346 if (const VariableArrayType *VAT =
347 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
348 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
349 VAT->getSizeExpr()->getSourceRange());
350 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 }
352 }
353 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000354 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroff5912a352007-08-28 20:14:24 +0000355
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000357 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 FunctionDecl::StorageClass SC;
360 switch (D.getDeclSpec().getStorageClassSpec()) {
361 default: assert(0 && "Unknown storage class!");
362 case DeclSpec::SCS_auto:
363 case DeclSpec::SCS_register:
364 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
365 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000366 InvalidDecl = true;
367 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
369 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
370 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
371 }
372
373 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000374 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 LastDeclarator);
376
377 // Merge the decl with the existing one if appropriate.
378 if (PrevDecl) {
379 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
380 if (NewFD == 0) return 0;
381 }
382 New = NewFD;
383 } else {
384 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000385 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000386
387 VarDecl *NewVD;
388 VarDecl::StorageClass SC;
389 switch (D.getDeclSpec().getStorageClassSpec()) {
390 default: assert(0 && "Unknown storage class!");
391 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
392 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
393 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
394 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
395 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
396 }
397 if (S->getParent() == 0) {
398 // File scope. C99 6.9.2p2: A declaration of an identifier for and
399 // object that has file scope without an initializer, and without a
400 // storage-class specifier or with the storage-class specifier "static",
401 // constitutes a tentative definition. Note: A tentative definition with
402 // external linkage is valid (C99 6.2.2p5).
403 if (!Init && SC == VarDecl::Static) {
404 // C99 6.9.2p3: If the declaration of an identifier for an object is
405 // a tentative definition and has internal linkage (C99 6.2.2p3), the
406 // declared type shall not be an incomplete type.
407 if (R->isIncompleteType()) {
408 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
409 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000410 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 }
412 }
413 // C99 6.9p2: The storage-class specifiers auto and register shall not
414 // appear in the declaration specifiers in an external declaration.
415 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
416 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
417 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000418 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 }
Steve Naroffd7444aa2007-08-31 17:20:07 +0000420 if (SC == VarDecl::Static) {
421 // C99 6.7.5.2p2: If an identifier is declared to be an object with
422 // static storage duration, it shall not have a variable length array.
423 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
424 Expr *Size = VLA->getSizeExpr();
425 if (Size || (!Size && !Init)) {
426 // FIXME: Since we don't support initializers yet, we only emit this
427 // error when we don't have an initializer. Once initializers are
428 // implemented, the VLA will change to a CLA.
429 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
430 InvalidDecl = true;
431 }
432 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 }
434 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000435 } else {
436 if (Init) {
437 CheckInitializer(Init, R);
438 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 // Block scope. C99 6.7p7: If an identifier for an object is declared with
440 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
441 if (SC != VarDecl::Extern) {
442 if (R->isIncompleteType()) {
443 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
444 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000445 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 }
447 }
448 if (SC == VarDecl::Static) {
449 // C99 6.7.5.2p2: If an identifier is declared to be an object with
450 // static storage duration, it shall not have a variable length array.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000451 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
452 Expr *Size = VLA->getSizeExpr();
453 if (Size || (!Size && !Init)) {
454 // FIXME: Since we don't support initializers yet, we only emit this
455 // error when we don't have an initializer. Once initializers are
456 // implemented, the VLA will change to a CLA.
457 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff53a32342007-08-28 18:45:29 +0000458 InvalidDecl = true;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000459 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 }
461 }
462 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000463 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
467
468 // Merge the decl with the existing one if appropriate.
469 if (PrevDecl) {
470 NewVD = MergeVarDecl(NewVD, PrevDecl);
471 if (NewVD == 0) return 0;
472 }
Steve Narofff0090632007-09-02 02:04:30 +0000473 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Narofff1120de2007-08-24 22:33:52 +0000474 NewVD->setInit(Init);
475 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 New = NewVD;
477 }
478
479 // If this has an identifier, add it to the scope stack.
480 if (II) {
481 New->setNext(II->getFETokenInfo<Decl>());
482 II->setFETokenInfo(New);
483 S->AddDecl(New);
484 }
485
486 if (S->getParent() == 0)
487 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000488
489 // If any semantic error occurred, mark the decl as invalid.
490 if (D.getInvalidType() || InvalidDecl)
491 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000492
493 return New;
494}
495
496/// The declarators are chained together backwards, reverse the list.
497Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
498 // Often we have single declarators, handle them quickly.
499 Decl *Group = static_cast<Decl*>(group);
500 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
501
502 Decl *NewGroup = 0;
503 while (Group) {
504 Decl *Next = Group->getNextDeclarator();
505 Group->setNextDeclarator(NewGroup);
506 NewGroup = Group;
507 Group = Next;
508 }
509 return NewGroup;
510}
Steve Naroffe1223f72007-08-28 03:03:08 +0000511
512// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000513ParmVarDecl *
514Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
515 Scope *FnScope) {
516 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
517
518 IdentifierInfo *II = PI.Ident;
519 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
520 // Can this happen for params? We already checked that they don't conflict
521 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000522 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 PI.IdentLoc, FnScope)) {
524
525 }
526
527 // FIXME: Handle storage class (auto, register). No declarator?
528 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000529
530 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
531 // Doing the promotion here has a win and a loss. The win is the type for
532 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
533 // code generator). The loss is the orginal type isn't preserved. For example:
534 //
535 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
536 // int blockvardecl[5];
537 // sizeof(parmvardecl); // size == 4
538 // sizeof(blockvardecl); // size == 20
539 // }
540 //
541 // For expressions, all implicit conversions are captured using the
542 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
543 //
544 // FIXME: If a source translation tool needs to see the original type, then
545 // we need to consider storing both types (in ParmVarDecl)...
546 //
547 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
548 if (const ArrayType *AT = parmDeclType->getAsArrayType())
549 parmDeclType = Context.getPointerType(AT->getElementType());
550 else if (parmDeclType->isFunctionType())
551 parmDeclType = Context.getPointerType(parmDeclType);
552
553 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000554 VarDecl::None, 0);
555 if (PI.InvalidType)
556 New->setInvalidDecl();
557
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 // If this has an identifier, add it to the scope stack.
559 if (II) {
560 New->setNext(II->getFETokenInfo<Decl>());
561 II->setFETokenInfo(New);
562 FnScope->AddDecl(New);
563 }
564
565 return New;
566}
567
568
569Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
570 assert(CurFunctionDecl == 0 && "Function parsing confused");
571 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
572 "Not a function declarator!");
573 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
574
575 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
576 // for a K&R function.
577 if (!FTI.hasPrototype) {
578 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
579 if (FTI.ArgInfo[i].TypeInfo == 0) {
580 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
581 FTI.ArgInfo[i].Ident->getName());
582 // Implicitly declare the argument as type 'int' for lack of a better
583 // type.
584 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
585 }
586 }
587
588 // Since this is a function definition, act as though we have information
589 // about the arguments.
590 FTI.hasPrototype = true;
591 } else {
592 // FIXME: Diagnose arguments without names in C.
593
594 }
595
596 Scope *GlobalScope = FnBodyScope->getParent();
597
598 FunctionDecl *FD =
599 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
600 CurFunctionDecl = FD;
601
602 // Create Decl objects for each parameter, adding them to the FunctionDecl.
603 llvm::SmallVector<ParmVarDecl*, 16> Params;
604
605 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
606 // no arguments, not a function that takes a single void argument.
607 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
608 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
609 // empty arg list, don't push any params.
610 } else {
611 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
612 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
613 }
614
615 FD->setParams(&Params[0], Params.size());
616
617 return FD;
618}
619
620Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
621 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
622 FD->setBody((Stmt*)Body);
623
624 assert(FD == CurFunctionDecl && "Function parsing confused");
625 CurFunctionDecl = 0;
626
627 // Verify and clean out per-function state.
628
629 // Check goto/label use.
630 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
631 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
632 // Verify that we have no forward references left. If so, there was a goto
633 // or address of a label taken, but no definition of it. Label fwd
634 // definitions are indicated with a null substmt.
635 if (I->second->getSubStmt() == 0) {
636 LabelStmt *L = I->second;
637 // Emit error.
638 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
639
640 // At this point, we have gotos that use the bogus label. Stitch it into
641 // the function body so that they aren't leaked and that the AST is well
642 // formed.
643 L->setSubStmt(new NullStmt(L->getIdentLoc()));
644 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
645 }
646 }
647 LabelMap.clear();
648
649 return FD;
650}
651
652
653/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
654/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
655Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
656 Scope *S) {
657 if (getLangOptions().C99) // Extension in C99.
658 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
659 else // Legal in C90, but warn about it.
660 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
661
662 // FIXME: handle stuff like:
663 // void foo() { extern float X(); }
664 // void bar() { X(); } <-- implicit decl for X in another scope.
665
666 // Set a Declarator for the implicit definition: int foo();
667 const char *Dummy;
668 DeclSpec DS;
669 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
670 Error = Error; // Silence warning.
671 assert(!Error && "Error setting up implicit decl!");
672 Declarator D(DS, Declarator::BlockContext);
673 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
674 D.SetIdentifier(&II, Loc);
675
676 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000677 if (Scope *FnS = S->getFnParent())
678 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 while (S->getParent())
680 S = S->getParent();
681
682 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
683}
684
685
686TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
687 Decl *LastDeclarator) {
688 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
689
690 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000691 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000692
693 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000694 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
695 T, LastDeclarator);
696 if (D.getInvalidType())
697 NewTD->setInvalidDecl();
698 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000699}
700
701
702/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
703/// former case, Name will be non-null. In the later case, Name will be null.
704/// TagType indicates what kind of tag this is. TK indicates whether this is a
705/// reference/declaration/definition of a tag.
706Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
707 SourceLocation KWLoc, IdentifierInfo *Name,
708 SourceLocation NameLoc, AttributeList *Attr) {
709 // If this is a use of an existing tag, it must have a name.
710 assert((Name != 0 || TK == TK_Definition) &&
711 "Nameless record must be a definition!");
712
713 Decl::Kind Kind;
714 switch (TagType) {
715 default: assert(0 && "Unknown tag type!");
716 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
717 case DeclSpec::TST_union: Kind = Decl::Union; break;
718//case DeclSpec::TST_class: Kind = Decl::Class; break;
719 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
720 }
721
722 // If this is a named struct, check to see if there was a previous forward
723 // declaration or definition.
724 if (TagDecl *PrevDecl =
725 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
726 NameLoc, S))) {
727
728 // If this is a use of a previous tag, or if the tag is already declared in
729 // the same scope (so that the definition/declaration completes or
730 // rementions the tag), reuse the decl.
731 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
732 // Make sure that this wasn't declared as an enum and now used as a struct
733 // or something similar.
734 if (PrevDecl->getKind() != Kind) {
735 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
736 Diag(PrevDecl->getLocation(), diag::err_previous_use);
737 }
738
739 // If this is a use or a forward declaration, we're good.
740 if (TK != TK_Definition)
741 return PrevDecl;
742
743 // Diagnose attempts to redefine a tag.
744 if (PrevDecl->isDefinition()) {
745 Diag(NameLoc, diag::err_redefinition, Name->getName());
746 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
747 // If this is a redefinition, recover by making this struct be
748 // anonymous, which will make any later references get the previous
749 // definition.
750 Name = 0;
751 } else {
752 // Okay, this is definition of a previously declared or referenced tag.
753 // Move the location of the decl to be the definition site.
754 PrevDecl->setLocation(NameLoc);
755 return PrevDecl;
756 }
757 }
758 // If we get here, this is a definition of a new struct type in a nested
759 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
760 // type.
761 }
762
763 // If there is an identifier, use the location of the identifier as the
764 // location of the decl, otherwise use the location of the struct/union
765 // keyword.
766 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
767
768 // Otherwise, if this is the first time we've seen this tag, create the decl.
769 TagDecl *New;
770 switch (Kind) {
771 default: assert(0 && "Unknown tag kind!");
772 case Decl::Enum:
773 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
774 // enum X { A, B, C } D; D should chain to X.
775 New = new EnumDecl(Loc, Name, 0);
776 // If this is an undefined enum, warn.
777 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
778 break;
779 case Decl::Union:
780 case Decl::Struct:
781 case Decl::Class:
782 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
783 // struct X { int A; } D; D should chain to X.
784 New = new RecordDecl(Kind, Loc, Name, 0);
785 break;
786 }
787
788 // If this has an identifier, add it to the scope stack.
789 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000790 // The scope passed in may not be a decl scope. Zip up the scope tree until
791 // we find one that is.
792 while ((S->getFlags() & Scope::DeclScope) == 0)
793 S = S->getParent();
794
795 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 New->setNext(Name->getFETokenInfo<Decl>());
797 Name->setFETokenInfo(New);
798 S->AddDecl(New);
799 }
800
801 return New;
802}
803
804/// ParseField - Each field of a struct/union/class is passed into this in order
805/// to create a FieldDecl object for it.
806Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
807 SourceLocation DeclStart,
808 Declarator &D, ExprTy *BitfieldWidth) {
809 IdentifierInfo *II = D.getIdentifier();
810 Expr *BitWidth = (Expr*)BitfieldWidth;
811
812 SourceLocation Loc = DeclStart;
813 if (II) Loc = D.getIdentifierLoc();
814
815 // FIXME: Unnamed fields can be handled in various different ways, for
816 // example, unnamed unions inject all members into the struct namespace!
817
818
819 if (BitWidth) {
820 // TODO: Validate.
821 //printf("WARNING: BITFIELDS IGNORED!\n");
822
823 // 6.7.2.1p3
824 // 6.7.2.1p4
825
826 } else {
827 // Not a bitfield.
828
829 // validate II.
830
831 }
832
833 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000834 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
835 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +0000836
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 // C99 6.7.2.1p8: A member of a structure or union may have any type other
838 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000839 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
840 Diag(Loc, diag::err_typecheck_illegal_vla,
841 VAT->getSizeExpr()->getSourceRange());
842 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000844 // FIXME: Chain fielddecls together.
Steve Naroff5912a352007-08-28 20:14:24 +0000845 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
846 if (D.getInvalidType() || InvalidDecl)
847 NewFD->setInvalidDecl();
848 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000849}
850
851void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
852 DeclTy **Fields, unsigned NumFields) {
853 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
854 if (Record->isDefinition()) {
855 // Diagnose code like:
856 // struct S { struct S {} X; };
857 // We discover this when we complete the outer S. Reject and ignore the
858 // outer S.
859 Diag(Record->getLocation(), diag::err_nested_redefinition,
860 Record->getKindName());
861 Diag(RecLoc, diag::err_previous_definition);
862 return;
863 }
864
865 // Verify that all the fields are okay.
866 unsigned NumNamedMembers = 0;
867 llvm::SmallVector<FieldDecl*, 32> RecFields;
868 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
869
870 for (unsigned i = 0; i != NumFields; ++i) {
871 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
872 if (!FD) continue; // Already issued a diagnostic.
873
874 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +0000875 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000876
877 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000878 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 Diag(FD->getLocation(), diag::err_field_declared_as_function,
880 FD->getName());
881 delete FD;
882 continue;
883 }
884
885 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
886 if (FDTy->isIncompleteType()) {
887 if (i != NumFields-1 || // ... that the last member ...
888 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +0000889 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
891 delete FD;
892 continue;
893 }
894 if (NumNamedMembers < 1) { //... must have more than named member ...
895 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
896 FD->getName());
897 delete FD;
898 continue;
899 }
900
901 // Okay, we have a legal flexible array member at the end of the struct.
902 Record->setHasFlexibleArrayMember(true);
903 }
904
905
906 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
907 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000908 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
910 // If this is a member of a union, then entire union becomes "flexible".
911 if (Record->getKind() == Decl::Union) {
912 Record->setHasFlexibleArrayMember(true);
913 } else {
914 // If this is a struct/class and this is not the last element, reject
915 // it. Note that GCC supports variable sized arrays in the middle of
916 // structures.
917 if (i != NumFields-1) {
918 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
919 FD->getName());
920 delete FD;
921 continue;
922 }
923
924 // We support flexible arrays at the end of structs in other structs
925 // as an extension.
926 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
927 FD->getName());
928 Record->setHasFlexibleArrayMember(true);
929 }
930 }
931 }
932
933 // Keep track of the number of named members.
934 if (IdentifierInfo *II = FD->getIdentifier()) {
935 // Detect duplicate member names.
936 if (!FieldIDs.insert(II)) {
937 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
938 // Find the previous decl.
939 SourceLocation PrevLoc;
940 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
941 assert(i != e && "Didn't find previous def!");
942 if (RecFields[i]->getIdentifier() == II) {
943 PrevLoc = RecFields[i]->getLocation();
944 break;
945 }
946 }
947 Diag(PrevLoc, diag::err_previous_definition);
948 delete FD;
949 continue;
950 }
951 ++NumNamedMembers;
952 }
953
954 // Remember good fields.
955 RecFields.push_back(FD);
956 }
957
958
959 // Okay, we successfully defined 'Record'.
960 Record->defineBody(&RecFields[0], RecFields.size());
961}
962
963Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
964 DeclTy *lastEnumConst,
965 SourceLocation IdLoc, IdentifierInfo *Id,
966 SourceLocation EqualLoc, ExprTy *val) {
967 theEnumDecl = theEnumDecl; // silence unused warning.
968 EnumConstantDecl *LastEnumConst =
969 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
970 Expr *Val = static_cast<Expr*>(val);
971
Chris Lattner31e05722007-08-26 06:24:45 +0000972 // The scope passed in may not be a decl scope. Zip up the scope tree until
973 // we find one that is.
974 while ((S->getFlags() & Scope::DeclScope) == 0)
975 S = S->getParent();
976
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 // Verify that there isn't already something declared with this name in this
978 // scope.
979 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
980 if (S->isDeclScope(PrevDecl)) {
981 if (isa<EnumConstantDecl>(PrevDecl))
982 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
983 else
984 Diag(IdLoc, diag::err_redefinition, Id->getName());
985 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
986 // FIXME: Don't leak memory: delete Val;
987 return 0;
988 }
989 }
990
991 llvm::APSInt EnumVal(32);
992 QualType EltTy;
993 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +0000994 // Make sure to promote the operand type to int.
995 UsualUnaryConversions(Val);
996
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
998 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +0000999 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1001 Id->getName());
1002 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001003 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001004 } else {
1005 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001007 }
1008
1009 if (!Val) {
1010 if (LastEnumConst) {
1011 // Assign the last value + 1.
1012 EnumVal = LastEnumConst->getInitVal();
1013 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001014
1015 // Check for overflow on increment.
1016 if (EnumVal < LastEnumConst->getInitVal())
1017 Diag(IdLoc, diag::warn_enum_value_overflow);
1018
Chris Lattnerb7416f92007-08-27 17:37:24 +00001019 EltTy = LastEnumConst->getType();
1020 } else {
1021 // First value, set to zero.
1022 EltTy = Context.IntTy;
Chris Lattner421a23d2007-08-27 21:16:18 +00001023 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001024 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 }
1026
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1028 LastEnumConst);
1029
1030 // Register this decl in the current scope stack.
1031 New->setNext(Id->getFETokenInfo<Decl>());
1032 Id->setFETokenInfo(New);
1033 S->AddDecl(New);
1034 return New;
1035}
1036
1037void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1038 DeclTy **Elements, unsigned NumElements) {
1039 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1040 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1041
Chris Lattnere37f0be2007-08-28 05:10:31 +00001042 // TODO: If the result value doesn't fit in an int, it must be a long or long
1043 // long value. ISO C does not support this, but GCC does as an extension,
1044 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001045 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001046
1047
Chris Lattnerac609682007-08-28 06:15:15 +00001048 // Verify that all the values are okay, compute the size of the values, and
1049 // reverse the list.
1050 unsigned NumNegativeBits = 0;
1051 unsigned NumPositiveBits = 0;
1052
1053 // Keep track of whether all elements have type int.
1054 bool AllElementsInt = true;
1055
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 EnumConstantDecl *EltList = 0;
1057 for (unsigned i = 0; i != NumElements; ++i) {
1058 EnumConstantDecl *ECD =
1059 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1060 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001061
1062 // If the enum value doesn't fit in an int, emit an extension warning.
1063 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1064 "Should have promoted value to int");
1065 const llvm::APSInt &InitVal = ECD->getInitVal();
1066 if (InitVal.getBitWidth() > IntWidth) {
1067 llvm::APSInt V(InitVal);
1068 V.trunc(IntWidth);
1069 V.extend(InitVal.getBitWidth());
1070 if (V != InitVal)
1071 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1072 InitVal.toString());
1073 }
Chris Lattnerac609682007-08-28 06:15:15 +00001074
1075 // Keep track of the size of positive and negative values.
1076 if (InitVal.isUnsigned() || !InitVal.isNegative())
1077 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1078 else
1079 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001080
Chris Lattnerac609682007-08-28 06:15:15 +00001081 // Keep track of whether every enum element has type int (very commmon).
1082 if (AllElementsInt)
1083 AllElementsInt = ECD->getType() == Context.IntTy;
1084
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 ECD->setNextDeclarator(EltList);
1086 EltList = ECD;
1087 }
1088
Chris Lattnerac609682007-08-28 06:15:15 +00001089 // Figure out the type that should be used for this enum.
1090 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1091 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001092 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001093
1094 if (NumNegativeBits) {
1095 // If there is a negative value, figure out the smallest integer type (of
1096 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001097 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001098 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001099 BestWidth = IntWidth;
1100 } else {
1101 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1102 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001103 BestType = Context.LongTy;
1104 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001105 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1106 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001107 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1108 BestType = Context.LongLongTy;
1109 }
1110 }
1111 } else {
1112 // If there is no negative value, figure out which of uint, ulong, ulonglong
1113 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001114 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001115 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001116 BestWidth = IntWidth;
1117 } else if (NumPositiveBits <=
1118 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001119 BestType = Context.UnsignedLongTy;
1120 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001121 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1122 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001123 "How could an initializer get larger than ULL?");
1124 BestType = Context.UnsignedLongLongTy;
1125 }
1126 }
1127
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001128 // Loop over all of the enumerator constants, changing their types to match
1129 // the type of the enum if needed.
1130 for (unsigned i = 0; i != NumElements; ++i) {
1131 EnumConstantDecl *ECD =
1132 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1133 if (!ECD) continue; // Already issued a diagnostic.
1134
1135 // Standard C says the enumerators have int type, but we allow, as an
1136 // extension, the enumerators to be larger than int size. If each
1137 // enumerator value fits in an int, type it as an int, otherwise type it the
1138 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1139 // that X has type 'int', not 'unsigned'.
1140 if (ECD->getType() == Context.IntTy)
1141 continue; // Already int type.
1142
1143 // Determine whether the value fits into an int.
1144 llvm::APSInt InitVal = ECD->getInitVal();
1145 bool FitsInInt;
1146 if (InitVal.isUnsigned() || !InitVal.isNegative())
1147 FitsInInt = InitVal.getActiveBits() < IntWidth;
1148 else
1149 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1150
1151 // If it fits into an integer type, force it. Otherwise force it to match
1152 // the enum decl type.
1153 QualType NewTy;
1154 unsigned NewWidth;
1155 bool NewSign;
1156 if (FitsInInt) {
1157 NewTy = Context.IntTy;
1158 NewWidth = IntWidth;
1159 NewSign = true;
1160 } else if (ECD->getType() == BestType) {
1161 // Already the right type!
1162 continue;
1163 } else {
1164 NewTy = BestType;
1165 NewWidth = BestWidth;
1166 NewSign = BestType->isSignedIntegerType();
1167 }
1168
1169 // Adjust the APSInt value.
1170 InitVal.extOrTrunc(NewWidth);
1171 InitVal.setIsSigned(NewSign);
1172 ECD->setInitVal(InitVal);
1173
1174 // Adjust the Expr initializer and type.
1175 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1176 ECD->setType(NewTy);
1177 }
Chris Lattnerac609682007-08-28 06:15:15 +00001178
Chris Lattnere00b18c2007-08-28 18:24:31 +00001179 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001180}
1181
1182void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1183 if (!current) return;
1184
1185 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1186 // remember this in the LastInGroupList list.
1187 if (last)
1188 LastInGroupList.push_back((Decl*)last);
1189}
1190
1191void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1192 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1193 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1194 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1195 if (!newType.isNull()) // install the new vector type into the decl
1196 vDecl->setType(newType);
1197 }
1198 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1199 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1200 rawAttr);
1201 if (!newType.isNull()) // install the new vector type into the decl
1202 tDecl->setUnderlyingType(newType);
1203 }
1204 }
Steve Naroff73322922007-07-18 18:00:27 +00001205 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001206 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1207 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1208 else
Steve Naroff73322922007-07-18 18:00:27 +00001209 Diag(rawAttr->getAttributeLoc(),
1210 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001211 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001212 // FIXME: add other attributes...
1213}
1214
1215void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1216 AttributeList *declarator_postfix) {
1217 while (declspec_prefix) {
1218 HandleDeclAttribute(New, declspec_prefix);
1219 declspec_prefix = declspec_prefix->getNext();
1220 }
1221 while (declarator_postfix) {
1222 HandleDeclAttribute(New, declarator_postfix);
1223 declarator_postfix = declarator_postfix->getNext();
1224 }
1225}
1226
Steve Naroffbea0b342007-07-29 16:33:31 +00001227void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1228 AttributeList *rawAttr) {
1229 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001230 // check the attribute arugments.
1231 if (rawAttr->getNumArgs() != 1) {
1232 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1233 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001234 return;
Steve Naroff73322922007-07-18 18:00:27 +00001235 }
1236 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1237 llvm::APSInt vecSize(32);
1238 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1239 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1240 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001241 return;
Steve Naroff73322922007-07-18 18:00:27 +00001242 }
1243 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1244 // in conjunction with complex types (pointers, arrays, functions, etc.).
1245 Type *canonType = curType.getCanonicalType().getTypePtr();
1246 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1247 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1248 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001249 return;
Steve Naroff73322922007-07-18 18:00:27 +00001250 }
1251 // unlike gcc's vector_size attribute, the size is specified as the
1252 // number of elements, not the number of bytes.
1253 unsigned vectorSize = vecSize.getZExtValue();
1254
1255 if (vectorSize == 0) {
1256 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1257 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001258 return;
Steve Naroff73322922007-07-18 18:00:27 +00001259 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001260 // Instantiate/Install the vector type, the number of elements is > 0.
1261 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1262 // Remember this typedef decl, we will need it later for diagnostics.
1263 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001264}
1265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001267 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 // check the attribute arugments.
1269 if (rawAttr->getNumArgs() != 1) {
1270 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1271 std::string("1"));
1272 return QualType();
1273 }
1274 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1275 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001276 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1278 sizeExpr->getSourceRange());
1279 return QualType();
1280 }
1281 // navigate to the base type - we need to provide for vector pointers,
1282 // vector arrays, and functions returning vectors.
1283 Type *canonType = curType.getCanonicalType().getTypePtr();
1284
Steve Naroff73322922007-07-18 18:00:27 +00001285 if (canonType->isPointerType() || canonType->isArrayType() ||
1286 canonType->isFunctionType()) {
1287 assert(1 && "HandleVector(): Complex type construction unimplemented");
1288 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1289 do {
1290 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1291 canonType = PT->getPointeeType().getTypePtr();
1292 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1293 canonType = AT->getElementType().getTypePtr();
1294 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1295 canonType = FT->getResultType().getTypePtr();
1296 } while (canonType->isPointerType() || canonType->isArrayType() ||
1297 canonType->isFunctionType());
1298 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 }
1300 // the base type must be integer or float.
1301 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1302 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1303 curType.getCanonicalType().getAsString());
1304 return QualType();
1305 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001306 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 // vecSize is specified in bytes - convert to bits.
1308 unsigned vectorSize = vecSize.getZExtValue() * 8;
1309
1310 // the vector size needs to be an integral multiple of the type size.
1311 if (vectorSize % typeSize) {
1312 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1313 sizeExpr->getSourceRange());
1314 return QualType();
1315 }
1316 if (vectorSize == 0) {
1317 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1318 sizeExpr->getSourceRange());
1319 return QualType();
1320 }
1321 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1322 // the number of elements to be a power of two (unlike GCC).
1323 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001324 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001325}
1326