blob: 301813bb187cf8dbdbe4a5a12159e27015175fc1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/SmallSet.h"
26using namespace clang;
27
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) {
Chris Lattner8b9023b2007-07-13 03:05:23 +000032 const Expr *Size = Array->getSizeExpr();
Reid Spencer5f016e22007-07-11 17:01:13 +000033 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);
Chris Lattner590b6642007-07-15 23:26:56 +000044 if (!Size->isIntegerConstantExpr(SizeVal, Context, &Loc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000045 // 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 Lattner31e05722007-08-26 06:24:45 +000081 if (S->decl_empty()) return;
82 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
83
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner70c8b2e2007-08-26 04:02:13 +0000162 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000163
164 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000165 if (Scope *FnS = S->getFnParent())
166 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +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 *
Chris Lattner24c39902007-07-12 00:36:32 +0000280Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 DeclTy *lastDeclarator) {
282 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner24c39902007-07-12 00:36:32 +0000283 Expr *Init = static_cast<Expr*>(init);
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 IdentifierInfo *II = D.getIdentifier();
285
Chris Lattnere80a59c2007-07-25 00:24:17 +0000286 // 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) {
289 Diag(D.getDeclSpec().getSourceRange().Begin(), diag::err_declarator_need_ident,
290 D.getDeclSpec().getSourceRange(), D.getSourceRange());
291 return 0;
292 }
293
Chris Lattner31e05722007-08-26 06:24:45 +0000294 // The scope passed in may not be a decl scope. Zip up the scope tree until
295 // we find one that is.
296 while ((S->getFlags() & Scope::DeclScope) == 0)
297 S = S->getParent();
298
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 // See if this is a redefinition of a variable in the same scope.
300 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
301 D.getIdentifierLoc(), S);
302 if (PrevDecl && !S->isDeclScope(PrevDecl))
303 PrevDecl = 0; // If in outer scope, it isn't the same thing.
304
305 Decl *New;
306 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner24c39902007-07-12 00:36:32 +0000307 assert(Init == 0 && "Can't have initializer for a typedef!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
309 if (!NewTD) return 0;
310
311 // Handle attributes prior to checking for duplicates in MergeVarDecl
312 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
313 D.getAttributes());
314 // Merge the decl with the existing one if appropriate.
315 if (PrevDecl) {
316 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
317 if (NewTD == 0) return 0;
318 }
319 New = NewTD;
320 if (S->getParent() == 0) {
321 // C99 6.7.7p2: If a typedef name specifies a variably modified type
322 // then it shall have block scope.
323 if (ArrayType *ary = dyn_cast<ArrayType>(NewTD->getUnderlyingType())) {
324 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
325 return 0;
326 }
327 }
328 } else if (D.isFunctionDeclarator()) {
Chris Lattner24c39902007-07-12 00:36:32 +0000329 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 QualType R = GetTypeForDeclarator(D, S);
331 if (R.isNull()) return 0; // FIXME: "auto func();" passes through...
Steve Naroff49b45262007-07-13 16:58:59 +0000332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333 FunctionDecl::StorageClass SC;
334 switch (D.getDeclSpec().getStorageClassSpec()) {
335 default: assert(0 && "Unknown storage class!");
336 case DeclSpec::SCS_auto:
337 case DeclSpec::SCS_register:
338 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
339 R.getAsString());
340 return 0;
341 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
342 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
343 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
344 }
345
346 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000347 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 LastDeclarator);
349
350 // Merge the decl with the existing one if appropriate.
351 if (PrevDecl) {
352 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
353 if (NewFD == 0) return 0;
354 }
355 New = NewFD;
356 } else {
357 QualType R = GetTypeForDeclarator(D, S);
358 if (R.isNull()) return 0;
359
360 VarDecl *NewVD;
361 VarDecl::StorageClass SC;
362 switch (D.getDeclSpec().getStorageClassSpec()) {
363 default: assert(0 && "Unknown storage class!");
364 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
365 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
366 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
367 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
368 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
369 }
370 if (S->getParent() == 0) {
371 // File scope. C99 6.9.2p2: A declaration of an identifier for and
372 // object that has file scope without an initializer, and without a
373 // storage-class specifier or with the storage-class specifier "static",
374 // constitutes a tentative definition. Note: A tentative definition with
375 // external linkage is valid (C99 6.2.2p5).
376 if (!Init && SC == VarDecl::Static) {
377 // C99 6.9.2p3: If the declaration of an identifier for an object is
378 // a tentative definition and has internal linkage (C99 6.2.2p3), the
379 // declared type shall not be an incomplete type.
380 if (R->isIncompleteType()) {
381 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
382 R.getAsString());
383 return 0;
384 }
385 }
386 // C99 6.9p2: The storage-class specifiers auto and register shall not
387 // appear in the declaration specifiers in an external declaration.
388 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
389 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
390 R.getAsString());
391 return 0;
392 }
393 // C99 6.7.5.2p2: If an identifier is declared to be an object with
394 // static storage duration, it shall not have a variable length array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000395 if (const ArrayType *ary = R->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
397 return 0;
398 }
399 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
400 } else {
401 // Block scope. C99 6.7p7: If an identifier for an object is declared with
402 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
403 if (SC != VarDecl::Extern) {
404 if (R->isIncompleteType()) {
405 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
406 R.getAsString());
407 return 0;
408 }
409 }
410 if (SC == VarDecl::Static) {
411 // C99 6.7.5.2p2: If an identifier is declared to be an object with
412 // static storage duration, it shall not have a variable length array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000413 if (const ArrayType *ary = R->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 if (VerifyConstantArrayType(ary, D.getIdentifierLoc()))
415 return 0;
416 }
417 }
418 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
419 }
420 // Handle attributes prior to checking for duplicates in MergeVarDecl
421 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
422 D.getAttributes());
423
424 // Merge the decl with the existing one if appropriate.
425 if (PrevDecl) {
426 NewVD = MergeVarDecl(NewVD, PrevDecl);
427 if (NewVD == 0) return 0;
428 }
Steve Narofff1120de2007-08-24 22:33:52 +0000429 if (Init) {
430 AssignmentCheckResult result;
431 result = CheckSingleAssignmentConstraints(R, Init);
432 // FIXME: emit errors if appropriate.
433 NewVD->setInit(Init);
434 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 New = NewVD;
436 }
437
438 // If this has an identifier, add it to the scope stack.
439 if (II) {
440 New->setNext(II->getFETokenInfo<Decl>());
441 II->setFETokenInfo(New);
442 S->AddDecl(New);
443 }
444
445 if (S->getParent() == 0)
446 AddTopLevelDecl(New, LastDeclarator);
447
448 return New;
449}
450
451/// The declarators are chained together backwards, reverse the list.
452Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
453 // Often we have single declarators, handle them quickly.
454 Decl *Group = static_cast<Decl*>(group);
455 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
456
457 Decl *NewGroup = 0;
458 while (Group) {
459 Decl *Next = Group->getNextDeclarator();
460 Group->setNextDeclarator(NewGroup);
461 NewGroup = Group;
462 Group = Next;
463 }
464 return NewGroup;
465}
Steve Naroffe1223f72007-08-28 03:03:08 +0000466
467// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000468ParmVarDecl *
469Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
470 Scope *FnScope) {
471 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
472
473 IdentifierInfo *II = PI.Ident;
474 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
475 // Can this happen for params? We already checked that they don't conflict
476 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000477 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000478 PI.IdentLoc, FnScope)) {
479
480 }
481
482 // FIXME: Handle storage class (auto, register). No declarator?
483 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000484
485 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
486 // Doing the promotion here has a win and a loss. The win is the type for
487 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
488 // code generator). The loss is the orginal type isn't preserved. For example:
489 //
490 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
491 // int blockvardecl[5];
492 // sizeof(parmvardecl); // size == 4
493 // sizeof(blockvardecl); // size == 20
494 // }
495 //
496 // For expressions, all implicit conversions are captured using the
497 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
498 //
499 // FIXME: If a source translation tool needs to see the original type, then
500 // we need to consider storing both types (in ParmVarDecl)...
501 //
502 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
503 if (const ArrayType *AT = parmDeclType->getAsArrayType())
504 parmDeclType = Context.getPointerType(AT->getElementType());
505 else if (parmDeclType->isFunctionType())
506 parmDeclType = Context.getPointerType(parmDeclType);
507
508 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffe1223f72007-08-28 03:03:08 +0000509 VarDecl::None, 0, PI.InvalidType);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510
511 // If this has an identifier, add it to the scope stack.
512 if (II) {
513 New->setNext(II->getFETokenInfo<Decl>());
514 II->setFETokenInfo(New);
515 FnScope->AddDecl(New);
516 }
517
518 return New;
519}
520
521
522Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
523 assert(CurFunctionDecl == 0 && "Function parsing confused");
524 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
525 "Not a function declarator!");
526 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
527
528 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
529 // for a K&R function.
530 if (!FTI.hasPrototype) {
531 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
532 if (FTI.ArgInfo[i].TypeInfo == 0) {
533 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
534 FTI.ArgInfo[i].Ident->getName());
535 // Implicitly declare the argument as type 'int' for lack of a better
536 // type.
537 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
538 }
539 }
540
541 // Since this is a function definition, act as though we have information
542 // about the arguments.
543 FTI.hasPrototype = true;
544 } else {
545 // FIXME: Diagnose arguments without names in C.
546
547 }
548
549 Scope *GlobalScope = FnBodyScope->getParent();
550
551 FunctionDecl *FD =
552 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
553 CurFunctionDecl = FD;
554
555 // Create Decl objects for each parameter, adding them to the FunctionDecl.
556 llvm::SmallVector<ParmVarDecl*, 16> Params;
557
558 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
559 // no arguments, not a function that takes a single void argument.
560 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
561 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
562 // empty arg list, don't push any params.
563 } else {
564 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
565 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
566 }
567
568 FD->setParams(&Params[0], Params.size());
569
570 return FD;
571}
572
573Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
574 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
575 FD->setBody((Stmt*)Body);
576
577 assert(FD == CurFunctionDecl && "Function parsing confused");
578 CurFunctionDecl = 0;
579
580 // Verify and clean out per-function state.
581
582 // Check goto/label use.
583 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
584 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
585 // Verify that we have no forward references left. If so, there was a goto
586 // or address of a label taken, but no definition of it. Label fwd
587 // definitions are indicated with a null substmt.
588 if (I->second->getSubStmt() == 0) {
589 LabelStmt *L = I->second;
590 // Emit error.
591 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
592
593 // At this point, we have gotos that use the bogus label. Stitch it into
594 // the function body so that they aren't leaked and that the AST is well
595 // formed.
596 L->setSubStmt(new NullStmt(L->getIdentLoc()));
597 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
598 }
599 }
600 LabelMap.clear();
601
602 return FD;
603}
604
605
606/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
607/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
608Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
609 Scope *S) {
610 if (getLangOptions().C99) // Extension in C99.
611 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
612 else // Legal in C90, but warn about it.
613 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
614
615 // FIXME: handle stuff like:
616 // void foo() { extern float X(); }
617 // void bar() { X(); } <-- implicit decl for X in another scope.
618
619 // Set a Declarator for the implicit definition: int foo();
620 const char *Dummy;
621 DeclSpec DS;
622 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
623 Error = Error; // Silence warning.
624 assert(!Error && "Error setting up implicit decl!");
625 Declarator D(DS, Declarator::BlockContext);
626 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
627 D.SetIdentifier(&II, Loc);
628
629 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000630 if (Scope *FnS = S->getFnParent())
631 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 while (S->getParent())
633 S = S->getParent();
634
635 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
636}
637
638
639TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
640 Decl *LastDeclarator) {
641 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
642
643 QualType T = GetTypeForDeclarator(D, S);
644 if (T.isNull()) return 0;
645
646 // Scope manipulation handled by caller.
647 return new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(), T,
648 LastDeclarator);
649}
650
651
652/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
653/// former case, Name will be non-null. In the later case, Name will be null.
654/// TagType indicates what kind of tag this is. TK indicates whether this is a
655/// reference/declaration/definition of a tag.
656Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
657 SourceLocation KWLoc, IdentifierInfo *Name,
658 SourceLocation NameLoc, AttributeList *Attr) {
659 // If this is a use of an existing tag, it must have a name.
660 assert((Name != 0 || TK == TK_Definition) &&
661 "Nameless record must be a definition!");
662
663 Decl::Kind Kind;
664 switch (TagType) {
665 default: assert(0 && "Unknown tag type!");
666 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
667 case DeclSpec::TST_union: Kind = Decl::Union; break;
668//case DeclSpec::TST_class: Kind = Decl::Class; break;
669 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
670 }
671
672 // If this is a named struct, check to see if there was a previous forward
673 // declaration or definition.
674 if (TagDecl *PrevDecl =
675 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
676 NameLoc, S))) {
677
678 // If this is a use of a previous tag, or if the tag is already declared in
679 // the same scope (so that the definition/declaration completes or
680 // rementions the tag), reuse the decl.
681 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
682 // Make sure that this wasn't declared as an enum and now used as a struct
683 // or something similar.
684 if (PrevDecl->getKind() != Kind) {
685 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
686 Diag(PrevDecl->getLocation(), diag::err_previous_use);
687 }
688
689 // If this is a use or a forward declaration, we're good.
690 if (TK != TK_Definition)
691 return PrevDecl;
692
693 // Diagnose attempts to redefine a tag.
694 if (PrevDecl->isDefinition()) {
695 Diag(NameLoc, diag::err_redefinition, Name->getName());
696 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
697 // If this is a redefinition, recover by making this struct be
698 // anonymous, which will make any later references get the previous
699 // definition.
700 Name = 0;
701 } else {
702 // Okay, this is definition of a previously declared or referenced tag.
703 // Move the location of the decl to be the definition site.
704 PrevDecl->setLocation(NameLoc);
705 return PrevDecl;
706 }
707 }
708 // If we get here, this is a definition of a new struct type in a nested
709 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
710 // type.
711 }
712
713 // If there is an identifier, use the location of the identifier as the
714 // location of the decl, otherwise use the location of the struct/union
715 // keyword.
716 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
717
718 // Otherwise, if this is the first time we've seen this tag, create the decl.
719 TagDecl *New;
720 switch (Kind) {
721 default: assert(0 && "Unknown tag kind!");
722 case Decl::Enum:
723 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
724 // enum X { A, B, C } D; D should chain to X.
725 New = new EnumDecl(Loc, Name, 0);
726 // If this is an undefined enum, warn.
727 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
728 break;
729 case Decl::Union:
730 case Decl::Struct:
731 case Decl::Class:
732 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
733 // struct X { int A; } D; D should chain to X.
734 New = new RecordDecl(Kind, Loc, Name, 0);
735 break;
736 }
737
738 // If this has an identifier, add it to the scope stack.
739 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +0000740 // The scope passed in may not be a decl scope. Zip up the scope tree until
741 // we find one that is.
742 while ((S->getFlags() & Scope::DeclScope) == 0)
743 S = S->getParent();
744
745 // Add it to the decl chain.
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 New->setNext(Name->getFETokenInfo<Decl>());
747 Name->setFETokenInfo(New);
748 S->AddDecl(New);
749 }
750
751 return New;
752}
753
754/// ParseField - Each field of a struct/union/class is passed into this in order
755/// to create a FieldDecl object for it.
756Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
757 SourceLocation DeclStart,
758 Declarator &D, ExprTy *BitfieldWidth) {
759 IdentifierInfo *II = D.getIdentifier();
760 Expr *BitWidth = (Expr*)BitfieldWidth;
761
762 SourceLocation Loc = DeclStart;
763 if (II) Loc = D.getIdentifierLoc();
764
765 // FIXME: Unnamed fields can be handled in various different ways, for
766 // example, unnamed unions inject all members into the struct namespace!
767
768
769 if (BitWidth) {
770 // TODO: Validate.
771 //printf("WARNING: BITFIELDS IGNORED!\n");
772
773 // 6.7.2.1p3
774 // 6.7.2.1p4
775
776 } else {
777 // Not a bitfield.
778
779 // validate II.
780
781 }
782
783 QualType T = GetTypeForDeclarator(D, S);
784 if (T.isNull()) return 0;
785
786 // C99 6.7.2.1p8: A member of a structure or union may have any type other
787 // than a variably modified type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000788 if (const ArrayType *ary = T->getAsArrayType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 if (VerifyConstantArrayType(ary, Loc))
790 return 0;
791 }
792
793 // FIXME: Chain fielddecls together.
794 return new FieldDecl(Loc, II, T, 0);
795}
796
797void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
798 DeclTy **Fields, unsigned NumFields) {
799 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
800 if (Record->isDefinition()) {
801 // Diagnose code like:
802 // struct S { struct S {} X; };
803 // We discover this when we complete the outer S. Reject and ignore the
804 // outer S.
805 Diag(Record->getLocation(), diag::err_nested_redefinition,
806 Record->getKindName());
807 Diag(RecLoc, diag::err_previous_definition);
808 return;
809 }
810
811 // Verify that all the fields are okay.
812 unsigned NumNamedMembers = 0;
813 llvm::SmallVector<FieldDecl*, 32> RecFields;
814 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
815
816 for (unsigned i = 0; i != NumFields; ++i) {
817 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
818 if (!FD) continue; // Already issued a diagnostic.
819
820 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +0000821 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +0000822
823 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +0000824 if (FDTy->isFunctionType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 Diag(FD->getLocation(), diag::err_field_declared_as_function,
826 FD->getName());
827 delete FD;
828 continue;
829 }
830
831 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
832 if (FDTy->isIncompleteType()) {
833 if (i != NumFields-1 || // ... that the last member ...
834 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +0000835 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
837 delete FD;
838 continue;
839 }
840 if (NumNamedMembers < 1) { //... must have more than named member ...
841 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
842 FD->getName());
843 delete FD;
844 continue;
845 }
846
847 // Okay, we have a legal flexible array member at the end of the struct.
848 Record->setHasFlexibleArrayMember(true);
849 }
850
851
852 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
853 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +0000854 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000855 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
856 // If this is a member of a union, then entire union becomes "flexible".
857 if (Record->getKind() == Decl::Union) {
858 Record->setHasFlexibleArrayMember(true);
859 } else {
860 // If this is a struct/class and this is not the last element, reject
861 // it. Note that GCC supports variable sized arrays in the middle of
862 // structures.
863 if (i != NumFields-1) {
864 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
865 FD->getName());
866 delete FD;
867 continue;
868 }
869
870 // We support flexible arrays at the end of structs in other structs
871 // as an extension.
872 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
873 FD->getName());
874 Record->setHasFlexibleArrayMember(true);
875 }
876 }
877 }
878
879 // Keep track of the number of named members.
880 if (IdentifierInfo *II = FD->getIdentifier()) {
881 // Detect duplicate member names.
882 if (!FieldIDs.insert(II)) {
883 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
884 // Find the previous decl.
885 SourceLocation PrevLoc;
886 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
887 assert(i != e && "Didn't find previous def!");
888 if (RecFields[i]->getIdentifier() == II) {
889 PrevLoc = RecFields[i]->getLocation();
890 break;
891 }
892 }
893 Diag(PrevLoc, diag::err_previous_definition);
894 delete FD;
895 continue;
896 }
897 ++NumNamedMembers;
898 }
899
900 // Remember good fields.
901 RecFields.push_back(FD);
902 }
903
904
905 // Okay, we successfully defined 'Record'.
906 Record->defineBody(&RecFields[0], RecFields.size());
907}
908
909Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
910 DeclTy *lastEnumConst,
911 SourceLocation IdLoc, IdentifierInfo *Id,
912 SourceLocation EqualLoc, ExprTy *val) {
913 theEnumDecl = theEnumDecl; // silence unused warning.
914 EnumConstantDecl *LastEnumConst =
915 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
916 Expr *Val = static_cast<Expr*>(val);
917
Chris Lattner31e05722007-08-26 06:24:45 +0000918 // The scope passed in may not be a decl scope. Zip up the scope tree until
919 // we find one that is.
920 while ((S->getFlags() & Scope::DeclScope) == 0)
921 S = S->getParent();
922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 // Verify that there isn't already something declared with this name in this
924 // scope.
925 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
926 if (S->isDeclScope(PrevDecl)) {
927 if (isa<EnumConstantDecl>(PrevDecl))
928 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
929 else
930 Diag(IdLoc, diag::err_redefinition, Id->getName());
931 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
932 // FIXME: Don't leak memory: delete Val;
933 return 0;
934 }
935 }
936
937 llvm::APSInt EnumVal(32);
938 QualType EltTy;
939 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +0000940 // Make sure to promote the operand type to int.
941 UsualUnaryConversions(Val);
942
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
944 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +0000945 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
947 Id->getName());
948 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +0000949 Val = 0; // Just forget about it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 }
951 EltTy = Val->getType();
Chris Lattnerb7416f92007-08-27 17:37:24 +0000952 }
953
954 if (!Val) {
955 if (LastEnumConst) {
956 // Assign the last value + 1.
957 EnumVal = LastEnumConst->getInitVal();
958 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +0000959
960 // Check for overflow on increment.
961 if (EnumVal < LastEnumConst->getInitVal())
962 Diag(IdLoc, diag::warn_enum_value_overflow);
963
Chris Lattnerb7416f92007-08-27 17:37:24 +0000964 EltTy = LastEnumConst->getType();
965 } else {
966 // First value, set to zero.
967 EltTy = Context.IntTy;
Chris Lattner421a23d2007-08-27 21:16:18 +0000968 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerb7416f92007-08-27 17:37:24 +0000969 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 }
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
973 LastEnumConst);
974
975 // Register this decl in the current scope stack.
976 New->setNext(Id->getFETokenInfo<Decl>());
977 Id->setFETokenInfo(New);
978 S->AddDecl(New);
979 return New;
980}
981
982void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
983 DeclTy **Elements, unsigned NumElements) {
984 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
985 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
986
Chris Lattnere37f0be2007-08-28 05:10:31 +0000987 // TODO: If the result value doesn't fit in an int, it must be a long or long
988 // long value. ISO C does not support this, but GCC does as an extension,
989 // emit a warning.
Chris Lattner211a30e2007-08-28 05:27:00 +0000990 unsigned IntWidth = Context.getTypeSize(Context.IntTy, Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +0000991
992
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 // Verify that all the values are okay, and reverse the list.
994 EnumConstantDecl *EltList = 0;
995 for (unsigned i = 0; i != NumElements; ++i) {
996 EnumConstantDecl *ECD =
997 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
998 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +0000999
1000 // If the enum value doesn't fit in an int, emit an extension warning.
1001 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1002 "Should have promoted value to int");
1003 const llvm::APSInt &InitVal = ECD->getInitVal();
1004 if (InitVal.getBitWidth() > IntWidth) {
1005 llvm::APSInt V(InitVal);
1006 V.trunc(IntWidth);
1007 V.extend(InitVal.getBitWidth());
1008 if (V != InitVal)
1009 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1010 InitVal.toString());
1011 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001012
1013 ECD->setNextDeclarator(EltList);
1014 EltList = ECD;
1015 }
1016
1017 Enum->defineElements(EltList);
1018}
1019
1020void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1021 if (!current) return;
1022
1023 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1024 // remember this in the LastInGroupList list.
1025 if (last)
1026 LastInGroupList.push_back((Decl*)last);
1027}
1028
1029void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1030 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1031 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1032 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1033 if (!newType.isNull()) // install the new vector type into the decl
1034 vDecl->setType(newType);
1035 }
1036 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1037 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1038 rawAttr);
1039 if (!newType.isNull()) // install the new vector type into the decl
1040 tDecl->setUnderlyingType(newType);
1041 }
1042 }
Steve Naroff73322922007-07-18 18:00:27 +00001043 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001044 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1045 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1046 else
Steve Naroff73322922007-07-18 18:00:27 +00001047 Diag(rawAttr->getAttributeLoc(),
1048 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001049 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // FIXME: add other attributes...
1051}
1052
1053void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1054 AttributeList *declarator_postfix) {
1055 while (declspec_prefix) {
1056 HandleDeclAttribute(New, declspec_prefix);
1057 declspec_prefix = declspec_prefix->getNext();
1058 }
1059 while (declarator_postfix) {
1060 HandleDeclAttribute(New, declarator_postfix);
1061 declarator_postfix = declarator_postfix->getNext();
1062 }
1063}
1064
Steve Naroffbea0b342007-07-29 16:33:31 +00001065void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1066 AttributeList *rawAttr) {
1067 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001068 // check the attribute arugments.
1069 if (rawAttr->getNumArgs() != 1) {
1070 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1071 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001072 return;
Steve Naroff73322922007-07-18 18:00:27 +00001073 }
1074 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1075 llvm::APSInt vecSize(32);
1076 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1077 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1078 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001079 return;
Steve Naroff73322922007-07-18 18:00:27 +00001080 }
1081 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1082 // in conjunction with complex types (pointers, arrays, functions, etc.).
1083 Type *canonType = curType.getCanonicalType().getTypePtr();
1084 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1085 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1086 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001087 return;
Steve Naroff73322922007-07-18 18:00:27 +00001088 }
1089 // unlike gcc's vector_size attribute, the size is specified as the
1090 // number of elements, not the number of bytes.
1091 unsigned vectorSize = vecSize.getZExtValue();
1092
1093 if (vectorSize == 0) {
1094 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1095 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001096 return;
Steve Naroff73322922007-07-18 18:00:27 +00001097 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001098 // Instantiate/Install the vector type, the number of elements is > 0.
1099 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1100 // Remember this typedef decl, we will need it later for diagnostics.
1101 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001102}
1103
Reid Spencer5f016e22007-07-11 17:01:13 +00001104QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001105 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // check the attribute arugments.
1107 if (rawAttr->getNumArgs() != 1) {
1108 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1109 std::string("1"));
1110 return QualType();
1111 }
1112 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1113 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001114 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1116 sizeExpr->getSourceRange());
1117 return QualType();
1118 }
1119 // navigate to the base type - we need to provide for vector pointers,
1120 // vector arrays, and functions returning vectors.
1121 Type *canonType = curType.getCanonicalType().getTypePtr();
1122
Steve Naroff73322922007-07-18 18:00:27 +00001123 if (canonType->isPointerType() || canonType->isArrayType() ||
1124 canonType->isFunctionType()) {
1125 assert(1 && "HandleVector(): Complex type construction unimplemented");
1126 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1127 do {
1128 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1129 canonType = PT->getPointeeType().getTypePtr();
1130 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1131 canonType = AT->getElementType().getTypePtr();
1132 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1133 canonType = FT->getResultType().getTypePtr();
1134 } while (canonType->isPointerType() || canonType->isArrayType() ||
1135 canonType->isFunctionType());
1136 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 }
1138 // the base type must be integer or float.
1139 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1140 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1141 curType.getCanonicalType().getAsString());
1142 return QualType();
1143 }
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001144 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // vecSize is specified in bytes - convert to bits.
1146 unsigned vectorSize = vecSize.getZExtValue() * 8;
1147
1148 // the vector size needs to be an integral multiple of the type size.
1149 if (vectorSize % typeSize) {
1150 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1151 sizeExpr->getSourceRange());
1152 return QualType();
1153 }
1154 if (vectorSize == 0) {
1155 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1156 sizeExpr->getSourceRange());
1157 return QualType();
1158 }
1159 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1160 // the number of elements to be a power of two (unlike GCC).
1161 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001162 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163}
1164