blob: f1a6e78b6a8fb1b74df99f62d307874c182261b3 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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
28// C99: 6.7.5p3: Used by ParseDeclarator/ParseField to make sure we have
29// a constant expression of type int with a value greater than zero.
30bool Sema::VerifyConstantArrayType(const ArrayType *Array,
31 SourceLocation DeclLoc) {
Steve Naroff83c13012007-08-30 01:06:46 +000032 if (const VariableArrayType *VLA = dyn_cast<VariableArrayType>(Array)) {
33 Expr *Size = VLA->getSizeExpr();
34 if (Size == 0)
35 return false; // incomplete type.
Chris Lattner4b009652007-07-25 00:24:17 +000036
Steve Naroff83c13012007-08-30 01:06:46 +000037 if (!Size->getType()->isIntegerType()) {
38 Diag(Size->getLocStart(), diag::err_array_size_non_int,
39 Size->getType().getAsString(), Size->getSourceRange());
40 return false;
41 }
42 // FIXME: I don't think this is needed. It remains to keep test
43 // builtin_classify_type() happy...will revisit soon (today is 8/29/07:-)
44 SourceLocation Loc;
45 llvm::APSInt SizeVal(32);
46 if (!Size->isIntegerConstantExpr(SizeVal, Context, &Loc)) {
47 // FIXME: This emits the diagnostic to enforce 6.7.2.1p8, but the message
48 // is wrong. It is also wrong for static variables.
49 // FIXME: This is also wrong for:
50 // int sub1(int i, char *pi) { typedef int foo[i];
51 // struct bar {foo f1; int f2:3; int f3:4} *p; }
52 Diag(DeclLoc, diag::err_typecheck_illegal_vla, Size->getSourceRange());
53 return false;
54 }
Chris Lattner4b009652007-07-25 00:24:17 +000055 return true;
56 }
Steve Naroff83c13012007-08-30 01:06:46 +000057 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Array);
Chris Lattner4b009652007-07-25 00:24:17 +000058
Steve Naroff83c13012007-08-30 01:06:46 +000059 assert(CAT && "Sema::VerifyConstantArrayType(): Illegal array type");
Chris Lattner4b009652007-07-25 00:24:17 +000060
Steve Naroff83c13012007-08-30 01:06:46 +000061 llvm::APSInt SizeVal(32);
62 SizeVal = CAT->getSize();
63
Chris Lattner4b009652007-07-25 00:24:17 +000064 // We have a constant expression with an integer type, now make sure
65 // value greater than zero (C99 6.7.5.2p1).
66
67 // FIXME: This check isn't specific to static VLAs, this should be moved
68 // elsewhere or replicated. 'int X[-1];' inside a function should emit an
69 // error.
70 if (SizeVal.isSigned()) {
71 llvm::APSInt Zero(SizeVal.getBitWidth());
72 Zero.setIsUnsigned(false);
73 if (SizeVal < Zero) {
Steve Naroff83c13012007-08-30 01:06:46 +000074 Diag(DeclLoc, diag::err_typecheck_negative_array_size);
Chris Lattner4b009652007-07-25 00:24:17 +000075 return true;
76 } else if (SizeVal == 0) {
77 // GCC accepts zero sized static arrays.
Steve Naroff83c13012007-08-30 01:06:46 +000078 Diag(DeclLoc, diag::err_typecheck_zero_array_size);
Chris Lattner4b009652007-07-25 00:24:17 +000079 }
80 }
81 return false;
82}
83
84Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
85 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
86}
87
88void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000089 if (S->decl_empty()) return;
90 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
91
Chris Lattner4b009652007-07-25 00:24:17 +000092 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
93 I != E; ++I) {
94 Decl *D = static_cast<Decl*>(*I);
95 assert(D && "This decl didn't get pushed??");
96 IdentifierInfo *II = D->getIdentifier();
97 if (!II) continue;
98
99 // Unlink this decl from the identifier. Because the scope contains decls
100 // in an unordered collection, and because we have multiple identifier
101 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
102 if (II->getFETokenInfo<Decl>() == D) {
103 // Normal case, no multiple decls in different namespaces.
104 II->setFETokenInfo(D->getNext());
105 } else {
106 // Scan ahead. There are only three namespaces in C, so this loop can
107 // never execute more than 3 times.
108 Decl *SomeDecl = II->getFETokenInfo<Decl>();
109 while (SomeDecl->getNext() != D) {
110 SomeDecl = SomeDecl->getNext();
111 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
112 }
113 SomeDecl->setNext(D->getNext());
114 }
115
116 // This will have to be revisited for C++: there we want to nest stuff in
117 // namespace decls etc. Even for C, we might want a top-level translation
118 // unit decl or something.
119 if (!CurFunctionDecl)
120 continue;
121
122 // Chain this decl to the containing function, it now owns the memory for
123 // the decl.
124 D->setNext(CurFunctionDecl->getDeclChain());
125 CurFunctionDecl->setDeclChain(D);
126 }
127}
128
129/// LookupScopedDecl - Look up the inner-most declaration in the specified
130/// namespace.
131Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
132 SourceLocation IdLoc, Scope *S) {
133 if (II == 0) return 0;
134 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
135
136 // Scan up the scope chain looking for a decl that matches this identifier
137 // that is in the appropriate namespace. This search should not take long, as
138 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
139 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
140 if (D->getIdentifierNamespace() == NS)
141 return D;
142
143 // If we didn't find a use of this identifier, and if the identifier
144 // corresponds to a compiler builtin, create the decl object for the builtin
145 // now, injecting it into translation unit scope, and return it.
146 if (NS == Decl::IDNS_Ordinary) {
147 // If this is a builtin on some other target, or if this builtin varies
148 // across targets (e.g. in type), emit a diagnostic and mark the translation
149 // unit non-portable for using it.
150 if (II->isNonPortableBuiltin()) {
151 // Only emit this diagnostic once for this builtin.
152 II->setNonPortableBuiltin(false);
153 Context.Target.DiagnoseNonPortability(IdLoc,
154 diag::port_target_builtin_use);
155 }
156 // If this is a builtin on this (or all) targets, create the decl.
157 if (unsigned BuiltinID = II->getBuiltinID())
158 return LazilyCreateBuiltin(II, BuiltinID, S);
159 }
160 return 0;
161}
162
163/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
164/// lazily create a decl for it.
165Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
166 Builtin::ID BID = (Builtin::ID)bid;
167
168 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
169 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000170 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000171
172 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000173 if (Scope *FnS = S->getFnParent())
174 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000175 while (S->getParent())
176 S = S->getParent();
177 S->AddDecl(New);
178
179 // Add this decl to the end of the identifier info.
180 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
181 // Scan until we find the last (outermost) decl in the id chain.
182 while (LastDecl->getNext())
183 LastDecl = LastDecl->getNext();
184 // Insert before (outside) it.
185 LastDecl->setNext(New);
186 } else {
187 II->setFETokenInfo(New);
188 }
189 // Make sure clients iterating over decls see this.
190 LastInGroupList.push_back(New);
191
192 return New;
193}
194
195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
209 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
210 // TODO: This is totally simplistic. It should handle merging functions
211 // together etc, merging extern int X; int X; ...
212 Diag(New->getLocation(), diag::err_redefinition, New->getName());
213 Diag(Old->getLocation(), diag::err_previous_definition);
214 return New;
215}
216
217/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
218/// and scope as a previous declaration 'Old'. Figure out how to resolve this
219/// situation, merging decls or emitting diagnostics as appropriate.
220///
221FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
222 // Verify the old decl was also a function.
223 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
224 if (!Old) {
225 Diag(New->getLocation(), diag::err_redefinition_different_kind,
226 New->getName());
227 Diag(OldD->getLocation(), diag::err_previous_definition);
228 return New;
229 }
230
231 // This is not right, but it's a start. If 'Old' is a function prototype with
232 // the same type as 'New', silently allow this. FIXME: We should link up decl
233 // objects here.
234 if (Old->getBody() == 0 &&
235 Old->getCanonicalType() == New->getCanonicalType()) {
236 return New;
237 }
238
239 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
240 // TODO: This is totally simplistic. It should handle merging functions
241 // together etc, merging extern int X; int X; ...
242 Diag(New->getLocation(), diag::err_redefinition, New->getName());
243 Diag(Old->getLocation(), diag::err_previous_definition);
244 return New;
245}
246
247/// MergeVarDecl - We just parsed a variable 'New' which has the same name
248/// and scope as a previous declaration 'Old'. Figure out how to resolve this
249/// situation, merging decls or emitting diagnostics as appropriate.
250///
251/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
252/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
253///
254VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
255 // Verify the old decl was also a variable.
256 VarDecl *Old = dyn_cast<VarDecl>(OldD);
257 if (!Old) {
258 Diag(New->getLocation(), diag::err_redefinition_different_kind,
259 New->getName());
260 Diag(OldD->getLocation(), diag::err_previous_definition);
261 return New;
262 }
Steve Naroff83c13012007-08-30 01:06:46 +0000263 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
264 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
265 bool OldIsTentative = false;
266
267 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
268 // Handle C "tentative" external object definitions. FIXME: finish!
269 if (!OldFSDecl->getInit() &&
270 (OldFSDecl->getStorageClass() == VarDecl::None ||
271 OldFSDecl->getStorageClass() == VarDecl::Static))
272 OldIsTentative = true;
273 }
Chris Lattner4b009652007-07-25 00:24:17 +0000274 // Verify the types match.
275 if (Old->getCanonicalType() != New->getCanonicalType()) {
276 Diag(New->getLocation(), diag::err_redefinition, New->getName());
277 Diag(Old->getLocation(), diag::err_previous_definition);
278 return New;
279 }
280 // We've verified the types match, now check if Old is "extern".
281 if (Old->getStorageClass() != VarDecl::Extern) {
282 Diag(New->getLocation(), diag::err_redefinition, New->getName());
283 Diag(Old->getLocation(), diag::err_previous_definition);
284 }
285 return New;
286}
287
288/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
289/// no declarator (e.g. "struct foo;") is parsed.
290Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
291 // TODO: emit error on 'int;' or 'const enum foo;'.
292 // TODO: emit error on 'typedef int;'
293 // if (!DS.isMissingDeclaratorOk()) Diag(...);
294
295 return 0;
296}
297
298Sema::DeclTy *
299Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
300 DeclTy *lastDeclarator) {
301 Decl *LastDeclarator = (Decl*)lastDeclarator;
302 Expr *Init = static_cast<Expr*>(init);
303 IdentifierInfo *II = D.getIdentifier();
304
305 // All of these full declarators require an identifier. If it doesn't have
306 // one, the ParsedFreeStandingDeclSpec action should be used.
307 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000308 Diag(D.getDeclSpec().getSourceRange().Begin(),
309 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000310 D.getDeclSpec().getSourceRange(), D.getSourceRange());
311 return 0;
312 }
313
Chris Lattnera7549902007-08-26 06:24:45 +0000314 // The scope passed in may not be a decl scope. Zip up the scope tree until
315 // we find one that is.
316 while ((S->getFlags() & Scope::DeclScope) == 0)
317 S = S->getParent();
318
Chris Lattner4b009652007-07-25 00:24:17 +0000319 // See if this is a redefinition of a variable in the same scope.
320 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
321 D.getIdentifierLoc(), S);
322 if (PrevDecl && !S->isDeclScope(PrevDecl))
323 PrevDecl = 0; // If in outer scope, it isn't the same thing.
324
325 Decl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000326 bool InvalidDecl = false;
327
Chris Lattner4b009652007-07-25 00:24:17 +0000328 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
329 assert(Init == 0 && "Can't have initializer for a typedef!");
330 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
331 if (!NewTD) return 0;
332
333 // Handle attributes prior to checking for duplicates in MergeVarDecl
334 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
335 D.getAttributes());
336 // Merge the decl with the existing one if appropriate.
337 if (PrevDecl) {
338 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
339 if (NewTD == 0) return 0;
340 }
341 New = NewTD;
342 if (S->getParent() == 0) {
343 // C99 6.7.7p2: If a typedef name specifies a variably modified type
344 // then it shall have block scope.
345 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
346 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000347 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000348 }
349 }
350 } else if (D.isFunctionDeclarator()) {
351 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000352
Chris Lattner4b009652007-07-25 00:24:17 +0000353 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000354 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000355
356 FunctionDecl::StorageClass SC;
357 switch (D.getDeclSpec().getStorageClassSpec()) {
358 default: assert(0 && "Unknown storage class!");
359 case DeclSpec::SCS_auto:
360 case DeclSpec::SCS_register:
361 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
362 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000363 InvalidDecl = true;
364 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000365 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
366 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
367 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
368 }
369
370 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000371 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000372 LastDeclarator);
373
374 // Merge the decl with the existing one if appropriate.
375 if (PrevDecl) {
376 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
377 if (NewFD == 0) return 0;
378 }
379 New = NewFD;
380 } else {
381 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000382 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000383
384 VarDecl *NewVD;
385 VarDecl::StorageClass SC;
386 switch (D.getDeclSpec().getStorageClassSpec()) {
387 default: assert(0 && "Unknown storage class!");
388 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
389 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
390 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
391 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
392 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
393 }
394 if (S->getParent() == 0) {
395 // File scope. C99 6.9.2p2: A declaration of an identifier for and
396 // object that has file scope without an initializer, and without a
397 // storage-class specifier or with the storage-class specifier "static",
398 // constitutes a tentative definition. Note: A tentative definition with
399 // external linkage is valid (C99 6.2.2p5).
400 if (!Init && SC == VarDecl::Static) {
401 // C99 6.9.2p3: If the declaration of an identifier for an object is
402 // a tentative definition and has internal linkage (C99 6.2.2p3), the
403 // declared type shall not be an incomplete type.
404 if (R->isIncompleteType()) {
405 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
406 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000407 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000408 }
409 }
410 // C99 6.9p2: The storage-class specifiers auto and register shall not
411 // appear in the declaration specifiers in an external declaration.
412 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
413 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
414 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000415 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000416 }
417 // C99 6.7.5.2p2: If an identifier is declared to be an object with
418 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000419 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000420 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcae537d2007-08-28 18:45:29 +0000421 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000422 }
423 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
424 } else {
425 // Block scope. C99 6.7p7: If an identifier for an object is declared with
426 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
427 if (SC != VarDecl::Extern) {
428 if (R->isIncompleteType()) {
429 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
430 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000431 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000432 }
433 }
434 if (SC == VarDecl::Static) {
435 // C99 6.7.5.2p2: If an identifier is declared to be an object with
436 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000437 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000438 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcae537d2007-08-28 18:45:29 +0000439 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000440 }
441 }
442 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000443 }
Chris Lattner4b009652007-07-25 00:24:17 +0000444 // Handle attributes prior to checking for duplicates in MergeVarDecl
445 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
446 D.getAttributes());
447
448 // Merge the decl with the existing one if appropriate.
449 if (PrevDecl) {
450 NewVD = MergeVarDecl(NewVD, PrevDecl);
451 if (NewVD == 0) return 0;
452 }
Steve Naroff0f32f432007-08-24 22:33:52 +0000453 if (Init) {
454 AssignmentCheckResult result;
455 result = CheckSingleAssignmentConstraints(R, Init);
456 // FIXME: emit errors if appropriate.
457 NewVD->setInit(Init);
458 }
Chris Lattner4b009652007-07-25 00:24:17 +0000459 New = NewVD;
460 }
461
462 // If this has an identifier, add it to the scope stack.
463 if (II) {
464 New->setNext(II->getFETokenInfo<Decl>());
465 II->setFETokenInfo(New);
466 S->AddDecl(New);
467 }
468
469 if (S->getParent() == 0)
470 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000471
472 // If any semantic error occurred, mark the decl as invalid.
473 if (D.getInvalidType() || InvalidDecl)
474 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000475
476 return New;
477}
478
479/// The declarators are chained together backwards, reverse the list.
480Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
481 // Often we have single declarators, handle them quickly.
482 Decl *Group = static_cast<Decl*>(group);
483 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
484
485 Decl *NewGroup = 0;
486 while (Group) {
487 Decl *Next = Group->getNextDeclarator();
488 Group->setNextDeclarator(NewGroup);
489 NewGroup = Group;
490 Group = Next;
491 }
492 return NewGroup;
493}
Steve Naroff91b03f72007-08-28 03:03:08 +0000494
495// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000496ParmVarDecl *
497Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
498 Scope *FnScope) {
499 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
500
501 IdentifierInfo *II = PI.Ident;
502 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
503 // Can this happen for params? We already checked that they don't conflict
504 // among each other. Here they can only shadow globals, which is ok.
505 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
506 PI.IdentLoc, FnScope)) {
507
508 }
509
510 // FIXME: Handle storage class (auto, register). No declarator?
511 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000512
513 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
514 // Doing the promotion here has a win and a loss. The win is the type for
515 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
516 // code generator). The loss is the orginal type isn't preserved. For example:
517 //
518 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
519 // int blockvardecl[5];
520 // sizeof(parmvardecl); // size == 4
521 // sizeof(blockvardecl); // size == 20
522 // }
523 //
524 // For expressions, all implicit conversions are captured using the
525 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
526 //
527 // FIXME: If a source translation tool needs to see the original type, then
528 // we need to consider storing both types (in ParmVarDecl)...
529 //
530 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
531 if (const ArrayType *AT = parmDeclType->getAsArrayType())
532 parmDeclType = Context.getPointerType(AT->getElementType());
533 else if (parmDeclType->isFunctionType())
534 parmDeclType = Context.getPointerType(parmDeclType);
535
536 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000537 VarDecl::None, 0);
538 if (PI.InvalidType)
539 New->setInvalidDecl();
540
Chris Lattner4b009652007-07-25 00:24:17 +0000541 // If this has an identifier, add it to the scope stack.
542 if (II) {
543 New->setNext(II->getFETokenInfo<Decl>());
544 II->setFETokenInfo(New);
545 FnScope->AddDecl(New);
546 }
547
548 return New;
549}
550
551
552Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
553 assert(CurFunctionDecl == 0 && "Function parsing confused");
554 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
555 "Not a function declarator!");
556 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
557
558 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
559 // for a K&R function.
560 if (!FTI.hasPrototype) {
561 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
562 if (FTI.ArgInfo[i].TypeInfo == 0) {
563 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
564 FTI.ArgInfo[i].Ident->getName());
565 // Implicitly declare the argument as type 'int' for lack of a better
566 // type.
567 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
568 }
569 }
570
571 // Since this is a function definition, act as though we have information
572 // about the arguments.
573 FTI.hasPrototype = true;
574 } else {
575 // FIXME: Diagnose arguments without names in C.
576
577 }
578
579 Scope *GlobalScope = FnBodyScope->getParent();
580
581 FunctionDecl *FD =
582 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
583 CurFunctionDecl = FD;
584
585 // Create Decl objects for each parameter, adding them to the FunctionDecl.
586 llvm::SmallVector<ParmVarDecl*, 16> Params;
587
588 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
589 // no arguments, not a function that takes a single void argument.
590 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
591 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
592 // empty arg list, don't push any params.
593 } else {
594 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
595 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
596 }
597
598 FD->setParams(&Params[0], Params.size());
599
600 return FD;
601}
602
603Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
604 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
605 FD->setBody((Stmt*)Body);
606
607 assert(FD == CurFunctionDecl && "Function parsing confused");
608 CurFunctionDecl = 0;
609
610 // Verify and clean out per-function state.
611
612 // Check goto/label use.
613 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
614 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
615 // Verify that we have no forward references left. If so, there was a goto
616 // or address of a label taken, but no definition of it. Label fwd
617 // definitions are indicated with a null substmt.
618 if (I->second->getSubStmt() == 0) {
619 LabelStmt *L = I->second;
620 // Emit error.
621 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
622
623 // At this point, we have gotos that use the bogus label. Stitch it into
624 // the function body so that they aren't leaked and that the AST is well
625 // formed.
626 L->setSubStmt(new NullStmt(L->getIdentLoc()));
627 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
628 }
629 }
630 LabelMap.clear();
631
632 return FD;
633}
634
635
636/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
637/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
638Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
639 Scope *S) {
640 if (getLangOptions().C99) // Extension in C99.
641 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
642 else // Legal in C90, but warn about it.
643 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
644
645 // FIXME: handle stuff like:
646 // void foo() { extern float X(); }
647 // void bar() { X(); } <-- implicit decl for X in another scope.
648
649 // Set a Declarator for the implicit definition: int foo();
650 const char *Dummy;
651 DeclSpec DS;
652 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
653 Error = Error; // Silence warning.
654 assert(!Error && "Error setting up implicit decl!");
655 Declarator D(DS, Declarator::BlockContext);
656 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
657 D.SetIdentifier(&II, Loc);
658
659 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000660 if (Scope *FnS = S->getFnParent())
661 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000662 while (S->getParent())
663 S = S->getParent();
664
665 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
666}
667
668
669TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
670 Decl *LastDeclarator) {
671 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
672
673 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000674 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000675
676 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000677 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
678 T, LastDeclarator);
679 if (D.getInvalidType())
680 NewTD->setInvalidDecl();
681 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000682}
683
684
685/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
686/// former case, Name will be non-null. In the later case, Name will be null.
687/// TagType indicates what kind of tag this is. TK indicates whether this is a
688/// reference/declaration/definition of a tag.
689Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
690 SourceLocation KWLoc, IdentifierInfo *Name,
691 SourceLocation NameLoc, AttributeList *Attr) {
692 // If this is a use of an existing tag, it must have a name.
693 assert((Name != 0 || TK == TK_Definition) &&
694 "Nameless record must be a definition!");
695
696 Decl::Kind Kind;
697 switch (TagType) {
698 default: assert(0 && "Unknown tag type!");
699 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
700 case DeclSpec::TST_union: Kind = Decl::Union; break;
701//case DeclSpec::TST_class: Kind = Decl::Class; break;
702 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
703 }
704
705 // If this is a named struct, check to see if there was a previous forward
706 // declaration or definition.
707 if (TagDecl *PrevDecl =
708 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
709 NameLoc, S))) {
710
711 // If this is a use of a previous tag, or if the tag is already declared in
712 // the same scope (so that the definition/declaration completes or
713 // rementions the tag), reuse the decl.
714 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
715 // Make sure that this wasn't declared as an enum and now used as a struct
716 // or something similar.
717 if (PrevDecl->getKind() != Kind) {
718 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
719 Diag(PrevDecl->getLocation(), diag::err_previous_use);
720 }
721
722 // If this is a use or a forward declaration, we're good.
723 if (TK != TK_Definition)
724 return PrevDecl;
725
726 // Diagnose attempts to redefine a tag.
727 if (PrevDecl->isDefinition()) {
728 Diag(NameLoc, diag::err_redefinition, Name->getName());
729 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
730 // If this is a redefinition, recover by making this struct be
731 // anonymous, which will make any later references get the previous
732 // definition.
733 Name = 0;
734 } else {
735 // Okay, this is definition of a previously declared or referenced tag.
736 // Move the location of the decl to be the definition site.
737 PrevDecl->setLocation(NameLoc);
738 return PrevDecl;
739 }
740 }
741 // If we get here, this is a definition of a new struct type in a nested
742 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
743 // type.
744 }
745
746 // If there is an identifier, use the location of the identifier as the
747 // location of the decl, otherwise use the location of the struct/union
748 // keyword.
749 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
750
751 // Otherwise, if this is the first time we've seen this tag, create the decl.
752 TagDecl *New;
753 switch (Kind) {
754 default: assert(0 && "Unknown tag kind!");
755 case Decl::Enum:
756 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
757 // enum X { A, B, C } D; D should chain to X.
758 New = new EnumDecl(Loc, Name, 0);
759 // If this is an undefined enum, warn.
760 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
761 break;
762 case Decl::Union:
763 case Decl::Struct:
764 case Decl::Class:
765 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
766 // struct X { int A; } D; D should chain to X.
767 New = new RecordDecl(Kind, Loc, Name, 0);
768 break;
769 }
770
771 // If this has an identifier, add it to the scope stack.
772 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000773 // The scope passed in may not be a decl scope. Zip up the scope tree until
774 // we find one that is.
775 while ((S->getFlags() & Scope::DeclScope) == 0)
776 S = S->getParent();
777
778 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000779 New->setNext(Name->getFETokenInfo<Decl>());
780 Name->setFETokenInfo(New);
781 S->AddDecl(New);
782 }
783
784 return New;
785}
786
787/// ParseField - Each field of a struct/union/class is passed into this in order
788/// to create a FieldDecl object for it.
789Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
790 SourceLocation DeclStart,
791 Declarator &D, ExprTy *BitfieldWidth) {
792 IdentifierInfo *II = D.getIdentifier();
793 Expr *BitWidth = (Expr*)BitfieldWidth;
794
795 SourceLocation Loc = DeclStart;
796 if (II) Loc = D.getIdentifierLoc();
797
798 // FIXME: Unnamed fields can be handled in various different ways, for
799 // example, unnamed unions inject all members into the struct namespace!
800
801
802 if (BitWidth) {
803 // TODO: Validate.
804 //printf("WARNING: BITFIELDS IGNORED!\n");
805
806 // 6.7.2.1p3
807 // 6.7.2.1p4
808
809 } else {
810 // Not a bitfield.
811
812 // validate II.
813
814 }
815
816 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000817 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
818 bool InvalidDecl = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000819
820 // C99 6.7.2.1p8: A member of a structure or union may have any type other
821 // than a variably modified type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000822 if (const ArrayType *ary = T->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000823 if (VerifyConstantArrayType(ary, Loc))
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000824 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000825 }
826
827 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000828 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
829 if (D.getInvalidType() || InvalidDecl)
830 NewFD->setInvalidDecl();
831 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +0000832}
833
834void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
835 DeclTy **Fields, unsigned NumFields) {
836 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
837 if (Record->isDefinition()) {
838 // Diagnose code like:
839 // struct S { struct S {} X; };
840 // We discover this when we complete the outer S. Reject and ignore the
841 // outer S.
842 Diag(Record->getLocation(), diag::err_nested_redefinition,
843 Record->getKindName());
844 Diag(RecLoc, diag::err_previous_definition);
845 return;
846 }
847
848 // Verify that all the fields are okay.
849 unsigned NumNamedMembers = 0;
850 llvm::SmallVector<FieldDecl*, 32> RecFields;
851 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
852
853 for (unsigned i = 0; i != NumFields; ++i) {
854 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
855 if (!FD) continue; // Already issued a diagnostic.
856
857 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +0000858 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000861 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000862 Diag(FD->getLocation(), diag::err_field_declared_as_function,
863 FD->getName());
864 delete FD;
865 continue;
866 }
867
868 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
869 if (FDTy->isIncompleteType()) {
870 if (i != NumFields-1 || // ... that the last member ...
871 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +0000872 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +0000873 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
874 delete FD;
875 continue;
876 }
877 if (NumNamedMembers < 1) { //... must have more than named member ...
878 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
879 FD->getName());
880 delete FD;
881 continue;
882 }
883
884 // Okay, we have a legal flexible array member at the end of the struct.
885 Record->setHasFlexibleArrayMember(true);
886 }
887
888
889 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
890 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000891 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000892 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
893 // If this is a member of a union, then entire union becomes "flexible".
894 if (Record->getKind() == Decl::Union) {
895 Record->setHasFlexibleArrayMember(true);
896 } else {
897 // If this is a struct/class and this is not the last element, reject
898 // it. Note that GCC supports variable sized arrays in the middle of
899 // structures.
900 if (i != NumFields-1) {
901 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
902 FD->getName());
903 delete FD;
904 continue;
905 }
906
907 // We support flexible arrays at the end of structs in other structs
908 // as an extension.
909 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
910 FD->getName());
911 Record->setHasFlexibleArrayMember(true);
912 }
913 }
914 }
915
916 // Keep track of the number of named members.
917 if (IdentifierInfo *II = FD->getIdentifier()) {
918 // Detect duplicate member names.
919 if (!FieldIDs.insert(II)) {
920 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
921 // Find the previous decl.
922 SourceLocation PrevLoc;
923 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
924 assert(i != e && "Didn't find previous def!");
925 if (RecFields[i]->getIdentifier() == II) {
926 PrevLoc = RecFields[i]->getLocation();
927 break;
928 }
929 }
930 Diag(PrevLoc, diag::err_previous_definition);
931 delete FD;
932 continue;
933 }
934 ++NumNamedMembers;
935 }
936
937 // Remember good fields.
938 RecFields.push_back(FD);
939 }
940
941
942 // Okay, we successfully defined 'Record'.
943 Record->defineBody(&RecFields[0], RecFields.size());
944}
945
946Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
947 DeclTy *lastEnumConst,
948 SourceLocation IdLoc, IdentifierInfo *Id,
949 SourceLocation EqualLoc, ExprTy *val) {
950 theEnumDecl = theEnumDecl; // silence unused warning.
951 EnumConstantDecl *LastEnumConst =
952 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
953 Expr *Val = static_cast<Expr*>(val);
954
Chris Lattnera7549902007-08-26 06:24:45 +0000955 // The scope passed in may not be a decl scope. Zip up the scope tree until
956 // we find one that is.
957 while ((S->getFlags() & Scope::DeclScope) == 0)
958 S = S->getParent();
959
Chris Lattner4b009652007-07-25 00:24:17 +0000960 // Verify that there isn't already something declared with this name in this
961 // scope.
962 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
963 if (S->isDeclScope(PrevDecl)) {
964 if (isa<EnumConstantDecl>(PrevDecl))
965 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
966 else
967 Diag(IdLoc, diag::err_redefinition, Id->getName());
968 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
969 // FIXME: Don't leak memory: delete Val;
970 return 0;
971 }
972 }
973
974 llvm::APSInt EnumVal(32);
975 QualType EltTy;
976 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +0000977 // Make sure to promote the operand type to int.
978 UsualUnaryConversions(Val);
979
Chris Lattner4b009652007-07-25 00:24:17 +0000980 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
981 SourceLocation ExpLoc;
982 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
983 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
984 Id->getName());
985 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +0000986 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +0000987 } else {
988 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
Chris Lattnere7f53a42007-08-27 17:37:24 +0000990 }
991
992 if (!Val) {
993 if (LastEnumConst) {
994 // Assign the last value + 1.
995 EnumVal = LastEnumConst->getInitVal();
996 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +0000997
998 // Check for overflow on increment.
999 if (EnumVal < LastEnumConst->getInitVal())
1000 Diag(IdLoc, diag::warn_enum_value_overflow);
1001
Chris Lattnere7f53a42007-08-27 17:37:24 +00001002 EltTy = LastEnumConst->getType();
1003 } else {
1004 // First value, set to zero.
1005 EltTy = Context.IntTy;
Chris Lattner2cda8792007-08-27 21:16:18 +00001006 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001007 }
Chris Lattner4b009652007-07-25 00:24:17 +00001008 }
1009
Chris Lattner4b009652007-07-25 00:24:17 +00001010 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1011 LastEnumConst);
1012
1013 // Register this decl in the current scope stack.
1014 New->setNext(Id->getFETokenInfo<Decl>());
1015 Id->setFETokenInfo(New);
1016 S->AddDecl(New);
1017 return New;
1018}
1019
1020void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1021 DeclTy **Elements, unsigned NumElements) {
1022 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1023 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1024
Chris Lattner435c3fd2007-08-28 05:10:31 +00001025 // TODO: If the result value doesn't fit in an int, it must be a long or long
1026 // long value. ISO C does not support this, but GCC does as an extension,
1027 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001028 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001029
1030
Chris Lattner206754a2007-08-28 06:15:15 +00001031 // Verify that all the values are okay, compute the size of the values, and
1032 // reverse the list.
1033 unsigned NumNegativeBits = 0;
1034 unsigned NumPositiveBits = 0;
1035
1036 // Keep track of whether all elements have type int.
1037 bool AllElementsInt = true;
1038
Chris Lattner4b009652007-07-25 00:24:17 +00001039 EnumConstantDecl *EltList = 0;
1040 for (unsigned i = 0; i != NumElements; ++i) {
1041 EnumConstantDecl *ECD =
1042 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1043 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001044
1045 // If the enum value doesn't fit in an int, emit an extension warning.
1046 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1047 "Should have promoted value to int");
1048 const llvm::APSInt &InitVal = ECD->getInitVal();
1049 if (InitVal.getBitWidth() > IntWidth) {
1050 llvm::APSInt V(InitVal);
1051 V.trunc(IntWidth);
1052 V.extend(InitVal.getBitWidth());
1053 if (V != InitVal)
1054 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1055 InitVal.toString());
1056 }
Chris Lattner206754a2007-08-28 06:15:15 +00001057
1058 // Keep track of the size of positive and negative values.
1059 if (InitVal.isUnsigned() || !InitVal.isNegative())
1060 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1061 else
1062 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001063
Chris Lattner206754a2007-08-28 06:15:15 +00001064 // Keep track of whether every enum element has type int (very commmon).
1065 if (AllElementsInt)
1066 AllElementsInt = ECD->getType() == Context.IntTy;
1067
Chris Lattner4b009652007-07-25 00:24:17 +00001068 ECD->setNextDeclarator(EltList);
1069 EltList = ECD;
1070 }
1071
Chris Lattner206754a2007-08-28 06:15:15 +00001072 // Figure out the type that should be used for this enum.
1073 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1074 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001075 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001076
1077 if (NumNegativeBits) {
1078 // If there is a negative value, figure out the smallest integer type (of
1079 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001080 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001081 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001082 BestWidth = IntWidth;
1083 } else {
1084 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1085 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001086 BestType = Context.LongTy;
1087 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001088 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1089 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001090 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1091 BestType = Context.LongLongTy;
1092 }
1093 }
1094 } else {
1095 // If there is no negative value, figure out which of uint, ulong, ulonglong
1096 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001097 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001098 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001099 BestWidth = IntWidth;
1100 } else if (NumPositiveBits <=
1101 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001102 BestType = Context.UnsignedLongTy;
1103 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001104 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1105 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001106 "How could an initializer get larger than ULL?");
1107 BestType = Context.UnsignedLongLongTy;
1108 }
1109 }
1110
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001111 // Loop over all of the enumerator constants, changing their types to match
1112 // the type of the enum if needed.
1113 for (unsigned i = 0; i != NumElements; ++i) {
1114 EnumConstantDecl *ECD =
1115 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1116 if (!ECD) continue; // Already issued a diagnostic.
1117
1118 // Standard C says the enumerators have int type, but we allow, as an
1119 // extension, the enumerators to be larger than int size. If each
1120 // enumerator value fits in an int, type it as an int, otherwise type it the
1121 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1122 // that X has type 'int', not 'unsigned'.
1123 if (ECD->getType() == Context.IntTy)
1124 continue; // Already int type.
1125
1126 // Determine whether the value fits into an int.
1127 llvm::APSInt InitVal = ECD->getInitVal();
1128 bool FitsInInt;
1129 if (InitVal.isUnsigned() || !InitVal.isNegative())
1130 FitsInInt = InitVal.getActiveBits() < IntWidth;
1131 else
1132 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1133
1134 // If it fits into an integer type, force it. Otherwise force it to match
1135 // the enum decl type.
1136 QualType NewTy;
1137 unsigned NewWidth;
1138 bool NewSign;
1139 if (FitsInInt) {
1140 NewTy = Context.IntTy;
1141 NewWidth = IntWidth;
1142 NewSign = true;
1143 } else if (ECD->getType() == BestType) {
1144 // Already the right type!
1145 continue;
1146 } else {
1147 NewTy = BestType;
1148 NewWidth = BestWidth;
1149 NewSign = BestType->isSignedIntegerType();
1150 }
1151
1152 // Adjust the APSInt value.
1153 InitVal.extOrTrunc(NewWidth);
1154 InitVal.setIsSigned(NewSign);
1155 ECD->setInitVal(InitVal);
1156
1157 // Adjust the Expr initializer and type.
1158 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1159 ECD->setType(NewTy);
1160 }
Chris Lattner206754a2007-08-28 06:15:15 +00001161
Chris Lattner90a018d2007-08-28 18:24:31 +00001162 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001163}
1164
1165void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1166 if (!current) return;
1167
1168 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1169 // remember this in the LastInGroupList list.
1170 if (last)
1171 LastInGroupList.push_back((Decl*)last);
1172}
1173
1174void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1175 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1176 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1177 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1178 if (!newType.isNull()) // install the new vector type into the decl
1179 vDecl->setType(newType);
1180 }
1181 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1182 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1183 rawAttr);
1184 if (!newType.isNull()) // install the new vector type into the decl
1185 tDecl->setUnderlyingType(newType);
1186 }
1187 }
1188 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001189 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1190 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1191 else
Chris Lattner4b009652007-07-25 00:24:17 +00001192 Diag(rawAttr->getAttributeLoc(),
1193 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001194 }
1195 // FIXME: add other attributes...
1196}
1197
1198void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1199 AttributeList *declarator_postfix) {
1200 while (declspec_prefix) {
1201 HandleDeclAttribute(New, declspec_prefix);
1202 declspec_prefix = declspec_prefix->getNext();
1203 }
1204 while (declarator_postfix) {
1205 HandleDeclAttribute(New, declarator_postfix);
1206 declarator_postfix = declarator_postfix->getNext();
1207 }
1208}
1209
Steve Naroff82113e32007-07-29 16:33:31 +00001210void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1211 AttributeList *rawAttr) {
1212 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001213 // check the attribute arugments.
1214 if (rawAttr->getNumArgs() != 1) {
1215 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1216 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001217 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001218 }
1219 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1220 llvm::APSInt vecSize(32);
1221 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1222 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1223 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001224 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001225 }
1226 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1227 // in conjunction with complex types (pointers, arrays, functions, etc.).
1228 Type *canonType = curType.getCanonicalType().getTypePtr();
1229 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1230 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1231 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001232 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001233 }
1234 // unlike gcc's vector_size attribute, the size is specified as the
1235 // number of elements, not the number of bytes.
1236 unsigned vectorSize = vecSize.getZExtValue();
1237
1238 if (vectorSize == 0) {
1239 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1240 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001241 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001242 }
Steve Naroff82113e32007-07-29 16:33:31 +00001243 // Instantiate/Install the vector type, the number of elements is > 0.
1244 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1245 // Remember this typedef decl, we will need it later for diagnostics.
1246 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001247}
1248
1249QualType Sema::HandleVectorTypeAttribute(QualType curType,
1250 AttributeList *rawAttr) {
1251 // check the attribute arugments.
1252 if (rawAttr->getNumArgs() != 1) {
1253 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1254 std::string("1"));
1255 return QualType();
1256 }
1257 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1258 llvm::APSInt vecSize(32);
1259 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1260 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1261 sizeExpr->getSourceRange());
1262 return QualType();
1263 }
1264 // navigate to the base type - we need to provide for vector pointers,
1265 // vector arrays, and functions returning vectors.
1266 Type *canonType = curType.getCanonicalType().getTypePtr();
1267
1268 if (canonType->isPointerType() || canonType->isArrayType() ||
1269 canonType->isFunctionType()) {
1270 assert(1 && "HandleVector(): Complex type construction unimplemented");
1271 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1272 do {
1273 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1274 canonType = PT->getPointeeType().getTypePtr();
1275 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1276 canonType = AT->getElementType().getTypePtr();
1277 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1278 canonType = FT->getResultType().getTypePtr();
1279 } while (canonType->isPointerType() || canonType->isArrayType() ||
1280 canonType->isFunctionType());
1281 */
1282 }
1283 // the base type must be integer or float.
1284 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1285 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1286 curType.getCanonicalType().getAsString());
1287 return QualType();
1288 }
1289 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
1290 // vecSize is specified in bytes - convert to bits.
1291 unsigned vectorSize = vecSize.getZExtValue() * 8;
1292
1293 // the vector size needs to be an integral multiple of the type size.
1294 if (vectorSize % typeSize) {
1295 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1296 sizeExpr->getSourceRange());
1297 return QualType();
1298 }
1299 if (vectorSize == 0) {
1300 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1301 sizeExpr->getSourceRange());
1302 return QualType();
1303 }
1304 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1305 // the number of elements to be a power of two (unlike GCC).
1306 // Instantiate the vector type, the number of elements is > 0.
1307 return Context.getVectorType(curType, vectorSize/typeSize);
1308}
1309