blob: 9a781b9ce49beb96e2656d34757558d49cb42991 [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;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000307 bool InvalidDecl = false;
308
Chris Lattner4b009652007-07-25 00:24:17 +0000309 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
310 assert(Init == 0 && "Can't have initializer for a typedef!");
311 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
312 if (!NewTD) return 0;
313
314 // Handle attributes prior to checking for duplicates in MergeVarDecl
315 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
316 D.getAttributes());
317 // Merge the decl with the existing one if appropriate.
318 if (PrevDecl) {
319 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
320 if (NewTD == 0) return 0;
321 }
322 New = NewTD;
323 if (S->getParent() == 0) {
324 // C99 6.7.7p2: If a typedef name specifies a variably modified type
325 // then it shall have block scope.
326 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
327 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000328 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000329 }
330 }
331 } else if (D.isFunctionDeclarator()) {
332 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000333
Chris Lattner4b009652007-07-25 00:24:17 +0000334 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000335 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000336
337 FunctionDecl::StorageClass SC;
338 switch (D.getDeclSpec().getStorageClassSpec()) {
339 default: assert(0 && "Unknown storage class!");
340 case DeclSpec::SCS_auto:
341 case DeclSpec::SCS_register:
342 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
343 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000344 InvalidDecl = true;
345 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000346 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
347 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
348 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
349 }
350
351 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000352 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000353 LastDeclarator);
354
355 // Merge the decl with the existing one if appropriate.
356 if (PrevDecl) {
357 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
358 if (NewFD == 0) return 0;
359 }
360 New = NewFD;
361 } else {
362 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000363 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000364
365 VarDecl *NewVD;
366 VarDecl::StorageClass SC;
367 switch (D.getDeclSpec().getStorageClassSpec()) {
368 default: assert(0 && "Unknown storage class!");
369 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
370 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
371 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
372 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
373 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
374 }
375 if (S->getParent() == 0) {
376 // File scope. C99 6.9.2p2: A declaration of an identifier for and
377 // object that has file scope without an initializer, and without a
378 // storage-class specifier or with the storage-class specifier "static",
379 // constitutes a tentative definition. Note: A tentative definition with
380 // external linkage is valid (C99 6.2.2p5).
381 if (!Init && SC == VarDecl::Static) {
382 // C99 6.9.2p3: If the declaration of an identifier for an object is
383 // a tentative definition and has internal linkage (C99 6.2.2p3), the
384 // declared type shall not be an incomplete type.
385 if (R->isIncompleteType()) {
386 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
387 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000388 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000389 }
390 }
391 // C99 6.9p2: The storage-class specifiers auto and register shall not
392 // appear in the declaration specifiers in an external declaration.
393 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
394 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
395 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000396 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000397 }
398 // C99 6.7.5.2p2: If an identifier is declared to be an object with
399 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000400 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000401 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcae537d2007-08-28 18:45:29 +0000402 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000403 }
404 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
405 } else {
406 // Block scope. C99 6.7p7: If an identifier for an object is declared with
407 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
408 if (SC != VarDecl::Extern) {
409 if (R->isIncompleteType()) {
410 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
411 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000412 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000413 }
414 }
415 if (SC == VarDecl::Static) {
416 // C99 6.7.5.2p2: If an identifier is declared to be an object with
417 // static storage duration, it shall not have a variable length array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000418 if (const ArrayType *ary = R->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
Steve Naroffcae537d2007-08-28 18:45:29 +0000420 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000421 }
422 }
423 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000424 }
Chris Lattner4b009652007-07-25 00:24:17 +0000425 // Handle attributes prior to checking for duplicates in MergeVarDecl
426 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
427 D.getAttributes());
428
429 // Merge the decl with the existing one if appropriate.
430 if (PrevDecl) {
431 NewVD = MergeVarDecl(NewVD, PrevDecl);
432 if (NewVD == 0) return 0;
433 }
Steve Naroff0f32f432007-08-24 22:33:52 +0000434 if (Init) {
435 AssignmentCheckResult result;
436 result = CheckSingleAssignmentConstraints(R, Init);
437 // FIXME: emit errors if appropriate.
438 NewVD->setInit(Init);
439 }
Chris Lattner4b009652007-07-25 00:24:17 +0000440 New = NewVD;
441 }
442
443 // If this has an identifier, add it to the scope stack.
444 if (II) {
445 New->setNext(II->getFETokenInfo<Decl>());
446 II->setFETokenInfo(New);
447 S->AddDecl(New);
448 }
449
450 if (S->getParent() == 0)
451 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000452
453 // If any semantic error occurred, mark the decl as invalid.
454 if (D.getInvalidType() || InvalidDecl)
455 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000456
457 return New;
458}
459
460/// The declarators are chained together backwards, reverse the list.
461Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
462 // Often we have single declarators, handle them quickly.
463 Decl *Group = static_cast<Decl*>(group);
464 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
465
466 Decl *NewGroup = 0;
467 while (Group) {
468 Decl *Next = Group->getNextDeclarator();
469 Group->setNextDeclarator(NewGroup);
470 NewGroup = Group;
471 Group = Next;
472 }
473 return NewGroup;
474}
Steve Naroff91b03f72007-08-28 03:03:08 +0000475
476// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000477ParmVarDecl *
478Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
479 Scope *FnScope) {
480 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
481
482 IdentifierInfo *II = PI.Ident;
483 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
484 // Can this happen for params? We already checked that they don't conflict
485 // among each other. Here they can only shadow globals, which is ok.
486 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
487 PI.IdentLoc, FnScope)) {
488
489 }
490
491 // FIXME: Handle storage class (auto, register). No declarator?
492 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000493
494 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
495 // Doing the promotion here has a win and a loss. The win is the type for
496 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
497 // code generator). The loss is the orginal type isn't preserved. For example:
498 //
499 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
500 // int blockvardecl[5];
501 // sizeof(parmvardecl); // size == 4
502 // sizeof(blockvardecl); // size == 20
503 // }
504 //
505 // For expressions, all implicit conversions are captured using the
506 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
507 //
508 // FIXME: If a source translation tool needs to see the original type, then
509 // we need to consider storing both types (in ParmVarDecl)...
510 //
511 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
512 if (const ArrayType *AT = parmDeclType->getAsArrayType())
513 parmDeclType = Context.getPointerType(AT->getElementType());
514 else if (parmDeclType->isFunctionType())
515 parmDeclType = Context.getPointerType(parmDeclType);
516
517 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000518 VarDecl::None, 0);
519 if (PI.InvalidType)
520 New->setInvalidDecl();
521
Chris Lattner4b009652007-07-25 00:24:17 +0000522 // If this has an identifier, add it to the scope stack.
523 if (II) {
524 New->setNext(II->getFETokenInfo<Decl>());
525 II->setFETokenInfo(New);
526 FnScope->AddDecl(New);
527 }
528
529 return New;
530}
531
532
533Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
534 assert(CurFunctionDecl == 0 && "Function parsing confused");
535 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
536 "Not a function declarator!");
537 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
538
539 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
540 // for a K&R function.
541 if (!FTI.hasPrototype) {
542 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
543 if (FTI.ArgInfo[i].TypeInfo == 0) {
544 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
545 FTI.ArgInfo[i].Ident->getName());
546 // Implicitly declare the argument as type 'int' for lack of a better
547 // type.
548 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
549 }
550 }
551
552 // Since this is a function definition, act as though we have information
553 // about the arguments.
554 FTI.hasPrototype = true;
555 } else {
556 // FIXME: Diagnose arguments without names in C.
557
558 }
559
560 Scope *GlobalScope = FnBodyScope->getParent();
561
562 FunctionDecl *FD =
563 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
564 CurFunctionDecl = FD;
565
566 // Create Decl objects for each parameter, adding them to the FunctionDecl.
567 llvm::SmallVector<ParmVarDecl*, 16> Params;
568
569 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
570 // no arguments, not a function that takes a single void argument.
571 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
572 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
573 // empty arg list, don't push any params.
574 } else {
575 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
576 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
577 }
578
579 FD->setParams(&Params[0], Params.size());
580
581 return FD;
582}
583
584Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
585 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
586 FD->setBody((Stmt*)Body);
587
588 assert(FD == CurFunctionDecl && "Function parsing confused");
589 CurFunctionDecl = 0;
590
591 // Verify and clean out per-function state.
592
593 // Check goto/label use.
594 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
595 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
596 // Verify that we have no forward references left. If so, there was a goto
597 // or address of a label taken, but no definition of it. Label fwd
598 // definitions are indicated with a null substmt.
599 if (I->second->getSubStmt() == 0) {
600 LabelStmt *L = I->second;
601 // Emit error.
602 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
603
604 // At this point, we have gotos that use the bogus label. Stitch it into
605 // the function body so that they aren't leaked and that the AST is well
606 // formed.
607 L->setSubStmt(new NullStmt(L->getIdentLoc()));
608 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
609 }
610 }
611 LabelMap.clear();
612
613 return FD;
614}
615
616
617/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
618/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
619Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
620 Scope *S) {
621 if (getLangOptions().C99) // Extension in C99.
622 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
623 else // Legal in C90, but warn about it.
624 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
625
626 // FIXME: handle stuff like:
627 // void foo() { extern float X(); }
628 // void bar() { X(); } <-- implicit decl for X in another scope.
629
630 // Set a Declarator for the implicit definition: int foo();
631 const char *Dummy;
632 DeclSpec DS;
633 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
634 Error = Error; // Silence warning.
635 assert(!Error && "Error setting up implicit decl!");
636 Declarator D(DS, Declarator::BlockContext);
637 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
638 D.SetIdentifier(&II, Loc);
639
640 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000641 if (Scope *FnS = S->getFnParent())
642 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000643 while (S->getParent())
644 S = S->getParent();
645
646 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
647}
648
649
650TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
651 Decl *LastDeclarator) {
652 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
653
654 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000655 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000656
657 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000658 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
659 T, LastDeclarator);
660 if (D.getInvalidType())
661 NewTD->setInvalidDecl();
662 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000663}
664
665
666/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
667/// former case, Name will be non-null. In the later case, Name will be null.
668/// TagType indicates what kind of tag this is. TK indicates whether this is a
669/// reference/declaration/definition of a tag.
670Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
671 SourceLocation KWLoc, IdentifierInfo *Name,
672 SourceLocation NameLoc, AttributeList *Attr) {
673 // If this is a use of an existing tag, it must have a name.
674 assert((Name != 0 || TK == TK_Definition) &&
675 "Nameless record must be a definition!");
676
677 Decl::Kind Kind;
678 switch (TagType) {
679 default: assert(0 && "Unknown tag type!");
680 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
681 case DeclSpec::TST_union: Kind = Decl::Union; break;
682//case DeclSpec::TST_class: Kind = Decl::Class; break;
683 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
684 }
685
686 // If this is a named struct, check to see if there was a previous forward
687 // declaration or definition.
688 if (TagDecl *PrevDecl =
689 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
690 NameLoc, S))) {
691
692 // If this is a use of a previous tag, or if the tag is already declared in
693 // the same scope (so that the definition/declaration completes or
694 // rementions the tag), reuse the decl.
695 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
696 // Make sure that this wasn't declared as an enum and now used as a struct
697 // or something similar.
698 if (PrevDecl->getKind() != Kind) {
699 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
700 Diag(PrevDecl->getLocation(), diag::err_previous_use);
701 }
702
703 // If this is a use or a forward declaration, we're good.
704 if (TK != TK_Definition)
705 return PrevDecl;
706
707 // Diagnose attempts to redefine a tag.
708 if (PrevDecl->isDefinition()) {
709 Diag(NameLoc, diag::err_redefinition, Name->getName());
710 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
711 // If this is a redefinition, recover by making this struct be
712 // anonymous, which will make any later references get the previous
713 // definition.
714 Name = 0;
715 } else {
716 // Okay, this is definition of a previously declared or referenced tag.
717 // Move the location of the decl to be the definition site.
718 PrevDecl->setLocation(NameLoc);
719 return PrevDecl;
720 }
721 }
722 // If we get here, this is a definition of a new struct type in a nested
723 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
724 // type.
725 }
726
727 // If there is an identifier, use the location of the identifier as the
728 // location of the decl, otherwise use the location of the struct/union
729 // keyword.
730 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
731
732 // Otherwise, if this is the first time we've seen this tag, create the decl.
733 TagDecl *New;
734 switch (Kind) {
735 default: assert(0 && "Unknown tag kind!");
736 case Decl::Enum:
737 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
738 // enum X { A, B, C } D; D should chain to X.
739 New = new EnumDecl(Loc, Name, 0);
740 // If this is an undefined enum, warn.
741 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
742 break;
743 case Decl::Union:
744 case Decl::Struct:
745 case Decl::Class:
746 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
747 // struct X { int A; } D; D should chain to X.
748 New = new RecordDecl(Kind, Loc, Name, 0);
749 break;
750 }
751
752 // If this has an identifier, add it to the scope stack.
753 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +0000754 // The scope passed in may not be a decl scope. Zip up the scope tree until
755 // we find one that is.
756 while ((S->getFlags() & Scope::DeclScope) == 0)
757 S = S->getParent();
758
759 // Add it to the decl chain.
Chris Lattner4b009652007-07-25 00:24:17 +0000760 New->setNext(Name->getFETokenInfo<Decl>());
761 Name->setFETokenInfo(New);
762 S->AddDecl(New);
763 }
764
765 return New;
766}
767
768/// ParseField - Each field of a struct/union/class is passed into this in order
769/// to create a FieldDecl object for it.
770Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
771 SourceLocation DeclStart,
772 Declarator &D, ExprTy *BitfieldWidth) {
773 IdentifierInfo *II = D.getIdentifier();
774 Expr *BitWidth = (Expr*)BitfieldWidth;
775
776 SourceLocation Loc = DeclStart;
777 if (II) Loc = D.getIdentifierLoc();
778
779 // FIXME: Unnamed fields can be handled in various different ways, for
780 // example, unnamed unions inject all members into the struct namespace!
781
782
783 if (BitWidth) {
784 // TODO: Validate.
785 //printf("WARNING: BITFIELDS IGNORED!\n");
786
787 // 6.7.2.1p3
788 // 6.7.2.1p4
789
790 } else {
791 // Not a bitfield.
792
793 // validate II.
794
795 }
796
797 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000798 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
799 bool InvalidDecl = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000800
801 // C99 6.7.2.1p8: A member of a structure or union may have any type other
802 // than a variably modified type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000803 if (const ArrayType *ary = T->getAsArrayType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000804 if (VerifyConstantArrayType(ary, Loc))
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000805 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000806 }
807
808 // FIXME: Chain fielddecls together.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000809 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
810 if (D.getInvalidType() || InvalidDecl)
811 NewFD->setInvalidDecl();
812 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +0000813}
814
815void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
816 DeclTy **Fields, unsigned NumFields) {
817 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
818 if (Record->isDefinition()) {
819 // Diagnose code like:
820 // struct S { struct S {} X; };
821 // We discover this when we complete the outer S. Reject and ignore the
822 // outer S.
823 Diag(Record->getLocation(), diag::err_nested_redefinition,
824 Record->getKindName());
825 Diag(RecLoc, diag::err_previous_definition);
826 return;
827 }
828
829 // Verify that all the fields are okay.
830 unsigned NumNamedMembers = 0;
831 llvm::SmallVector<FieldDecl*, 32> RecFields;
832 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
833
834 for (unsigned i = 0; i != NumFields; ++i) {
835 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
836 if (!FD) continue; // Already issued a diagnostic.
837
838 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +0000839 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +0000840
841 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +0000842 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000843 Diag(FD->getLocation(), diag::err_field_declared_as_function,
844 FD->getName());
845 delete FD;
846 continue;
847 }
848
849 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
850 if (FDTy->isIncompleteType()) {
851 if (i != NumFields-1 || // ... that the last member ...
852 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +0000853 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +0000854 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
855 delete FD;
856 continue;
857 }
858 if (NumNamedMembers < 1) { //... must have more than named member ...
859 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
860 FD->getName());
861 delete FD;
862 continue;
863 }
864
865 // Okay, we have a legal flexible array member at the end of the struct.
866 Record->setHasFlexibleArrayMember(true);
867 }
868
869
870 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
871 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +0000872 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000873 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
874 // If this is a member of a union, then entire union becomes "flexible".
875 if (Record->getKind() == Decl::Union) {
876 Record->setHasFlexibleArrayMember(true);
877 } else {
878 // If this is a struct/class and this is not the last element, reject
879 // it. Note that GCC supports variable sized arrays in the middle of
880 // structures.
881 if (i != NumFields-1) {
882 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
883 FD->getName());
884 delete FD;
885 continue;
886 }
887
888 // We support flexible arrays at the end of structs in other structs
889 // as an extension.
890 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
891 FD->getName());
892 Record->setHasFlexibleArrayMember(true);
893 }
894 }
895 }
896
897 // Keep track of the number of named members.
898 if (IdentifierInfo *II = FD->getIdentifier()) {
899 // Detect duplicate member names.
900 if (!FieldIDs.insert(II)) {
901 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
902 // Find the previous decl.
903 SourceLocation PrevLoc;
904 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
905 assert(i != e && "Didn't find previous def!");
906 if (RecFields[i]->getIdentifier() == II) {
907 PrevLoc = RecFields[i]->getLocation();
908 break;
909 }
910 }
911 Diag(PrevLoc, diag::err_previous_definition);
912 delete FD;
913 continue;
914 }
915 ++NumNamedMembers;
916 }
917
918 // Remember good fields.
919 RecFields.push_back(FD);
920 }
921
922
923 // Okay, we successfully defined 'Record'.
924 Record->defineBody(&RecFields[0], RecFields.size());
925}
926
927Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
928 DeclTy *lastEnumConst,
929 SourceLocation IdLoc, IdentifierInfo *Id,
930 SourceLocation EqualLoc, ExprTy *val) {
931 theEnumDecl = theEnumDecl; // silence unused warning.
932 EnumConstantDecl *LastEnumConst =
933 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
934 Expr *Val = static_cast<Expr*>(val);
935
Chris Lattnera7549902007-08-26 06:24:45 +0000936 // The scope passed in may not be a decl scope. Zip up the scope tree until
937 // we find one that is.
938 while ((S->getFlags() & Scope::DeclScope) == 0)
939 S = S->getParent();
940
Chris Lattner4b009652007-07-25 00:24:17 +0000941 // Verify that there isn't already something declared with this name in this
942 // scope.
943 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
944 if (S->isDeclScope(PrevDecl)) {
945 if (isa<EnumConstantDecl>(PrevDecl))
946 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
947 else
948 Diag(IdLoc, diag::err_redefinition, Id->getName());
949 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
950 // FIXME: Don't leak memory: delete Val;
951 return 0;
952 }
953 }
954
955 llvm::APSInt EnumVal(32);
956 QualType EltTy;
957 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +0000958 // Make sure to promote the operand type to int.
959 UsualUnaryConversions(Val);
960
Chris Lattner4b009652007-07-25 00:24:17 +0000961 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
962 SourceLocation ExpLoc;
963 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
964 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
965 Id->getName());
966 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +0000967 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +0000968 } else {
969 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000970 }
Chris Lattnere7f53a42007-08-27 17:37:24 +0000971 }
972
973 if (!Val) {
974 if (LastEnumConst) {
975 // Assign the last value + 1.
976 EnumVal = LastEnumConst->getInitVal();
977 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +0000978
979 // Check for overflow on increment.
980 if (EnumVal < LastEnumConst->getInitVal())
981 Diag(IdLoc, diag::warn_enum_value_overflow);
982
Chris Lattnere7f53a42007-08-27 17:37:24 +0000983 EltTy = LastEnumConst->getType();
984 } else {
985 // First value, set to zero.
986 EltTy = Context.IntTy;
Chris Lattner2cda8792007-08-27 21:16:18 +0000987 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnere7f53a42007-08-27 17:37:24 +0000988 }
Chris Lattner4b009652007-07-25 00:24:17 +0000989 }
990
Chris Lattner4b009652007-07-25 00:24:17 +0000991 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
992 LastEnumConst);
993
994 // Register this decl in the current scope stack.
995 New->setNext(Id->getFETokenInfo<Decl>());
996 Id->setFETokenInfo(New);
997 S->AddDecl(New);
998 return New;
999}
1000
1001void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1002 DeclTy **Elements, unsigned NumElements) {
1003 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1004 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1005
Chris Lattner435c3fd2007-08-28 05:10:31 +00001006 // TODO: If the result value doesn't fit in an int, it must be a long or long
1007 // long value. ISO C does not support this, but GCC does as an extension,
1008 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001009 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001010
1011
Chris Lattner206754a2007-08-28 06:15:15 +00001012 // Verify that all the values are okay, compute the size of the values, and
1013 // reverse the list.
1014 unsigned NumNegativeBits = 0;
1015 unsigned NumPositiveBits = 0;
1016
1017 // Keep track of whether all elements have type int.
1018 bool AllElementsInt = true;
1019
Chris Lattner4b009652007-07-25 00:24:17 +00001020 EnumConstantDecl *EltList = 0;
1021 for (unsigned i = 0; i != NumElements; ++i) {
1022 EnumConstantDecl *ECD =
1023 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1024 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001025
1026 // If the enum value doesn't fit in an int, emit an extension warning.
1027 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1028 "Should have promoted value to int");
1029 const llvm::APSInt &InitVal = ECD->getInitVal();
1030 if (InitVal.getBitWidth() > IntWidth) {
1031 llvm::APSInt V(InitVal);
1032 V.trunc(IntWidth);
1033 V.extend(InitVal.getBitWidth());
1034 if (V != InitVal)
1035 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1036 InitVal.toString());
1037 }
Chris Lattner206754a2007-08-28 06:15:15 +00001038
1039 // Keep track of the size of positive and negative values.
1040 if (InitVal.isUnsigned() || !InitVal.isNegative())
1041 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1042 else
1043 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001044
Chris Lattner206754a2007-08-28 06:15:15 +00001045 // Keep track of whether every enum element has type int (very commmon).
1046 if (AllElementsInt)
1047 AllElementsInt = ECD->getType() == Context.IntTy;
1048
Chris Lattner4b009652007-07-25 00:24:17 +00001049 ECD->setNextDeclarator(EltList);
1050 EltList = ECD;
1051 }
1052
Chris Lattner206754a2007-08-28 06:15:15 +00001053 // Figure out the type that should be used for this enum.
1054 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1055 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001056 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001057
1058 if (NumNegativeBits) {
1059 // If there is a negative value, figure out the smallest integer type (of
1060 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001061 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001062 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001063 BestWidth = IntWidth;
1064 } else {
1065 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1066 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001067 BestType = Context.LongTy;
1068 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001069 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1070 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001071 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1072 BestType = Context.LongLongTy;
1073 }
1074 }
1075 } else {
1076 // If there is no negative value, figure out which of uint, ulong, ulonglong
1077 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001078 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001079 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001080 BestWidth = IntWidth;
1081 } else if (NumPositiveBits <=
1082 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001083 BestType = Context.UnsignedLongTy;
1084 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001085 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1086 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001087 "How could an initializer get larger than ULL?");
1088 BestType = Context.UnsignedLongLongTy;
1089 }
1090 }
1091
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001092 // Loop over all of the enumerator constants, changing their types to match
1093 // the type of the enum if needed.
1094 for (unsigned i = 0; i != NumElements; ++i) {
1095 EnumConstantDecl *ECD =
1096 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1097 if (!ECD) continue; // Already issued a diagnostic.
1098
1099 // Standard C says the enumerators have int type, but we allow, as an
1100 // extension, the enumerators to be larger than int size. If each
1101 // enumerator value fits in an int, type it as an int, otherwise type it the
1102 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1103 // that X has type 'int', not 'unsigned'.
1104 if (ECD->getType() == Context.IntTy)
1105 continue; // Already int type.
1106
1107 // Determine whether the value fits into an int.
1108 llvm::APSInt InitVal = ECD->getInitVal();
1109 bool FitsInInt;
1110 if (InitVal.isUnsigned() || !InitVal.isNegative())
1111 FitsInInt = InitVal.getActiveBits() < IntWidth;
1112 else
1113 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1114
1115 // If it fits into an integer type, force it. Otherwise force it to match
1116 // the enum decl type.
1117 QualType NewTy;
1118 unsigned NewWidth;
1119 bool NewSign;
1120 if (FitsInInt) {
1121 NewTy = Context.IntTy;
1122 NewWidth = IntWidth;
1123 NewSign = true;
1124 } else if (ECD->getType() == BestType) {
1125 // Already the right type!
1126 continue;
1127 } else {
1128 NewTy = BestType;
1129 NewWidth = BestWidth;
1130 NewSign = BestType->isSignedIntegerType();
1131 }
1132
1133 // Adjust the APSInt value.
1134 InitVal.extOrTrunc(NewWidth);
1135 InitVal.setIsSigned(NewSign);
1136 ECD->setInitVal(InitVal);
1137
1138 // Adjust the Expr initializer and type.
1139 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1140 ECD->setType(NewTy);
1141 }
Chris Lattner206754a2007-08-28 06:15:15 +00001142
Chris Lattner90a018d2007-08-28 18:24:31 +00001143 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001144}
1145
1146void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1147 if (!current) return;
1148
1149 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1150 // remember this in the LastInGroupList list.
1151 if (last)
1152 LastInGroupList.push_back((Decl*)last);
1153}
1154
1155void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1156 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1157 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1158 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1159 if (!newType.isNull()) // install the new vector type into the decl
1160 vDecl->setType(newType);
1161 }
1162 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1163 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1164 rawAttr);
1165 if (!newType.isNull()) // install the new vector type into the decl
1166 tDecl->setUnderlyingType(newType);
1167 }
1168 }
1169 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001170 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1171 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1172 else
Chris Lattner4b009652007-07-25 00:24:17 +00001173 Diag(rawAttr->getAttributeLoc(),
1174 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001175 }
1176 // FIXME: add other attributes...
1177}
1178
1179void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1180 AttributeList *declarator_postfix) {
1181 while (declspec_prefix) {
1182 HandleDeclAttribute(New, declspec_prefix);
1183 declspec_prefix = declspec_prefix->getNext();
1184 }
1185 while (declarator_postfix) {
1186 HandleDeclAttribute(New, declarator_postfix);
1187 declarator_postfix = declarator_postfix->getNext();
1188 }
1189}
1190
Steve Naroff82113e32007-07-29 16:33:31 +00001191void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1192 AttributeList *rawAttr) {
1193 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001194 // check the attribute arugments.
1195 if (rawAttr->getNumArgs() != 1) {
1196 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1197 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001198 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001199 }
1200 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1201 llvm::APSInt vecSize(32);
1202 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1203 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1204 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001205 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001206 }
1207 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1208 // in conjunction with complex types (pointers, arrays, functions, etc.).
1209 Type *canonType = curType.getCanonicalType().getTypePtr();
1210 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1211 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1212 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001213 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001214 }
1215 // unlike gcc's vector_size attribute, the size is specified as the
1216 // number of elements, not the number of bytes.
1217 unsigned vectorSize = vecSize.getZExtValue();
1218
1219 if (vectorSize == 0) {
1220 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1221 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001222 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001223 }
Steve Naroff82113e32007-07-29 16:33:31 +00001224 // Instantiate/Install the vector type, the number of elements is > 0.
1225 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1226 // Remember this typedef decl, we will need it later for diagnostics.
1227 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001228}
1229
1230QualType Sema::HandleVectorTypeAttribute(QualType curType,
1231 AttributeList *rawAttr) {
1232 // check the attribute arugments.
1233 if (rawAttr->getNumArgs() != 1) {
1234 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1235 std::string("1"));
1236 return QualType();
1237 }
1238 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1239 llvm::APSInt vecSize(32);
1240 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1241 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1242 sizeExpr->getSourceRange());
1243 return QualType();
1244 }
1245 // navigate to the base type - we need to provide for vector pointers,
1246 // vector arrays, and functions returning vectors.
1247 Type *canonType = curType.getCanonicalType().getTypePtr();
1248
1249 if (canonType->isPointerType() || canonType->isArrayType() ||
1250 canonType->isFunctionType()) {
1251 assert(1 && "HandleVector(): Complex type construction unimplemented");
1252 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1253 do {
1254 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1255 canonType = PT->getPointeeType().getTypePtr();
1256 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1257 canonType = AT->getElementType().getTypePtr();
1258 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1259 canonType = FT->getResultType().getTypePtr();
1260 } while (canonType->isPointerType() || canonType->isArrayType() ||
1261 canonType->isFunctionType());
1262 */
1263 }
1264 // the base type must be integer or float.
1265 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1266 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1267 curType.getCanonicalType().getAsString());
1268 return QualType();
1269 }
1270 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
1271 // vecSize is specified in bytes - convert to bits.
1272 unsigned vectorSize = vecSize.getZExtValue() * 8;
1273
1274 // the vector size needs to be an integral multiple of the type size.
1275 if (vectorSize % typeSize) {
1276 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1277 sizeExpr->getSourceRange());
1278 return QualType();
1279 }
1280 if (vectorSize == 0) {
1281 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1282 sizeExpr->getSourceRange());
1283 return QualType();
1284 }
1285 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1286 // the number of elements to be a power of two (unlike GCC).
1287 // Instantiate the vector type, the number of elements is > 0.
1288 return Context.getVectorType(curType, vectorSize/typeSize);
1289}
1290