blob: 6ccdf2c396a6bfb9618da36eebfa7a65af93483e [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) {
32 const Expr *Size = Array->getSizeExpr();
33 if (Size == 0) return false; // incomplete type.
34
35 if (!Size->getType()->isIntegerType()) {
36 Diag(Size->getLocStart(), diag::err_array_size_non_int,
37 Size->getType().getAsString(), Size->getSourceRange());
38 return true;
39 }
40
41 // Verify that the size of the array is an integer constant expr.
42 SourceLocation Loc;
43 llvm::APSInt SizeVal(32);
44 if (!Size->isIntegerConstantExpr(SizeVal, Context, &Loc)) {
45 // FIXME: This emits the diagnostic to enforce 6.7.2.1p8, but the message
46 // is wrong. It is also wrong for static variables.
47 // FIXME: This is also wrong for:
48 // int sub1(int i, char *pi) { typedef int foo[i];
49 // struct bar {foo f1; int f2:3; int f3:4} *p; }
50 Diag(DeclLoc, diag::err_typecheck_illegal_vla, Size->getSourceRange());
51 return true;
52 }
53
54 // We have a constant expression with an integer type, now make sure
55 // value greater than zero (C99 6.7.5.2p1).
56
57 // FIXME: This check isn't specific to static VLAs, this should be moved
58 // elsewhere or replicated. 'int X[-1];' inside a function should emit an
59 // error.
60 if (SizeVal.isSigned()) {
61 llvm::APSInt Zero(SizeVal.getBitWidth());
62 Zero.setIsUnsigned(false);
63 if (SizeVal < Zero) {
64 Diag(DeclLoc, diag::err_typecheck_negative_array_size,
65 Size->getSourceRange());
66 return true;
67 } else if (SizeVal == 0) {
68 // GCC accepts zero sized static arrays.
69 Diag(DeclLoc, diag::err_typecheck_zero_array_size,
70 Size->getSourceRange());
71 }
72 }
73 return false;
74}
75
76Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
77 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
78}
79
80void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000081 if (S->decl_empty()) return;
82 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
83
Chris Lattner4b009652007-07-25 00:24:17 +000084 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
85 I != E; ++I) {
86 Decl *D = static_cast<Decl*>(*I);
87 assert(D && "This decl didn't get pushed??");
88 IdentifierInfo *II = D->getIdentifier();
89 if (!II) continue;
90
91 // Unlink this decl from the identifier. Because the scope contains decls
92 // in an unordered collection, and because we have multiple identifier
93 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
94 if (II->getFETokenInfo<Decl>() == D) {
95 // Normal case, no multiple decls in different namespaces.
96 II->setFETokenInfo(D->getNext());
97 } else {
98 // Scan ahead. There are only three namespaces in C, so this loop can
99 // never execute more than 3 times.
100 Decl *SomeDecl = II->getFETokenInfo<Decl>();
101 while (SomeDecl->getNext() != D) {
102 SomeDecl = SomeDecl->getNext();
103 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
104 }
105 SomeDecl->setNext(D->getNext());
106 }
107
108 // This will have to be revisited for C++: there we want to nest stuff in
109 // namespace decls etc. Even for C, we might want a top-level translation
110 // unit decl or something.
111 if (!CurFunctionDecl)
112 continue;
113
114 // Chain this decl to the containing function, it now owns the memory for
115 // the decl.
116 D->setNext(CurFunctionDecl->getDeclChain());
117 CurFunctionDecl->setDeclChain(D);
118 }
119}
120
121/// LookupScopedDecl - Look up the inner-most declaration in the specified
122/// namespace.
123Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
124 SourceLocation IdLoc, Scope *S) {
125 if (II == 0) return 0;
126 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
127
128 // Scan up the scope chain looking for a decl that matches this identifier
129 // that is in the appropriate namespace. This search should not take long, as
130 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
131 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
132 if (D->getIdentifierNamespace() == NS)
133 return D;
134
135 // If we didn't find a use of this identifier, and if the identifier
136 // corresponds to a compiler builtin, create the decl object for the builtin
137 // now, injecting it into translation unit scope, and return it.
138 if (NS == Decl::IDNS_Ordinary) {
139 // If this is a builtin on some other target, or if this builtin varies
140 // across targets (e.g. in type), emit a diagnostic and mark the translation
141 // unit non-portable for using it.
142 if (II->isNonPortableBuiltin()) {
143 // Only emit this diagnostic once for this builtin.
144 II->setNonPortableBuiltin(false);
145 Context.Target.DiagnoseNonPortability(IdLoc,
146 diag::port_target_builtin_use);
147 }
148 // If this is a builtin on this (or all) targets, create the decl.
149 if (unsigned BuiltinID = II->getBuiltinID())
150 return LazilyCreateBuiltin(II, BuiltinID, S);
151 }
152 return 0;
153}
154
155/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
156/// lazily create a decl for it.
157Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
158 Builtin::ID BID = (Builtin::ID)bid;
159
160 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
161 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000162 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000163
164 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000165 if (Scope *FnS = S->getFnParent())
166 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000167 while (S->getParent())
168 S = S->getParent();
169 S->AddDecl(New);
170
171 // Add this decl to the end of the identifier info.
172 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
173 // Scan until we find the last (outermost) decl in the id chain.
174 while (LastDecl->getNext())
175 LastDecl = LastDecl->getNext();
176 // Insert before (outside) it.
177 LastDecl->setNext(New);
178 } else {
179 II->setFETokenInfo(New);
180 }
181 // Make sure clients iterating over decls see this.
182 LastInGroupList.push_back(New);
183
184 return New;
185}
186
187/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
188/// and scope as a previous declaration 'Old'. Figure out how to resolve this
189/// situation, merging decls or emitting diagnostics as appropriate.
190///
191TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
192 // Verify the old decl was also a typedef.
193 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
194 if (!Old) {
195 Diag(New->getLocation(), diag::err_redefinition_different_kind,
196 New->getName());
197 Diag(OldD->getLocation(), diag::err_previous_definition);
198 return New;
199 }
200
201 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
202 // TODO: This is totally simplistic. It should handle merging functions
203 // together etc, merging extern int X; int X; ...
204 Diag(New->getLocation(), diag::err_redefinition, New->getName());
205 Diag(Old->getLocation(), diag::err_previous_definition);
206 return New;
207}
208
209/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
210/// and scope as a previous declaration 'Old'. Figure out how to resolve this
211/// situation, merging decls or emitting diagnostics as appropriate.
212///
213FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
214 // Verify the old decl was also a function.
215 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
216 if (!Old) {
217 Diag(New->getLocation(), diag::err_redefinition_different_kind,
218 New->getName());
219 Diag(OldD->getLocation(), diag::err_previous_definition);
220 return New;
221 }
222
223 // This is not right, but it's a start. If 'Old' is a function prototype with
224 // the same type as 'New', silently allow this. FIXME: We should link up decl
225 // objects here.
226 if (Old->getBody() == 0 &&
227 Old->getCanonicalType() == New->getCanonicalType()) {
228 return New;
229 }
230
231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232 // TODO: This is totally simplistic. It should handle merging functions
233 // together etc, merging extern int X; int X; ...
234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 return New;
237}
238
239/// MergeVarDecl - We just parsed a variable 'New' which has the same name
240/// and scope as a previous declaration 'Old'. Figure out how to resolve this
241/// situation, merging decls or emitting diagnostics as appropriate.
242///
243/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
244/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
245///
246VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
247 // Verify the old decl was also a variable.
248 VarDecl *Old = dyn_cast<VarDecl>(OldD);
249 if (!Old) {
250 Diag(New->getLocation(), diag::err_redefinition_different_kind,
251 New->getName());
252 Diag(OldD->getLocation(), diag::err_previous_definition);
253 return New;
254 }
255 // Verify the types match.
256 if (Old->getCanonicalType() != New->getCanonicalType()) {
257 Diag(New->getLocation(), diag::err_redefinition, New->getName());
258 Diag(Old->getLocation(), diag::err_previous_definition);
259 return New;
260 }
261 // We've verified the types match, now check if Old is "extern".
262 if (Old->getStorageClass() != VarDecl::Extern) {
263 Diag(New->getLocation(), diag::err_redefinition, New->getName());
264 Diag(Old->getLocation(), diag::err_previous_definition);
265 }
266 return New;
267}
268
269/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
270/// no declarator (e.g. "struct foo;") is parsed.
271Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
272 // TODO: emit error on 'int;' or 'const enum foo;'.
273 // TODO: emit error on 'typedef int;'
274 // if (!DS.isMissingDeclaratorOk()) Diag(...);
275
276 return 0;
277}
278
279Sema::DeclTy *
280Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
281 DeclTy *lastDeclarator) {
282 Decl *LastDeclarator = (Decl*)lastDeclarator;
283 Expr *Init = static_cast<Expr*>(init);
284 IdentifierInfo *II = D.getIdentifier();
285
286 // All of these full declarators require an identifier. If it doesn't have
287 // one, the ParsedFreeStandingDeclSpec action should be used.
288 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000289 Diag(D.getDeclSpec().getSourceRange().Begin(),
290 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000291 D.getDeclSpec().getSourceRange(), D.getSourceRange());
292 return 0;
293 }
294
Chris Lattnera7549902007-08-26 06:24:45 +0000295 // The scope passed in may not be a decl scope. Zip up the scope tree until
296 // we find one that is.
297 while ((S->getFlags() & Scope::DeclScope) == 0)
298 S = S->getParent();
299
Chris Lattner4b009652007-07-25 00:24:17 +0000300 // See if this is a redefinition of a variable in the same scope.
301 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
302 D.getIdentifierLoc(), S);
303 if (PrevDecl && !S->isDeclScope(PrevDecl))
304 PrevDecl = 0; // If in outer scope, it isn't the same thing.
305
306 Decl *New;
307 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
308 assert(Init == 0 && "Can't have initializer for a typedef!");
309 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
310 if (!NewTD) return 0;
311
312 // Handle attributes prior to checking for duplicates in MergeVarDecl
313 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
314 D.getAttributes());
315 // Merge the decl with the existing one if appropriate.
316 if (PrevDecl) {
317 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
318 if (NewTD == 0) return 0;
319 }
320 New = NewTD;
321 if (S->getParent() == 0) {
322 // C99 6.7.7p2: If a typedef name specifies a variably modified type
323 // then it shall have block scope.
324 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
325 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
326 return 0;
327 }
328 }
329 } else if (D.isFunctionDeclarator()) {
330 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
331 QualType R = GetTypeForDeclarator(D, S);
332 if (R.isNull()) return 0; // FIXME: "auto func();" passes through...
333
334 FunctionDecl::StorageClass SC;
335 switch (D.getDeclSpec().getStorageClassSpec()) {
336 default: assert(0 && "Unknown storage class!");
337 case DeclSpec::SCS_auto:
338 case DeclSpec::SCS_register:
339 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
340 R.getAsString());
341 return 0;
342 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
343 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
344 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
345 }
346
347 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000348 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000349 LastDeclarator);
350
351 // Merge the decl with the existing one if appropriate.
352 if (PrevDecl) {
353 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
354 if (NewFD == 0) return 0;
355 }
356 New = NewFD;
357 } else {
358 QualType R = GetTypeForDeclarator(D, S);
359 if (R.isNull()) return 0;
360
361 VarDecl *NewVD;
362 VarDecl::StorageClass SC;
363 switch (D.getDeclSpec().getStorageClassSpec()) {
364 default: assert(0 && "Unknown storage class!");
365 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
366 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
367 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
368 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
369 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
370 }
371 if (S->getParent() == 0) {
372 // File scope. C99 6.9.2p2: A declaration of an identifier for and
373 // object that has file scope without an initializer, and without a
374 // storage-class specifier or with the storage-class specifier "static",
375 // constitutes a tentative definition. Note: A tentative definition with
376 // external linkage is valid (C99 6.2.2p5).
377 if (!Init && SC == VarDecl::Static) {
378 // C99 6.9.2p3: If the declaration of an identifier for an object is
379 // a tentative definition and has internal linkage (C99 6.2.2p3), the
380 // declared type shall not be an incomplete type.
381 if (R->isIncompleteType()) {
382 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
383 R.getAsString());
384 return 0;
385 }
386 }
387 // C99 6.9p2: The storage-class specifiers auto and register shall not
388 // appear in the declaration specifiers in an external declaration.
389 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
390 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
391 R.getAsString());
392 return 0;
393 }
394 // C99 6.7.5.2p2: If an identifier is declared to be an object with
395 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000396 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000397 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
398 return 0;
399 }
400 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
401 } else {
402 // Block scope. C99 6.7p7: If an identifier for an object is declared with
403 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
404 if (SC != VarDecl::Extern) {
405 if (R->isIncompleteType()) {
406 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
407 R.getAsString());
408 return 0;
409 }
410 }
411 if (SC == VarDecl::Static) {
412 // C99 6.7.5.2p2: If an identifier is declared to be an object with
413 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000414 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000415 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
416 return 0;
417 }
418 }
419 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
420 }
421 // Handle attributes prior to checking for duplicates in MergeVarDecl
422 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
423 D.getAttributes());
424
425 // Merge the decl with the existing one if appropriate.
426 if (PrevDecl) {
427 NewVD = MergeVarDecl(NewVD, PrevDecl);
428 if (NewVD == 0) return 0;
429 }
Steve Naroff0f32f432007-08-24 22:33:52 +0000430 if (Init) {
431 AssignmentCheckResult result;
432 result = CheckSingleAssignmentConstraints(R, Init);
433 // FIXME: emit errors if appropriate.
434 NewVD->setInit(Init);
435 }
Chris Lattner4b009652007-07-25 00:24:17 +0000436 New = NewVD;
437 }
438
439 // If this has an identifier, add it to the scope stack.
440 if (II) {
441 New->setNext(II->getFETokenInfo<Decl>());
442 II->setFETokenInfo(New);
443 S->AddDecl(New);
444 }
445
446 if (S->getParent() == 0)
447 AddTopLevelDecl(New, LastDeclarator);
448
449 return New;
450}
451
452/// The declarators are chained together backwards, reverse the list.
453Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
454 // Often we have single declarators, handle them quickly.
455 Decl *Group = static_cast<Decl*>(group);
456 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
457
458 Decl *NewGroup = 0;
459 while (Group) {
460 Decl *Next = Group->getNextDeclarator();
461 Group->setNextDeclarator(NewGroup);
462 NewGroup = Group;
463 Group = Next;
464 }
465 return NewGroup;
466}
Steve Naroff91b03f72007-08-28 03:03:08 +0000467
468// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000469ParmVarDecl *
470Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
471 Scope *FnScope) {
472 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
473
474 IdentifierInfo *II = PI.Ident;
475 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
476 // Can this happen for params? We already checked that they don't conflict
477 // among each other. Here they can only shadow globals, which is ok.
478 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
479 PI.IdentLoc, FnScope)) {
480
481 }
482
483 // FIXME: Handle storage class (auto, register). No declarator?
484 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000485
486 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
487 // Doing the promotion here has a win and a loss. The win is the type for
488 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
489 // code generator). The loss is the orginal type isn't preserved. For example:
490 //
491 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
492 // int blockvardecl[5];
493 // sizeof(parmvardecl); // size == 4
494 // sizeof(blockvardecl); // size == 20
495 // }
496 //
497 // For expressions, all implicit conversions are captured using the
498 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
499 //
500 // FIXME: If a source translation tool needs to see the original type, then
501 // we need to consider storing both types (in ParmVarDecl)...
502 //
503 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
504 if (const ArrayType *AT = parmDeclType->getAsArrayType())
505 parmDeclType = Context.getPointerType(AT->getElementType());
506 else if (parmDeclType->isFunctionType())
507 parmDeclType = Context.getPointerType(parmDeclType);
508
509 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff91b03f72007-08-28 03:03:08 +0000510 VarDecl::None, 0, PI.InvalidType);
Chris Lattner4b009652007-07-25 00:24:17 +0000511
512 // If this has an identifier, add it to the scope stack.
513 if (II) {
514 New->setNext(II->getFETokenInfo<Decl>());
515 II->setFETokenInfo(New);
516 FnScope->AddDecl(New);
517 }
518
519 return New;
520}
521
522
523Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
524 assert(CurFunctionDecl == 0 && "Function parsing confused");
525 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
526 "Not a function declarator!");
527 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
528
529 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
530 // for a K&R function.
531 if (!FTI.hasPrototype) {
532 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
533 if (FTI.ArgInfo[i].TypeInfo == 0) {
534 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
535 FTI.ArgInfo[i].Ident->getName());
536 // Implicitly declare the argument as type 'int' for lack of a better
537 // type.
538 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
539 }
540 }
541
542 // Since this is a function definition, act as though we have information
543 // about the arguments.
544 FTI.hasPrototype = true;
545 } else {
546 // FIXME: Diagnose arguments without names in C.
547
548 }
549
550 Scope *GlobalScope = FnBodyScope->getParent();
551
552 FunctionDecl *FD =
553 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
554 CurFunctionDecl = FD;
555
556 // Create Decl objects for each parameter, adding them to the FunctionDecl.
557 llvm::SmallVector<ParmVarDecl*, 16> Params;
558
559 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
560 // no arguments, not a function that takes a single void argument.
561 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
562 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
563 // empty arg list, don't push any params.
564 } else {
565 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
566 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
567 }
568
569 FD->setParams(&Params[0], Params.size());
570
571 return FD;
572}
573
574Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
575 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
576 FD->setBody((Stmt*)Body);
577
578 assert(FD == CurFunctionDecl && "Function parsing confused");
579 CurFunctionDecl = 0;
580
581 // Verify and clean out per-function state.
582
583 // Check goto/label use.
584 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
585 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
586 // Verify that we have no forward references left. If so, there was a goto
587 // or address of a label taken, but no definition of it. Label fwd
588 // definitions are indicated with a null substmt.
589 if (I->second->getSubStmt() == 0) {
590 LabelStmt *L = I->second;
591 // Emit error.
592 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
593
594 // At this point, we have gotos that use the bogus label. Stitch it into
595 // the function body so that they aren't leaked and that the AST is well
596 // formed.
597 L->setSubStmt(new NullStmt(L->getIdentLoc()));
598 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
599 }
600 }
601 LabelMap.clear();
602
603 return FD;
604}
605
606
607/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
608/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
609Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
610 Scope *S) {
611 if (getLangOptions().C99) // Extension in C99.
612 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
613 else // Legal in C90, but warn about it.
614 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
615
616 // FIXME: handle stuff like:
617 // void foo() { extern float X(); }
618 // void bar() { X(); } <-- implicit decl for X in another scope.
619
620 // Set a Declarator for the implicit definition: int foo();
621 const char *Dummy;
622 DeclSpec DS;
623 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
624 Error = Error; // Silence warning.
625 assert(!Error && "Error setting up implicit decl!");
626 Declarator D(DS, Declarator::BlockContext);
627 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
628 D.SetIdentifier(&II, Loc);
629
630 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000631 if (Scope *FnS = S->getFnParent())
632 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000633 while (S->getParent())
634 S = S->getParent();
635
636 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
637}
638
639
640TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
641 Decl *LastDeclarator) {
642 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
643
644 QualType T = GetTypeForDeclarator(D, S);
645 if (T.isNull()) return 0;
646
647 // Scope manipulation handled by caller.
648 return new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(), T,
649 LastDeclarator);
650}
651
652
653/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
654/// former case, Name will be non-null. In the later case, Name will be null.
655/// TagType indicates what kind of tag this is. TK indicates whether this is a
656/// reference/declaration/definition of a tag.
657Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
658 SourceLocation KWLoc, IdentifierInfo *Name,
659 SourceLocation NameLoc, AttributeList *Attr) {
660 // If this is a use of an existing tag, it must have a name.
661 assert((Name != 0 || TK == TK_Definition) &&
662 "Nameless record must be a definition!");
663
664 Decl::Kind Kind;
665 switch (TagType) {
666 default: assert(0 && "Unknown tag type!");
667 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
668 case DeclSpec::TST_union: Kind = Decl::Union; break;
669//case DeclSpec::TST_class: Kind = Decl::Class; break;
670 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
671 }
672
673 // If this is a named struct, check to see if there was a previous forward
674 // declaration or definition.
675 if (TagDecl *PrevDecl =
676 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
677 NameLoc, S))) {
678
679 // If this is a use of a previous tag, or if the tag is already declared in
680 // the same scope (so that the definition/declaration completes or
681 // rementions the tag), reuse the decl.
682 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
683 // Make sure that this wasn't declared as an enum and now used as a struct
684 // or something similar.
685 if (PrevDecl->getKind() != Kind) {
686 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
687 Diag(PrevDecl->getLocation(), diag::err_previous_use);
688 }
689
690 // If this is a use or a forward declaration, we're good.
691 if (TK != TK_Definition)
692 return PrevDecl;
693
694 // Diagnose attempts to redefine a tag.
695 if (PrevDecl->isDefinition()) {
696 Diag(NameLoc, diag::err_redefinition, Name->getName());
697 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
698 // If this is a redefinition, recover by making this struct be
699 // anonymous, which will make any later references get the previous
700 // definition.
701 Name = 0;
702 } else {
703 // Okay, this is definition of a previously declared or referenced tag.
704 // Move the location of the decl to be the definition site.
705 PrevDecl->setLocation(NameLoc);
706 return PrevDecl;
707 }
708 }
709 // If we get here, this is a definition of a new struct type in a nested
710 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
711 // type.
712 }
713
714 // If there is an identifier, use the location of the identifier as the
715 // location of the decl, otherwise use the location of the struct/union
716 // keyword.
717 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
718
719 // Otherwise, if this is the first time we've seen this tag, create the decl.
720 TagDecl *New;
721 switch (Kind) {
722 default: assert(0 && "Unknown tag kind!");
723 case Decl::Enum:
724 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
725 // enum X { A, B, C } D; D should chain to X.
726 New = new EnumDecl(Loc, Name, 0);
727 // If this is an undefined enum, warn.
728 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
729 break;
730 case Decl::Union:
731 case Decl::Struct:
732 case Decl::Class:
733 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
734 // struct X { int A; } D; D should chain to X.
735 New = new RecordDecl(Kind, Loc, Name, 0);
736 break;
737 }
738
739 // If this has an identifier, add it to the scope stack.
740 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000741 // The scope passed in may not be a decl scope. Zip up the scope tree until
742 // we find one that is.
743 while ((S->getFlags() & Scope::DeclScope) == 0)
744 S = S->getParent();
745
746 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000747 New->setNext(Name->getFETokenInfo<Decl>());
748 Name->setFETokenInfo(New);
749 S->AddDecl(New);
750 }
751
752 return New;
753}
754
755/// ParseField - Each field of a struct/union/class is passed into this in order
756/// to create a FieldDecl object for it.
757Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
758 SourceLocation DeclStart,
759 Declarator &D, ExprTy *BitfieldWidth) {
760 IdentifierInfo *II = D.getIdentifier();
761 Expr *BitWidth = (Expr*)BitfieldWidth;
762
763 SourceLocation Loc = DeclStart;
764 if (II) Loc = D.getIdentifierLoc();
765
766 // FIXME: Unnamed fields can be handled in various different ways, for
767 // example, unnamed unions inject all members into the struct namespace!
768
769
770 if (BitWidth) {
771 // TODO: Validate.
772 //printf("WARNING: BITFIELDS IGNORED!\n");
773
774 // 6.7.2.1p3
775 // 6.7.2.1p4
776
777 } else {
778 // Not a bitfield.
779
780 // validate II.
781
782 }
783
784 QualType T = GetTypeForDeclarator(D, S);
785 if (T.isNull()) return 0;
786
787 // C99 6.7.2.1p8: A member of a structure or union may have any type other
788 // than a variably modified type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000789 if (const ArrayType *ary = T->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 if (VerifyConstantArrayType(ary, Loc))
791 return 0;
792 }
793
794 // FIXME: Chain fielddecls together.
795 return new FieldDecl(Loc, II, T, 0);
796}
797
798void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
799 DeclTy **Fields, unsigned NumFields) {
800 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
801 if (Record->isDefinition()) {
802 // Diagnose code like:
803 // struct S { struct S {} X; };
804 // We discover this when we complete the outer S. Reject and ignore the
805 // outer S.
806 Diag(Record->getLocation(), diag::err_nested_redefinition,
807 Record->getKindName());
808 Diag(RecLoc, diag::err_previous_definition);
809 return;
810 }
811
812 // Verify that all the fields are okay.
813 unsigned NumNamedMembers = 0;
814 llvm::SmallVector<FieldDecl*, 32> RecFields;
815 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
816
817 for (unsigned i = 0; i != NumFields; ++i) {
818 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
819 if (!FD) continue; // Already issued a diagnostic.
820
821 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +0000822 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +0000823
824 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000825 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000826 Diag(FD->getLocation(), diag::err_field_declared_as_function,
827 FD->getName());
828 delete FD;
829 continue;
830 }
831
832 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
833 if (FDTy->isIncompleteType()) {
834 if (i != NumFields-1 || // ... that the last member ...
835 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +0000836 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +0000837 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
838 delete FD;
839 continue;
840 }
841 if (NumNamedMembers < 1) { //... must have more than named member ...
842 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
843 FD->getName());
844 delete FD;
845 continue;
846 }
847
848 // Okay, we have a legal flexible array member at the end of the struct.
849 Record->setHasFlexibleArrayMember(true);
850 }
851
852
853 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
854 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000855 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000856 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
857 // If this is a member of a union, then entire union becomes "flexible".
858 if (Record->getKind() == Decl::Union) {
859 Record->setHasFlexibleArrayMember(true);
860 } else {
861 // If this is a struct/class and this is not the last element, reject
862 // it. Note that GCC supports variable sized arrays in the middle of
863 // structures.
864 if (i != NumFields-1) {
865 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
866 FD->getName());
867 delete FD;
868 continue;
869 }
870
871 // We support flexible arrays at the end of structs in other structs
872 // as an extension.
873 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
874 FD->getName());
875 Record->setHasFlexibleArrayMember(true);
876 }
877 }
878 }
879
880 // Keep track of the number of named members.
881 if (IdentifierInfo *II = FD->getIdentifier()) {
882 // Detect duplicate member names.
883 if (!FieldIDs.insert(II)) {
884 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
885 // Find the previous decl.
886 SourceLocation PrevLoc;
887 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
888 assert(i != e && "Didn't find previous def!");
889 if (RecFields[i]->getIdentifier() == II) {
890 PrevLoc = RecFields[i]->getLocation();
891 break;
892 }
893 }
894 Diag(PrevLoc, diag::err_previous_definition);
895 delete FD;
896 continue;
897 }
898 ++NumNamedMembers;
899 }
900
901 // Remember good fields.
902 RecFields.push_back(FD);
903 }
904
905
906 // Okay, we successfully defined 'Record'.
907 Record->defineBody(&RecFields[0], RecFields.size());
908}
909
910Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
911 DeclTy *lastEnumConst,
912 SourceLocation IdLoc, IdentifierInfo *Id,
913 SourceLocation EqualLoc, ExprTy *val) {
914 theEnumDecl = theEnumDecl; // silence unused warning.
915 EnumConstantDecl *LastEnumConst =
916 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
917 Expr *Val = static_cast<Expr*>(val);
918
Chris Lattnera7549902007-08-26 06:24:45 +0000919 // The scope passed in may not be a decl scope. Zip up the scope tree until
920 // we find one that is.
921 while ((S->getFlags() & Scope::DeclScope) == 0)
922 S = S->getParent();
923
Chris Lattner4b009652007-07-25 00:24:17 +0000924 // Verify that there isn't already something declared with this name in this
925 // scope.
926 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
927 if (S->isDeclScope(PrevDecl)) {
928 if (isa<EnumConstantDecl>(PrevDecl))
929 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
930 else
931 Diag(IdLoc, diag::err_redefinition, Id->getName());
932 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
933 // FIXME: Don't leak memory: delete Val;
934 return 0;
935 }
936 }
937
938 llvm::APSInt EnumVal(32);
939 QualType EltTy;
940 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +0000941 // Make sure to promote the operand type to int.
942 UsualUnaryConversions(Val);
943
Chris Lattner4b009652007-07-25 00:24:17 +0000944 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
945 SourceLocation ExpLoc;
946 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
947 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
948 Id->getName());
949 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +0000950 Val = 0; // Just forget about it.
Chris Lattner4b009652007-07-25 00:24:17 +0000951 }
952 EltTy = Val->getType();
Chris Lattnere7f53a42007-08-27 17:37:24 +0000953 }
954
955 if (!Val) {
956 if (LastEnumConst) {
957 // Assign the last value + 1.
958 EnumVal = LastEnumConst->getInitVal();
959 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +0000960
961 // Check for overflow on increment.
962 if (EnumVal < LastEnumConst->getInitVal())
963 Diag(IdLoc, diag::warn_enum_value_overflow);
964
Chris Lattnere7f53a42007-08-27 17:37:24 +0000965 EltTy = LastEnumConst->getType();
966 } else {
967 // First value, set to zero.
968 EltTy = Context.IntTy;
Chris Lattner2cda8792007-08-27 21:16:18 +0000969 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnere7f53a42007-08-27 17:37:24 +0000970 }
Chris Lattner4b009652007-07-25 00:24:17 +0000971 }
972
Chris Lattner4b009652007-07-25 00:24:17 +0000973 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
974 LastEnumConst);
975
976 // Register this decl in the current scope stack.
977 New->setNext(Id->getFETokenInfo<Decl>());
978 Id->setFETokenInfo(New);
979 S->AddDecl(New);
980 return New;
981}
982
983void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
984 DeclTy **Elements, unsigned NumElements) {
985 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
986 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
987
Chris Lattner435c3fd2007-08-28 05:10:31 +0000988 // TODO: If the result value doesn't fit in an int, it must be a long or long
989 // long value. ISO C does not support this, but GCC does as an extension,
990 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +0000991 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +0000992
993
Chris Lattner206754a2007-08-28 06:15:15 +0000994 // Verify that all the values are okay, compute the size of the values, and
995 // reverse the list.
996 unsigned NumNegativeBits = 0;
997 unsigned NumPositiveBits = 0;
998
999 // Keep track of whether all elements have type int.
1000 bool AllElementsInt = true;
1001
Chris Lattner4b009652007-07-25 00:24:17 +00001002 EnumConstantDecl *EltList = 0;
1003 for (unsigned i = 0; i != NumElements; ++i) {
1004 EnumConstantDecl *ECD =
1005 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1006 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001007
1008 // If the enum value doesn't fit in an int, emit an extension warning.
1009 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1010 "Should have promoted value to int");
1011 const llvm::APSInt &InitVal = ECD->getInitVal();
1012 if (InitVal.getBitWidth() > IntWidth) {
1013 llvm::APSInt V(InitVal);
1014 V.trunc(IntWidth);
1015 V.extend(InitVal.getBitWidth());
1016 if (V != InitVal)
1017 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1018 InitVal.toString());
1019 }
Chris Lattner206754a2007-08-28 06:15:15 +00001020
1021 // Keep track of the size of positive and negative values.
1022 if (InitVal.isUnsigned() || !InitVal.isNegative())
1023 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1024 else
1025 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001026
Chris Lattner206754a2007-08-28 06:15:15 +00001027 // Keep track of whether every enum element has type int (very commmon).
1028 if (AllElementsInt)
1029 AllElementsInt = ECD->getType() == Context.IntTy;
1030
Chris Lattner4b009652007-07-25 00:24:17 +00001031 ECD->setNextDeclarator(EltList);
1032 EltList = ECD;
1033 }
1034
Chris Lattner206754a2007-08-28 06:15:15 +00001035 // Figure out the type that should be used for this enum.
1036 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1037 QualType BestType;
1038
1039 if (NumNegativeBits) {
1040 // If there is a negative value, figure out the smallest integer type (of
1041 // int/long/longlong) that fits.
1042 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth)
1043 BestType = Context.IntTy;
1044 else {
1045 unsigned LongWidth = Context.Target.getLongWidth(Enum->getLocation());
1046 if (NumNegativeBits <= LongWidth && NumPositiveBits < LongWidth)
1047 BestType = Context.LongTy;
1048 else {
1049 unsigned LLWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1050 if (NumNegativeBits > LLWidth || NumPositiveBits >= LLWidth)
1051 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1052 BestType = Context.LongLongTy;
1053 }
1054 }
1055 } else {
1056 // If there is no negative value, figure out which of uint, ulong, ulonglong
1057 // fits.
1058 if (NumPositiveBits <= IntWidth)
1059 BestType = Context.UnsignedIntTy;
1060 else if (NumPositiveBits <=Context.Target.getLongWidth(Enum->getLocation()))
1061 BestType = Context.UnsignedLongTy;
1062 else {
1063 assert(NumPositiveBits <=
1064 Context.Target.getLongLongWidth(Enum->getLocation()) &&
1065 "How could an initializer get larger than ULL?");
1066 BestType = Context.UnsignedLongLongTy;
1067 }
1068 }
1069
1070 // FIXME: Install type in Enum and constant values.
1071
Chris Lattner90a018d2007-08-28 18:24:31 +00001072 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001073}
1074
1075void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1076 if (!current) return;
1077
1078 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1079 // remember this in the LastInGroupList list.
1080 if (last)
1081 LastInGroupList.push_back((Decl*)last);
1082}
1083
1084void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1085 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1086 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1087 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1088 if (!newType.isNull()) // install the new vector type into the decl
1089 vDecl->setType(newType);
1090 }
1091 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1092 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1093 rawAttr);
1094 if (!newType.isNull()) // install the new vector type into the decl
1095 tDecl->setUnderlyingType(newType);
1096 }
1097 }
1098 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001099 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1100 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1101 else
Chris Lattner4b009652007-07-25 00:24:17 +00001102 Diag(rawAttr->getAttributeLoc(),
1103 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001104 }
1105 // FIXME: add other attributes...
1106}
1107
1108void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1109 AttributeList *declarator_postfix) {
1110 while (declspec_prefix) {
1111 HandleDeclAttribute(New, declspec_prefix);
1112 declspec_prefix = declspec_prefix->getNext();
1113 }
1114 while (declarator_postfix) {
1115 HandleDeclAttribute(New, declarator_postfix);
1116 declarator_postfix = declarator_postfix->getNext();
1117 }
1118}
1119
Steve Naroff82113e32007-07-29 16:33:31 +00001120void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1121 AttributeList *rawAttr) {
1122 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001123 // check the attribute arugments.
1124 if (rawAttr->getNumArgs() != 1) {
1125 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1126 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001127 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001128 }
1129 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1130 llvm::APSInt vecSize(32);
1131 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1132 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1133 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001134 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001135 }
1136 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1137 // in conjunction with complex types (pointers, arrays, functions, etc.).
1138 Type *canonType = curType.getCanonicalType().getTypePtr();
1139 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1140 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1141 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001142 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001143 }
1144 // unlike gcc's vector_size attribute, the size is specified as the
1145 // number of elements, not the number of bytes.
1146 unsigned vectorSize = vecSize.getZExtValue();
1147
1148 if (vectorSize == 0) {
1149 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1150 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001151 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001152 }
Steve Naroff82113e32007-07-29 16:33:31 +00001153 // Instantiate/Install the vector type, the number of elements is > 0.
1154 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1155 // Remember this typedef decl, we will need it later for diagnostics.
1156 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001157}
1158
1159QualType Sema::HandleVectorTypeAttribute(QualType curType,
1160 AttributeList *rawAttr) {
1161 // check the attribute arugments.
1162 if (rawAttr->getNumArgs() != 1) {
1163 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1164 std::string("1"));
1165 return QualType();
1166 }
1167 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1168 llvm::APSInt vecSize(32);
1169 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1170 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1171 sizeExpr->getSourceRange());
1172 return QualType();
1173 }
1174 // navigate to the base type - we need to provide for vector pointers,
1175 // vector arrays, and functions returning vectors.
1176 Type *canonType = curType.getCanonicalType().getTypePtr();
1177
1178 if (canonType->isPointerType() || canonType->isArrayType() ||
1179 canonType->isFunctionType()) {
1180 assert(1 && "HandleVector(): Complex type construction unimplemented");
1181 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1182 do {
1183 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1184 canonType = PT->getPointeeType().getTypePtr();
1185 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1186 canonType = AT->getElementType().getTypePtr();
1187 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1188 canonType = FT->getResultType().getTypePtr();
1189 } while (canonType->isPointerType() || canonType->isArrayType() ||
1190 canonType->isFunctionType());
1191 */
1192 }
1193 // the base type must be integer or float.
1194 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1195 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1196 curType.getCanonicalType().getAsString());
1197 return QualType();
1198 }
1199 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
1200 // vecSize is specified in bytes - convert to bits.
1201 unsigned vectorSize = vecSize.getZExtValue() * 8;
1202
1203 // the vector size needs to be an integral multiple of the type size.
1204 if (vectorSize % typeSize) {
1205 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1206 sizeExpr->getSourceRange());
1207 return QualType();
1208 }
1209 if (vectorSize == 0) {
1210 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1211 sizeExpr->getSourceRange());
1212 return QualType();
1213 }
1214 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1215 // the number of elements to be a power of two (unlike GCC).
1216 // Instantiate the vector type, the number of elements is > 0.
1217 return Context.getVectorType(curType, vectorSize/typeSize);
1218}
1219