blob: 3985d510fdb4ae9c4aaf479a7215b388556b8191 [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"
Gabor Greif7ffc9ed2007-09-18 11:01:25 +000026#include <alloca.h>
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanian25e077d2007-09-17 21:07:36 +000032 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl) ||
33 dyn_cast_or_null<ObjcProtocolDecl>(IIDecl))
Steve Naroff3536b442007-09-06 21:24:23 +000034 return IIDecl;
35 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
38void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000039 if (S->decl_empty()) return;
40 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
41
Reid Spencer5f016e22007-07-11 17:01:13 +000042 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
43 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000044 Decl *TmpD = static_cast<Decl*>(*I);
45 assert(TmpD && "This decl didn't get pushed??");
46 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
47 assert(D && "This decl isn't a ScopedDecl?");
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049 IdentifierInfo *II = D->getIdentifier();
50 if (!II) continue;
51
52 // Unlink this decl from the identifier. Because the scope contains decls
53 // in an unordered collection, and because we have multiple identifier
54 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
55 if (II->getFETokenInfo<Decl>() == D) {
56 // Normal case, no multiple decls in different namespaces.
57 II->setFETokenInfo(D->getNext());
58 } else {
59 // Scan ahead. There are only three namespaces in C, so this loop can
60 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000061 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000062 while (SomeDecl->getNext() != D) {
63 SomeDecl = SomeDecl->getNext();
64 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
65 }
66 SomeDecl->setNext(D->getNext());
67 }
68
69 // This will have to be revisited for C++: there we want to nest stuff in
70 // namespace decls etc. Even for C, we might want a top-level translation
71 // unit decl or something.
72 if (!CurFunctionDecl)
73 continue;
74
75 // Chain this decl to the containing function, it now owns the memory for
76 // the decl.
77 D->setNext(CurFunctionDecl->getDeclChain());
78 CurFunctionDecl->setDeclChain(D);
79 }
80}
81
82/// LookupScopedDecl - Look up the inner-most declaration in the specified
83/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +000084ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
85 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +000086 if (II == 0) return 0;
87 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
88
89 // Scan up the scope chain looking for a decl that matches this identifier
90 // that is in the appropriate namespace. This search should not take long, as
91 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +000092 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +000093 if (D->getIdentifierNamespace() == NS)
94 return D;
95
96 // If we didn't find a use of this identifier, and if the identifier
97 // corresponds to a compiler builtin, create the decl object for the builtin
98 // now, injecting it into translation unit scope, and return it.
99 if (NS == Decl::IDNS_Ordinary) {
100 // If this is a builtin on some other target, or if this builtin varies
101 // across targets (e.g. in type), emit a diagnostic and mark the translation
102 // unit non-portable for using it.
103 if (II->isNonPortableBuiltin()) {
104 // Only emit this diagnostic once for this builtin.
105 II->setNonPortableBuiltin(false);
106 Context.Target.DiagnoseNonPortability(IdLoc,
107 diag::port_target_builtin_use);
108 }
109 // If this is a builtin on this (or all) targets, create the decl.
110 if (unsigned BuiltinID = II->getBuiltinID())
111 return LazilyCreateBuiltin(II, BuiltinID, S);
112 }
113 return 0;
114}
115
116/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
117/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000118ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 Builtin::ID BID = (Builtin::ID)bid;
120
121 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
122 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000123 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000124
125 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000126 if (Scope *FnS = S->getFnParent())
127 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 while (S->getParent())
129 S = S->getParent();
130 S->AddDecl(New);
131
132 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000133 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 // Scan until we find the last (outermost) decl in the id chain.
135 while (LastDecl->getNext())
136 LastDecl = LastDecl->getNext();
137 // Insert before (outside) it.
138 LastDecl->setNext(New);
139 } else {
140 II->setFETokenInfo(New);
141 }
142 // Make sure clients iterating over decls see this.
143 LastInGroupList.push_back(New);
144
145 return New;
146}
147
148/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
149/// and scope as a previous declaration 'Old'. Figure out how to resolve this
150/// situation, merging decls or emitting diagnostics as appropriate.
151///
Steve Naroff8e74c932007-09-13 21:41:19 +0000152TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 // Verify the old decl was also a typedef.
154 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
155 if (!Old) {
156 Diag(New->getLocation(), diag::err_redefinition_different_kind,
157 New->getName());
158 Diag(OldD->getLocation(), diag::err_previous_definition);
159 return New;
160 }
161
162 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
163 // TODO: This is totally simplistic. It should handle merging functions
164 // together etc, merging extern int X; int X; ...
165 Diag(New->getLocation(), diag::err_redefinition, New->getName());
166 Diag(Old->getLocation(), diag::err_previous_definition);
167 return New;
168}
169
170/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
171/// and scope as a previous declaration 'Old'. Figure out how to resolve this
172/// situation, merging decls or emitting diagnostics as appropriate.
173///
Steve Naroff8e74c932007-09-13 21:41:19 +0000174FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 // Verify the old decl was also a function.
176 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
177 if (!Old) {
178 Diag(New->getLocation(), diag::err_redefinition_different_kind,
179 New->getName());
180 Diag(OldD->getLocation(), diag::err_previous_definition);
181 return New;
182 }
183
184 // This is not right, but it's a start. If 'Old' is a function prototype with
185 // the same type as 'New', silently allow this. FIXME: We should link up decl
186 // objects here.
187 if (Old->getBody() == 0 &&
188 Old->getCanonicalType() == New->getCanonicalType()) {
189 return New;
190 }
191
192 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
193 // TODO: This is totally simplistic. It should handle merging functions
194 // together etc, merging extern int X; int X; ...
195 Diag(New->getLocation(), diag::err_redefinition, New->getName());
196 Diag(Old->getLocation(), diag::err_previous_definition);
197 return New;
198}
199
200/// MergeVarDecl - We just parsed a variable 'New' which has the same name
201/// and scope as a previous declaration 'Old'. Figure out how to resolve this
202/// situation, merging decls or emitting diagnostics as appropriate.
203///
204/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
205/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
206///
Steve Naroff8e74c932007-09-13 21:41:19 +0000207VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 // Verify the old decl was also a variable.
209 VarDecl *Old = dyn_cast<VarDecl>(OldD);
210 if (!Old) {
211 Diag(New->getLocation(), diag::err_redefinition_different_kind,
212 New->getName());
213 Diag(OldD->getLocation(), diag::err_previous_definition);
214 return New;
215 }
Steve Narofffb22d962007-08-30 01:06:46 +0000216 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
217 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
218 bool OldIsTentative = false;
219
220 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
221 // Handle C "tentative" external object definitions. FIXME: finish!
222 if (!OldFSDecl->getInit() &&
223 (OldFSDecl->getStorageClass() == VarDecl::None ||
224 OldFSDecl->getStorageClass() == VarDecl::Static))
225 OldIsTentative = true;
226 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000227 // Verify the types match.
228 if (Old->getCanonicalType() != New->getCanonicalType()) {
229 Diag(New->getLocation(), diag::err_redefinition, New->getName());
230 Diag(Old->getLocation(), diag::err_previous_definition);
231 return New;
232 }
233 // We've verified the types match, now check if Old is "extern".
234 if (Old->getStorageClass() != VarDecl::Extern) {
235 Diag(New->getLocation(), diag::err_redefinition, New->getName());
236 Diag(Old->getLocation(), diag::err_previous_definition);
237 }
238 return New;
239}
240
241/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
242/// no declarator (e.g. "struct foo;") is parsed.
243Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
244 // TODO: emit error on 'int;' or 'const enum foo;'.
245 // TODO: emit error on 'typedef int;'
246 // if (!DS.isMissingDeclaratorOk()) Diag(...);
247
248 return 0;
249}
250
Steve Naroff9e8925e2007-09-04 14:36:54 +0000251bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000252 AssignmentCheckResult result;
253 SourceLocation loc = Init->getLocStart();
254 // Get the type before calling CheckSingleAssignmentConstraints(), since
255 // it can promote the expression.
256 QualType rhsType = Init->getType();
257
258 result = CheckSingleAssignmentConstraints(DeclType, Init);
259
260 // decode the result (notice that extensions still return a type).
261 switch (result) {
262 case Compatible:
263 break;
264 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000265 // FIXME: tighten up this check which should allow:
266 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
267 if (rhsType == Context.getPointerType(Context.CharTy))
268 break;
Steve Narofff0090632007-09-02 02:04:30 +0000269 Diag(loc, diag::err_typecheck_assign_incompatible,
270 DeclType.getAsString(), rhsType.getAsString(),
271 Init->getSourceRange());
272 return true;
273 case PointerFromInt:
274 // check for null pointer constant (C99 6.3.2.3p3)
275 if (!Init->isNullPointerConstant(Context)) {
276 Diag(loc, diag::ext_typecheck_assign_pointer_int,
277 DeclType.getAsString(), rhsType.getAsString(),
278 Init->getSourceRange());
279 return true;
280 }
281 break;
282 case IntFromPointer:
283 Diag(loc, diag::ext_typecheck_assign_pointer_int,
284 DeclType.getAsString(), rhsType.getAsString(),
285 Init->getSourceRange());
286 break;
287 case IncompatiblePointer:
288 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
289 DeclType.getAsString(), rhsType.getAsString(),
290 Init->getSourceRange());
291 break;
292 case CompatiblePointerDiscardsQualifiers:
293 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
294 DeclType.getAsString(), rhsType.getAsString(),
295 Init->getSourceRange());
296 break;
297 }
298 return false;
299}
300
Steve Naroff9e8925e2007-09-04 14:36:54 +0000301bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
302 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000303 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000304 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000305
306 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
307 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
308 return true;
309 } else if (CheckSingleInitializer(expr, ElementType)) {
310 return true; // types weren't compatible.
311 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000312 if (savExpr != expr) // The type was promoted, update initializer list.
313 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000314 return false;
315}
316
317void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
318 QualType ElementType, bool isStatic,
319 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000320 for (unsigned i = 0; i < IList->getNumInits(); i++) {
321 Expr *expr = IList->getInit(i);
322
Steve Naroff371227d2007-09-04 02:20:04 +0000323 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
324 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000325 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000326 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
327 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000328 }
Steve Naroff371227d2007-09-04 02:20:04 +0000329 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000330 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000331 }
Steve Naroff371227d2007-09-04 02:20:04 +0000332 nInitializers++;
333 }
334 return;
335}
336
337// FIXME: Doesn't deal with arrays of structures yet.
338void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
339 QualType ElementType, bool isStatic,
340 int &totalInits, bool &hadError) {
341 int maxElementsAtThisLevel = 0;
342 int nInitsAtLevel = 0;
343
344 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
345 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000346 maxElementsAtThisLevel = CAT->getMaximumElements();
347 // Set DeclType, used below to recurse (for multi-dimensional arrays).
348 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000349 } else if (DeclType->isScalarType()) {
350 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
351 IList->getSourceRange());
352 maxElementsAtThisLevel = 1;
353 }
354 // The empty init list "{ }" is treated specially below.
355 unsigned numInits = IList->getNumInits();
356 if (numInits) {
357 for (unsigned i = 0; i < numInits; i++) {
358 Expr *expr = IList->getInit(i);
359
360 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
361 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
362 totalInits, hadError);
363 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000364 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000365 nInitsAtLevel++; // increment the number of initializers at this level.
366 totalInits--; // decrement the total number of initializers.
367
368 // Check if we have space for another initializer.
369 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
370 Diag(expr->getLocStart(), diag::warn_excess_initializers,
371 expr->getSourceRange());
372 }
373 }
374 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
375 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
376 } else {
377 // we have an initializer list with no elements.
378 totalInits -= maxElementsAtThisLevel;
379 if (totalInits < 0)
380 Diag(IList->getLocStart(), diag::warn_excess_initializers,
381 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000382 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000383 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000384}
385
Steve Naroff9e8925e2007-09-04 14:36:54 +0000386bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000387 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000388 if (!InitList)
389 return CheckSingleInitializer(Init, DeclType);
390
Steve Narofff0090632007-09-02 02:04:30 +0000391 // We have an InitListExpr, make sure we set the type.
392 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000393
394 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000395
Steve Naroff38374b02007-09-02 20:30:18 +0000396 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
397 // of unknown size ("[]") or an object type that is not a variable array type.
398 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
399 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000400 if (expr)
401 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
402 expr->getSourceRange());
403
Steve Naroff7cf8c442007-09-04 21:13:33 +0000404 // We have a VariableArrayType with unknown size. Note that only the first
405 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000406 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000407 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
408 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000409 if (!hadError) {
410 // Return a new array type from the number of initializers (C99 6.7.8p22).
411 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000412 ConstVal = numInits;
413 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000414 ArrayType::Normal, 0);
415 }
416 return hadError;
417 }
418 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000419 int maxElements = CAT->getMaximumElements();
420 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
421 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000422 return hadError;
423 }
Steve Naroff371227d2007-09-04 02:20:04 +0000424 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
425 int maxElements = 1;
426 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
427 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000428 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000429 }
430 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000431 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000432}
433
Reid Spencer5f016e22007-07-11 17:01:13 +0000434Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000435Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000436 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 IdentifierInfo *II = D.getIdentifier();
438
Chris Lattnere80a59c2007-07-25 00:24:17 +0000439 // All of these full declarators require an identifier. If it doesn't have
440 // one, the ParsedFreeStandingDeclSpec action should be used.
441 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000442 Diag(D.getDeclSpec().getSourceRange().Begin(),
443 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000444 D.getDeclSpec().getSourceRange(), D.getSourceRange());
445 return 0;
446 }
447
Chris Lattner31e05722007-08-26 06:24:45 +0000448 // The scope passed in may not be a decl scope. Zip up the scope tree until
449 // we find one that is.
450 while ((S->getFlags() & Scope::DeclScope) == 0)
451 S = S->getParent();
452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000454 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
455 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 if (PrevDecl && !S->isDeclScope(PrevDecl))
457 PrevDecl = 0; // If in outer scope, it isn't the same thing.
458
Steve Naroffc752d042007-09-13 18:10:37 +0000459 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000460 bool InvalidDecl = false;
461
Reid Spencer5f016e22007-07-11 17:01:13 +0000462 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
463 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
464 if (!NewTD) return 0;
465
466 // Handle attributes prior to checking for duplicates in MergeVarDecl
467 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
468 D.getAttributes());
469 // Merge the decl with the existing one if appropriate.
470 if (PrevDecl) {
471 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
472 if (NewTD == 0) return 0;
473 }
474 New = NewTD;
475 if (S->getParent() == 0) {
476 // C99 6.7.7p2: If a typedef name specifies a variably modified type
477 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000478 if (const VariableArrayType *VAT =
479 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
480 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
481 VAT->getSizeExpr()->getSourceRange());
482 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 }
484 }
485 } else if (D.isFunctionDeclarator()) {
486 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000487 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000488
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 FunctionDecl::StorageClass SC;
490 switch (D.getDeclSpec().getStorageClassSpec()) {
491 default: assert(0 && "Unknown storage class!");
492 case DeclSpec::SCS_auto:
493 case DeclSpec::SCS_register:
494 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
495 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000496 InvalidDecl = true;
497 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
499 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
500 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
501 }
502
503 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000504 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 LastDeclarator);
506
507 // Merge the decl with the existing one if appropriate.
508 if (PrevDecl) {
509 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
510 if (NewFD == 0) return 0;
511 }
512 New = NewFD;
513 } else {
514 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000515 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000516
517 VarDecl *NewVD;
518 VarDecl::StorageClass SC;
519 switch (D.getDeclSpec().getStorageClassSpec()) {
520 default: assert(0 && "Unknown storage class!");
521 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
522 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
523 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
524 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
525 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
526 }
527 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 // C99 6.9p2: The storage-class specifiers auto and register shall not
529 // appear in the declaration specifiers in an external declaration.
530 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
531 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
532 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000533 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000536 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000538 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 // Handle attributes prior to checking for duplicates in MergeVarDecl
540 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
541 D.getAttributes());
542
543 // Merge the decl with the existing one if appropriate.
544 if (PrevDecl) {
545 NewVD = MergeVarDecl(NewVD, PrevDecl);
546 if (NewVD == 0) return 0;
547 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 New = NewVD;
549 }
550
551 // If this has an identifier, add it to the scope stack.
552 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000553 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 II->setFETokenInfo(New);
555 S->AddDecl(New);
556 }
557
558 if (S->getParent() == 0)
559 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000560
561 // If any semantic error occurred, mark the decl as invalid.
562 if (D.getInvalidType() || InvalidDecl)
563 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000564
565 return New;
566}
567
Steve Naroffbb204692007-09-12 14:07:44 +0000568void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000569 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000570 Expr *Init = static_cast<Expr *>(init);
571
Steve Naroff410e3e22007-09-12 20:13:48 +0000572 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000573
Steve Naroff410e3e22007-09-12 20:13:48 +0000574 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
575 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000576 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
577 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000578 RealDecl->setInvalidDecl();
579 return;
580 }
Steve Naroffbb204692007-09-12 14:07:44 +0000581 // Get the decls type and save a reference for later, since
582 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000583 QualType DclT = VDecl->getType(), SavT = DclT;
584 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000585 VarDecl::StorageClass SC = BVD->getStorageClass();
586 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000587 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000588 BVD->setInvalidDecl();
589 } else if (!BVD->isInvalidDecl()) {
590 CheckInitializer(Init, DclT, SC == VarDecl::Static);
591 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000592 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000593 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000594 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000595 if (!FVD->isInvalidDecl())
596 CheckInitializer(Init, DclT, true);
597 }
598 // If the type changed, it means we had an incomplete type that was
599 // completed by the initializer. For example:
600 // int ary[] = { 1, 3, 5 };
601 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000602 if (!VDecl->isInvalidDecl() && (DclT != SavT))
603 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000604
605 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000606 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000607 return;
608}
609
Reid Spencer5f016e22007-07-11 17:01:13 +0000610/// The declarators are chained together backwards, reverse the list.
611Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
612 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000613 Decl *GroupDecl = static_cast<Decl*>(group);
614 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000615 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000616
617 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
618 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000619 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000620 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000621 else { // reverse the list.
622 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000623 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000624 Group->setNextDeclarator(NewGroup);
625 NewGroup = Group;
626 Group = Next;
627 }
628 }
629 // Perform semantic analysis that depends on having fully processed both
630 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000631 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000632 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
633 if (!IDecl)
634 continue;
635 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
636 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
637 QualType T = IDecl->getType();
638
639 // C99 6.7.5.2p2: If an identifier is declared to be an object with
640 // static storage duration, it shall not have a variable length array.
641 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
642 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
643 if (VLA->getSizeExpr()) {
644 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
645 IDecl->setInvalidDecl();
646 }
647 }
648 }
649 // Block scope. C99 6.7p7: If an identifier for an object is declared with
650 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
651 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
652 if (T->isIncompleteType()) {
653 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
654 T.getAsString());
655 IDecl->setInvalidDecl();
656 }
657 }
658 // File scope. C99 6.9.2p2: A declaration of an identifier for and
659 // object that has file scope without an initializer, and without a
660 // storage-class specifier or with the storage-class specifier "static",
661 // constitutes a tentative definition. Note: A tentative definition with
662 // external linkage is valid (C99 6.2.2p5).
663 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
664 // C99 6.9.2p3: If the declaration of an identifier for an object is
665 // a tentative definition and has internal linkage (C99 6.2.2p3), the
666 // declared type shall not be an incomplete type.
667 if (T->isIncompleteType()) {
668 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
669 T.getAsString());
670 IDecl->setInvalidDecl();
671 }
672 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 }
674 return NewGroup;
675}
Steve Naroffe1223f72007-08-28 03:03:08 +0000676
677// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000678ParmVarDecl *
679Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
680 Scope *FnScope) {
681 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
682
683 IdentifierInfo *II = PI.Ident;
684 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
685 // Can this happen for params? We already checked that they don't conflict
686 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000687 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 PI.IdentLoc, FnScope)) {
689
690 }
691
692 // FIXME: Handle storage class (auto, register). No declarator?
693 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000694
695 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
696 // Doing the promotion here has a win and a loss. The win is the type for
697 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
698 // code generator). The loss is the orginal type isn't preserved. For example:
699 //
700 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
701 // int blockvardecl[5];
702 // sizeof(parmvardecl); // size == 4
703 // sizeof(blockvardecl); // size == 20
704 // }
705 //
706 // For expressions, all implicit conversions are captured using the
707 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
708 //
709 // FIXME: If a source translation tool needs to see the original type, then
710 // we need to consider storing both types (in ParmVarDecl)...
711 //
712 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
713 if (const ArrayType *AT = parmDeclType->getAsArrayType())
714 parmDeclType = Context.getPointerType(AT->getElementType());
715 else if (parmDeclType->isFunctionType())
716 parmDeclType = Context.getPointerType(parmDeclType);
717
718 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000719 VarDecl::None, 0);
720 if (PI.InvalidType)
721 New->setInvalidDecl();
722
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 // If this has an identifier, add it to the scope stack.
724 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000725 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 II->setFETokenInfo(New);
727 FnScope->AddDecl(New);
728 }
729
730 return New;
731}
732
733
734Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
735 assert(CurFunctionDecl == 0 && "Function parsing confused");
736 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
737 "Not a function declarator!");
738 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
739
740 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
741 // for a K&R function.
742 if (!FTI.hasPrototype) {
743 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
744 if (FTI.ArgInfo[i].TypeInfo == 0) {
745 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
746 FTI.ArgInfo[i].Ident->getName());
747 // Implicitly declare the argument as type 'int' for lack of a better
748 // type.
749 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
750 }
751 }
752
753 // Since this is a function definition, act as though we have information
754 // about the arguments.
755 FTI.hasPrototype = true;
756 } else {
757 // FIXME: Diagnose arguments without names in C.
758
759 }
760
761 Scope *GlobalScope = FnBodyScope->getParent();
762
763 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000764 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 CurFunctionDecl = FD;
766
767 // Create Decl objects for each parameter, adding them to the FunctionDecl.
768 llvm::SmallVector<ParmVarDecl*, 16> Params;
769
770 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
771 // no arguments, not a function that takes a single void argument.
772 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
773 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
774 // empty arg list, don't push any params.
775 } else {
776 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
777 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
778 }
779
780 FD->setParams(&Params[0], Params.size());
781
782 return FD;
783}
784
785Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
786 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
787 FD->setBody((Stmt*)Body);
788
789 assert(FD == CurFunctionDecl && "Function parsing confused");
790 CurFunctionDecl = 0;
791
792 // Verify and clean out per-function state.
793
794 // Check goto/label use.
795 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
796 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
797 // Verify that we have no forward references left. If so, there was a goto
798 // or address of a label taken, but no definition of it. Label fwd
799 // definitions are indicated with a null substmt.
800 if (I->second->getSubStmt() == 0) {
801 LabelStmt *L = I->second;
802 // Emit error.
803 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
804
805 // At this point, we have gotos that use the bogus label. Stitch it into
806 // the function body so that they aren't leaked and that the AST is well
807 // formed.
808 L->setSubStmt(new NullStmt(L->getIdentLoc()));
809 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
810 }
811 }
812 LabelMap.clear();
813
814 return FD;
815}
816
817
818/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
819/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000820ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
821 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 if (getLangOptions().C99) // Extension in C99.
823 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
824 else // Legal in C90, but warn about it.
825 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
826
827 // FIXME: handle stuff like:
828 // void foo() { extern float X(); }
829 // void bar() { X(); } <-- implicit decl for X in another scope.
830
831 // Set a Declarator for the implicit definition: int foo();
832 const char *Dummy;
833 DeclSpec DS;
834 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
835 Error = Error; // Silence warning.
836 assert(!Error && "Error setting up implicit decl!");
837 Declarator D(DS, Declarator::BlockContext);
838 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
839 D.SetIdentifier(&II, Loc);
840
841 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000842 if (Scope *FnS = S->getFnParent())
843 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000844 while (S->getParent())
845 S = S->getParent();
846
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000847 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000848}
849
850
851TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000852 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
854
855 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000856 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000857
858 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000859 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
860 T, LastDeclarator);
861 if (D.getInvalidType())
862 NewTD->setInvalidDecl();
863 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000864}
865
Steve Naroff3536b442007-09-06 21:24:23 +0000866Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
867 IdentifierInfo *ClassName, SourceLocation ClassLoc,
868 IdentifierInfo *SuperName, SourceLocation SuperLoc,
869 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
870 AttributeList *AttrList) {
871 assert(ClassName && "Missing class identifier");
872 ObjcInterfaceDecl *IDecl;
873
874 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
875
876 // Chain & install the interface decl into the identifier.
Steve Naroffc752d042007-09-13 18:10:37 +0000877 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000878 ClassName->setFETokenInfo(IDecl);
879 return IDecl;
880}
881
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000882Sema::DeclTy *Sema::ObjcStartProtoInterface(SourceLocation AtProtoInterfaceLoc,
883 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
884 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
885 assert(ProtocolName && "Missing protocol identifier");
886 ObjcProtocolDecl *PDecl;
887
888 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, ProtocolName);
889
890 // Chain & install the protocol decl into the identifier.
891 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
892 ProtocolName->setFETokenInfo(PDecl);
893 return PDecl;
894}
895
Steve Naroff3536b442007-09-06 21:24:23 +0000896/// ObjcClassDeclaration -
897/// Scope will always be top level file scope.
898Action::DeclTy *
899Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
900 IdentifierInfo **IdentList, unsigned NumElts) {
901 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
902
903 for (unsigned i = 0; i != NumElts; ++i) {
904 ObjcInterfaceDecl *IDecl;
905
Steve Naroff2bd42fa2007-09-10 20:51:04 +0000906 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff3536b442007-09-06 21:24:23 +0000907 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
908 // Chain & install the interface decl into the identifier.
Steve Naroffc752d042007-09-13 18:10:37 +0000909 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff3536b442007-09-06 21:24:23 +0000910 IdentList[i]->setFETokenInfo(IDecl);
911
912 // Remember that this needs to be removed when the scope is popped.
913 S->AddDecl(IdentList[i]);
914
915 CDecl->setInterfaceDecl((int)i, IDecl);
916 }
917 return CDecl;
918}
919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920
Steve Naroff08d92e42007-09-15 18:49:24 +0000921/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +0000922/// former case, Name will be non-null. In the later case, Name will be null.
923/// TagType indicates what kind of tag this is. TK indicates whether this is a
924/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +0000925Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 SourceLocation KWLoc, IdentifierInfo *Name,
927 SourceLocation NameLoc, AttributeList *Attr) {
928 // If this is a use of an existing tag, it must have a name.
929 assert((Name != 0 || TK == TK_Definition) &&
930 "Nameless record must be a definition!");
931
932 Decl::Kind Kind;
933 switch (TagType) {
934 default: assert(0 && "Unknown tag type!");
935 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
936 case DeclSpec::TST_union: Kind = Decl::Union; break;
937//case DeclSpec::TST_class: Kind = Decl::Class; break;
938 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
939 }
940
941 // If this is a named struct, check to see if there was a previous forward
942 // declaration or definition.
943 if (TagDecl *PrevDecl =
944 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
945 NameLoc, S))) {
946
947 // If this is a use of a previous tag, or if the tag is already declared in
948 // the same scope (so that the definition/declaration completes or
949 // rementions the tag), reuse the decl.
950 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
951 // Make sure that this wasn't declared as an enum and now used as a struct
952 // or something similar.
953 if (PrevDecl->getKind() != Kind) {
954 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
955 Diag(PrevDecl->getLocation(), diag::err_previous_use);
956 }
957
958 // If this is a use or a forward declaration, we're good.
959 if (TK != TK_Definition)
960 return PrevDecl;
961
962 // Diagnose attempts to redefine a tag.
963 if (PrevDecl->isDefinition()) {
964 Diag(NameLoc, diag::err_redefinition, Name->getName());
965 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
966 // If this is a redefinition, recover by making this struct be
967 // anonymous, which will make any later references get the previous
968 // definition.
969 Name = 0;
970 } else {
971 // Okay, this is definition of a previously declared or referenced tag.
972 // Move the location of the decl to be the definition site.
973 PrevDecl->setLocation(NameLoc);
974 return PrevDecl;
975 }
976 }
977 // If we get here, this is a definition of a new struct type in a nested
978 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
979 // type.
980 }
981
982 // If there is an identifier, use the location of the identifier as the
983 // location of the decl, otherwise use the location of the struct/union
984 // keyword.
985 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
986
987 // Otherwise, if this is the first time we've seen this tag, create the decl.
988 TagDecl *New;
989 switch (Kind) {
990 default: assert(0 && "Unknown tag kind!");
991 case Decl::Enum:
992 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
993 // enum X { A, B, C } D; D should chain to X.
994 New = new EnumDecl(Loc, Name, 0);
995 // If this is an undefined enum, warn.
996 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
997 break;
998 case Decl::Union:
999 case Decl::Struct:
1000 case Decl::Class:
1001 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1002 // struct X { int A; } D; D should chain to X.
1003 New = new RecordDecl(Kind, Loc, Name, 0);
1004 break;
1005 }
1006
1007 // If this has an identifier, add it to the scope stack.
1008 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001009 // The scope passed in may not be a decl scope. Zip up the scope tree until
1010 // we find one that is.
1011 while ((S->getFlags() & Scope::DeclScope) == 0)
1012 S = S->getParent();
1013
1014 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001015 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 Name->setFETokenInfo(New);
1017 S->AddDecl(New);
1018 }
1019
1020 return New;
1021}
1022
Steve Naroff08d92e42007-09-15 18:49:24 +00001023/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001024/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001025Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 SourceLocation DeclStart,
1027 Declarator &D, ExprTy *BitfieldWidth) {
1028 IdentifierInfo *II = D.getIdentifier();
1029 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 SourceLocation Loc = DeclStart;
1031 if (II) Loc = D.getIdentifierLoc();
1032
1033 // FIXME: Unnamed fields can be handled in various different ways, for
1034 // example, unnamed unions inject all members into the struct namespace!
1035
1036
1037 if (BitWidth) {
1038 // TODO: Validate.
1039 //printf("WARNING: BITFIELDS IGNORED!\n");
1040
1041 // 6.7.2.1p3
1042 // 6.7.2.1p4
1043
1044 } else {
1045 // Not a bitfield.
1046
1047 // validate II.
1048
1049 }
1050
1051 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001052 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1053 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001054
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1056 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001057 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1058 Diag(Loc, diag::err_typecheck_illegal_vla,
1059 VAT->getSizeExpr()->getSourceRange());
1060 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001063 FieldDecl *NewFD;
1064
1065 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001066 NewFD = new FieldDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001067 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001068 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001069 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001070 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001071
Steve Naroff5912a352007-08-28 20:14:24 +00001072 if (D.getInvalidType() || InvalidDecl)
1073 NewFD->setInvalidDecl();
1074 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001075}
1076
Steve Narofff13271f2007-09-14 23:09:53 +00001077static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1078 tok::ObjCKeywordKind ivarVisibility) {
1079 assert(OIvar && "missing instance variable");
1080 switch (ivarVisibility) {
1081 case tok::objc_private:
1082 OIvar->setAccessControl(ObjcIvarDecl::Private);
1083 break;
1084 case tok::objc_public:
1085 OIvar->setAccessControl(ObjcIvarDecl::Public);
1086 break;
1087 case tok::objc_protected:
1088 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1089 break;
1090 case tok::objc_package:
1091 OIvar->setAccessControl(ObjcIvarDecl::Package);
1092 break;
1093 default:
1094 OIvar->setAccessControl(ObjcIvarDecl::None);
1095 break;
1096 }
1097}
1098
Steve Naroff08d92e42007-09-15 18:49:24 +00001099void Sema::ActOnFields(SourceLocation RecLoc, DeclTy *RecDecl,
1100 DeclTy **Fields, unsigned NumFields,
1101 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001102 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1103 assert(EnclosingDecl && "missing record or interface decl");
1104 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1105
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001106 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // Diagnose code like:
1108 // struct S { struct S {} X; };
1109 // We discover this when we complete the outer S. Reject and ignore the
1110 // outer S.
1111 Diag(Record->getLocation(), diag::err_nested_redefinition,
1112 Record->getKindName());
1113 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001114 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001115 return;
1116 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001117 // Verify that all the fields are okay.
1118 unsigned NumNamedMembers = 0;
1119 llvm::SmallVector<FieldDecl*, 32> RecFields;
1120 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001121
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001123
Steve Naroff74216642007-09-14 22:20:54 +00001124 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1125 assert(FD && "missing field decl");
1126
1127 // Remember all fields.
1128 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001129
1130 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001131 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001132
Steve Narofff13271f2007-09-14 23:09:53 +00001133 // If we have visibility info, make sure the AST is set accordingly.
1134 if (visibility)
1135 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1136
Reid Spencer5f016e22007-07-11 17:01:13 +00001137 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001138 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001139 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001141 FD->setInvalidDecl();
1142 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 continue;
1144 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1146 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001147 if (!Record) { // Incomplete ivar type is always an error.
1148 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001149 FD->setInvalidDecl();
1150 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001151 continue;
1152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001153 if (i != NumFields-1 || // ... that the last member ...
1154 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001155 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001156 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001157 FD->setInvalidDecl();
1158 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 continue;
1160 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001161 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1163 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001164 FD->setInvalidDecl();
1165 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 continue;
1167 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001169 if (Record)
1170 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1173 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001174 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1176 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001177 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 Record->setHasFlexibleArrayMember(true);
1179 } else {
1180 // If this is a struct/class and this is not the last element, reject
1181 // it. Note that GCC supports variable sized arrays in the middle of
1182 // structures.
1183 if (i != NumFields-1) {
1184 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1185 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001186 FD->setInvalidDecl();
1187 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001188 continue;
1189 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 // We support flexible arrays at the end of structs in other structs
1191 // as an extension.
1192 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1193 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001194 if (Record)
1195 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001196 }
1197 }
1198 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 // Keep track of the number of named members.
1200 if (IdentifierInfo *II = FD->getIdentifier()) {
1201 // Detect duplicate member names.
1202 if (!FieldIDs.insert(II)) {
1203 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1204 // Find the previous decl.
1205 SourceLocation PrevLoc;
1206 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1207 assert(i != e && "Didn't find previous def!");
1208 if (RecFields[i]->getIdentifier() == II) {
1209 PrevLoc = RecFields[i]->getLocation();
1210 break;
1211 }
1212 }
1213 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001214 FD->setInvalidDecl();
1215 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 continue;
1217 }
1218 ++NumNamedMembers;
1219 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001220 }
1221
Reid Spencer5f016e22007-07-11 17:01:13 +00001222 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001223 if (Record)
1224 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001225 else {
1226 ObjcIvarDecl **ClsFields =
1227 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
1228 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1229 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1230 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001231}
1232
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001233void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1234 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001235 // FIXME: Fix this when we can handle methods declared in protocols.
1236 // See Parser::ParseObjCAtProtocolDeclaration
1237 if (!ClassDecl)
1238 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001239 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1240 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1241
1242 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001243 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001244 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1245 if (!Method) continue; // Already issued a diagnostic.
1246 if (Method->isInstance())
1247 insMethods.push_back(Method);
1248 else
1249 clsMethods.push_back(Method);
1250 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001251 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1252 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1253 static_cast<Decl*>(ClassDecl));
1254 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1255 &clsMethods[0], clsMethods.size());
1256 }
1257 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1258 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1259 static_cast<Decl*>(ClassDecl));
1260 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1261 &clsMethods[0], clsMethods.size());
1262 }
1263 else
1264 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001265 return;
1266}
1267
Fariborz Jahanian00933592007-09-18 00:25:23 +00001268Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff37387c92007-09-17 20:25:27 +00001269 tok::TokenKind MethodType, TypeTy *ReturnType,
1270 ObjcKeywordDecl *Keywords, unsigned NumKeywords,
Fariborz Jahanian00933592007-09-18 00:25:23 +00001271 AttributeList *AttrList,
1272 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff37387c92007-09-17 20:25:27 +00001273 assert(NumKeywords && "Selector must be specified");
1274
1275 // Derive the selector name from the keyword declarations.
Steve Naroff3f128ad2007-09-17 14:16:13 +00001276 int len=0;
1277 char *methodName;
Steve Naroff37387c92007-09-17 20:25:27 +00001278 for (unsigned int i = 0; i < NumKeywords; i++) {
1279 if (Keywords[i].SelectorName)
1280 len += strlen(Keywords[i].SelectorName->getName());
Steve Naroff3f128ad2007-09-17 14:16:13 +00001281 len++;
1282 }
1283 methodName = (char *) alloca (len + 1);
1284 methodName[0] = '\0';
Steve Naroff37387c92007-09-17 20:25:27 +00001285 for (unsigned int i = 0; i < NumKeywords; i++) {
1286 if (Keywords[i].SelectorName)
1287 strcat(methodName, Keywords[i].SelectorName->getName());
Steve Naroff3f128ad2007-09-17 14:16:13 +00001288 strcat(methodName, ":");
1289 }
Steve Naroff37387c92007-09-17 20:25:27 +00001290 SelectorInfo &SelName = Context.getSelectorInfo(methodName, methodName+len);
Steve Naroff3f128ad2007-09-17 14:16:13 +00001291
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001292 llvm::SmallVector<ParmVarDecl*, 16> Params;
1293
1294 for (unsigned i = 0; i < NumKeywords; i++) {
Steve Naroff37387c92007-09-17 20:25:27 +00001295 ObjcKeywordDecl *arg = &Keywords[i];
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001296 // FIXME: arg->AttrList must be stored too!
1297 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1298 QualType::getFromOpaquePtr(arg->TypeInfo),
1299 VarDecl::None, 0);
1300 // FIXME: 'InvalidType' does not get set by caller yet.
1301 if (arg->InvalidType)
1302 Param->setInvalidDecl();
1303 Params.push_back(Param);
1304 }
1305 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001306 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1307 SelName, resultDeclType,
1308 0, -1, AttrList, MethodType == tok::minus);
1309 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
Fariborz Jahanian00933592007-09-18 00:25:23 +00001310 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001311 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001312 else
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001313 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001314 return ObjcMethod;
1315}
1316
Fariborz Jahanian00933592007-09-18 00:25:23 +00001317Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001318 tok::TokenKind MethodType, TypeTy *ReturnType,
Fariborz Jahanian00933592007-09-18 00:25:23 +00001319 IdentifierInfo *SelectorName, AttributeList *AttrList,
1320 tok::ObjCKeywordKind MethodDeclKind) {
Steve Naroff3f128ad2007-09-17 14:16:13 +00001321 const char *methodName = SelectorName->getName();
1322 SelectorInfo &SelName = Context.getSelectorInfo(methodName,
1323 methodName+strlen(methodName));
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001324 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001325 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1326 SelName, resultDeclType, 0, -1,
1327 AttrList, MethodType == tok::minus);
Fariborz Jahanian00933592007-09-18 00:25:23 +00001328 if (MethodDeclKind == tok::objc_optional)
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001329 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001330 else
Fariborz Jahanian146fbb02007-09-17 22:36:42 +00001331 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001332 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001333}
1334
Steve Naroff08d92e42007-09-15 18:49:24 +00001335Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001336 DeclTy *lastEnumConst,
1337 SourceLocation IdLoc, IdentifierInfo *Id,
1338 SourceLocation EqualLoc, ExprTy *val) {
1339 theEnumDecl = theEnumDecl; // silence unused warning.
1340 EnumConstantDecl *LastEnumConst =
1341 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1342 Expr *Val = static_cast<Expr*>(val);
1343
Chris Lattner31e05722007-08-26 06:24:45 +00001344 // The scope passed in may not be a decl scope. Zip up the scope tree until
1345 // we find one that is.
1346 while ((S->getFlags() & Scope::DeclScope) == 0)
1347 S = S->getParent();
1348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // Verify that there isn't already something declared with this name in this
1350 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001351 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1352 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 if (S->isDeclScope(PrevDecl)) {
1354 if (isa<EnumConstantDecl>(PrevDecl))
1355 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1356 else
1357 Diag(IdLoc, diag::err_redefinition, Id->getName());
1358 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1359 // FIXME: Don't leak memory: delete Val;
1360 return 0;
1361 }
1362 }
1363
1364 llvm::APSInt EnumVal(32);
1365 QualType EltTy;
1366 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001367 // Make sure to promote the operand type to int.
1368 UsualUnaryConversions(Val);
1369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1371 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001372 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1374 Id->getName());
1375 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001376 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001377 } else {
1378 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001380 }
1381
1382 if (!Val) {
1383 if (LastEnumConst) {
1384 // Assign the last value + 1.
1385 EnumVal = LastEnumConst->getInitVal();
1386 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001387
1388 // Check for overflow on increment.
1389 if (EnumVal < LastEnumConst->getInitVal())
1390 Diag(IdLoc, diag::warn_enum_value_overflow);
1391
Chris Lattnerb7416f92007-08-27 17:37:24 +00001392 EltTy = LastEnumConst->getType();
1393 } else {
1394 // First value, set to zero.
1395 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001396 EnumVal.zextOrTrunc(
1397 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001398 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 }
1400
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1402 LastEnumConst);
1403
1404 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001405 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 Id->setFETokenInfo(New);
1407 S->AddDecl(New);
1408 return New;
1409}
1410
Steve Naroff08d92e42007-09-15 18:49:24 +00001411void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 DeclTy **Elements, unsigned NumElements) {
1413 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1414 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1415
Chris Lattnere37f0be2007-08-28 05:10:31 +00001416 // TODO: If the result value doesn't fit in an int, it must be a long or long
1417 // long value. ISO C does not support this, but GCC does as an extension,
1418 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001419 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001420
1421
Chris Lattnerac609682007-08-28 06:15:15 +00001422 // Verify that all the values are okay, compute the size of the values, and
1423 // reverse the list.
1424 unsigned NumNegativeBits = 0;
1425 unsigned NumPositiveBits = 0;
1426
1427 // Keep track of whether all elements have type int.
1428 bool AllElementsInt = true;
1429
Reid Spencer5f016e22007-07-11 17:01:13 +00001430 EnumConstantDecl *EltList = 0;
1431 for (unsigned i = 0; i != NumElements; ++i) {
1432 EnumConstantDecl *ECD =
1433 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1434 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001435
1436 // If the enum value doesn't fit in an int, emit an extension warning.
1437 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1438 "Should have promoted value to int");
1439 const llvm::APSInt &InitVal = ECD->getInitVal();
1440 if (InitVal.getBitWidth() > IntWidth) {
1441 llvm::APSInt V(InitVal);
1442 V.trunc(IntWidth);
1443 V.extend(InitVal.getBitWidth());
1444 if (V != InitVal)
1445 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1446 InitVal.toString());
1447 }
Chris Lattnerac609682007-08-28 06:15:15 +00001448
1449 // Keep track of the size of positive and negative values.
1450 if (InitVal.isUnsigned() || !InitVal.isNegative())
1451 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1452 else
1453 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001454
Chris Lattnerac609682007-08-28 06:15:15 +00001455 // Keep track of whether every enum element has type int (very commmon).
1456 if (AllElementsInt)
1457 AllElementsInt = ECD->getType() == Context.IntTy;
1458
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 ECD->setNextDeclarator(EltList);
1460 EltList = ECD;
1461 }
1462
Chris Lattnerac609682007-08-28 06:15:15 +00001463 // Figure out the type that should be used for this enum.
1464 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1465 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001466 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001467
1468 if (NumNegativeBits) {
1469 // If there is a negative value, figure out the smallest integer type (of
1470 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001471 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001472 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001473 BestWidth = IntWidth;
1474 } else {
1475 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1476 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001477 BestType = Context.LongTy;
1478 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001479 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1480 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001481 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1482 BestType = Context.LongLongTy;
1483 }
1484 }
1485 } else {
1486 // If there is no negative value, figure out which of uint, ulong, ulonglong
1487 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001488 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001489 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001490 BestWidth = IntWidth;
1491 } else if (NumPositiveBits <=
1492 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001493 BestType = Context.UnsignedLongTy;
1494 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001495 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1496 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001497 "How could an initializer get larger than ULL?");
1498 BestType = Context.UnsignedLongLongTy;
1499 }
1500 }
1501
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001502 // Loop over all of the enumerator constants, changing their types to match
1503 // the type of the enum if needed.
1504 for (unsigned i = 0; i != NumElements; ++i) {
1505 EnumConstantDecl *ECD =
1506 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1507 if (!ECD) continue; // Already issued a diagnostic.
1508
1509 // Standard C says the enumerators have int type, but we allow, as an
1510 // extension, the enumerators to be larger than int size. If each
1511 // enumerator value fits in an int, type it as an int, otherwise type it the
1512 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1513 // that X has type 'int', not 'unsigned'.
1514 if (ECD->getType() == Context.IntTy)
1515 continue; // Already int type.
1516
1517 // Determine whether the value fits into an int.
1518 llvm::APSInt InitVal = ECD->getInitVal();
1519 bool FitsInInt;
1520 if (InitVal.isUnsigned() || !InitVal.isNegative())
1521 FitsInInt = InitVal.getActiveBits() < IntWidth;
1522 else
1523 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1524
1525 // If it fits into an integer type, force it. Otherwise force it to match
1526 // the enum decl type.
1527 QualType NewTy;
1528 unsigned NewWidth;
1529 bool NewSign;
1530 if (FitsInInt) {
1531 NewTy = Context.IntTy;
1532 NewWidth = IntWidth;
1533 NewSign = true;
1534 } else if (ECD->getType() == BestType) {
1535 // Already the right type!
1536 continue;
1537 } else {
1538 NewTy = BestType;
1539 NewWidth = BestWidth;
1540 NewSign = BestType->isSignedIntegerType();
1541 }
1542
1543 // Adjust the APSInt value.
1544 InitVal.extOrTrunc(NewWidth);
1545 InitVal.setIsSigned(NewSign);
1546 ECD->setInitVal(InitVal);
1547
1548 // Adjust the Expr initializer and type.
1549 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1550 ECD->setType(NewTy);
1551 }
Chris Lattnerac609682007-08-28 06:15:15 +00001552
Chris Lattnere00b18c2007-08-28 18:24:31 +00001553 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554}
1555
1556void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1557 if (!current) return;
1558
1559 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1560 // remember this in the LastInGroupList list.
1561 if (last)
1562 LastInGroupList.push_back((Decl*)last);
1563}
1564
1565void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1566 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1567 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1568 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1569 if (!newType.isNull()) // install the new vector type into the decl
1570 vDecl->setType(newType);
1571 }
1572 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1573 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1574 rawAttr);
1575 if (!newType.isNull()) // install the new vector type into the decl
1576 tDecl->setUnderlyingType(newType);
1577 }
1578 }
Steve Naroff73322922007-07-18 18:00:27 +00001579 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001580 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1581 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1582 else
Steve Naroff73322922007-07-18 18:00:27 +00001583 Diag(rawAttr->getAttributeLoc(),
1584 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001585 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 // FIXME: add other attributes...
1587}
1588
1589void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1590 AttributeList *declarator_postfix) {
1591 while (declspec_prefix) {
1592 HandleDeclAttribute(New, declspec_prefix);
1593 declspec_prefix = declspec_prefix->getNext();
1594 }
1595 while (declarator_postfix) {
1596 HandleDeclAttribute(New, declarator_postfix);
1597 declarator_postfix = declarator_postfix->getNext();
1598 }
1599}
1600
Steve Naroffbea0b342007-07-29 16:33:31 +00001601void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1602 AttributeList *rawAttr) {
1603 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001604 // check the attribute arugments.
1605 if (rawAttr->getNumArgs() != 1) {
1606 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1607 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001608 return;
Steve Naroff73322922007-07-18 18:00:27 +00001609 }
1610 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1611 llvm::APSInt vecSize(32);
1612 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1613 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1614 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001615 return;
Steve Naroff73322922007-07-18 18:00:27 +00001616 }
1617 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1618 // in conjunction with complex types (pointers, arrays, functions, etc.).
1619 Type *canonType = curType.getCanonicalType().getTypePtr();
1620 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1621 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1622 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001623 return;
Steve Naroff73322922007-07-18 18:00:27 +00001624 }
1625 // unlike gcc's vector_size attribute, the size is specified as the
1626 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001627 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001628
1629 if (vectorSize == 0) {
1630 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1631 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001632 return;
Steve Naroff73322922007-07-18 18:00:27 +00001633 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001634 // Instantiate/Install the vector type, the number of elements is > 0.
1635 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1636 // Remember this typedef decl, we will need it later for diagnostics.
1637 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001638}
1639
Reid Spencer5f016e22007-07-11 17:01:13 +00001640QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001641 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 // check the attribute arugments.
1643 if (rawAttr->getNumArgs() != 1) {
1644 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1645 std::string("1"));
1646 return QualType();
1647 }
1648 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1649 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001650 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1652 sizeExpr->getSourceRange());
1653 return QualType();
1654 }
1655 // navigate to the base type - we need to provide for vector pointers,
1656 // vector arrays, and functions returning vectors.
1657 Type *canonType = curType.getCanonicalType().getTypePtr();
1658
Steve Naroff73322922007-07-18 18:00:27 +00001659 if (canonType->isPointerType() || canonType->isArrayType() ||
1660 canonType->isFunctionType()) {
1661 assert(1 && "HandleVector(): Complex type construction unimplemented");
1662 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1663 do {
1664 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1665 canonType = PT->getPointeeType().getTypePtr();
1666 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1667 canonType = AT->getElementType().getTypePtr();
1668 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1669 canonType = FT->getResultType().getTypePtr();
1670 } while (canonType->isPointerType() || canonType->isArrayType() ||
1671 canonType->isFunctionType());
1672 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001673 }
1674 // the base type must be integer or float.
1675 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1676 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1677 curType.getCanonicalType().getAsString());
1678 return QualType();
1679 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001680 unsigned typeSize = static_cast<unsigned>(
1681 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001683 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001684
1685 // the vector size needs to be an integral multiple of the type size.
1686 if (vectorSize % typeSize) {
1687 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1688 sizeExpr->getSourceRange());
1689 return QualType();
1690 }
1691 if (vectorSize == 0) {
1692 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1693 sizeExpr->getSourceRange());
1694 return QualType();
1695 }
1696 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1697 // the number of elements to be a power of two (unlike GCC).
1698 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00001699 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001700}
1701