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