blob: e997a050aff8e7d0cc30625ecbcc02a75bbe5ee4 [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
Chris Lattner4b009652007-07-25 00:24:17 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff81f1bba2007-09-06 21:24:23 +000029 Decl *IIDecl = II.getFETokenInfo<Decl>();
30 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
31 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
33 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Chris Lattner4b009652007-07-25 00:24:17 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000042 Decl *TmpD = static_cast<Decl*>(*I);
43 assert(TmpD && "This decl didn't get pushed??");
44 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
45 assert(D && "This decl isn't a ScopedDecl?");
46
Chris Lattner4b009652007-07-25 00:24:17 +000047 IdentifierInfo *II = D->getIdentifier();
48 if (!II) continue;
49
50 // Unlink this decl from the identifier. Because the scope contains decls
51 // in an unordered collection, and because we have multiple identifier
52 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
53 if (II->getFETokenInfo<Decl>() == D) {
54 // Normal case, no multiple decls in different namespaces.
55 II->setFETokenInfo(D->getNext());
56 } else {
57 // Scan ahead. There are only three namespaces in C, so this loop can
58 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000059 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000060 while (SomeDecl->getNext() != D) {
61 SomeDecl = SomeDecl->getNext();
62 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
63 }
64 SomeDecl->setNext(D->getNext());
65 }
66
67 // This will have to be revisited for C++: there we want to nest stuff in
68 // namespace decls etc. Even for C, we might want a top-level translation
69 // unit decl or something.
70 if (!CurFunctionDecl)
71 continue;
72
73 // Chain this decl to the containing function, it now owns the memory for
74 // the decl.
75 D->setNext(CurFunctionDecl->getDeclChain());
76 CurFunctionDecl->setDeclChain(D);
77 }
78}
79
80/// LookupScopedDecl - Look up the inner-most declaration in the specified
81/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000082ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
83 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +000084 if (II == 0) return 0;
85 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
86
87 // Scan up the scope chain looking for a decl that matches this identifier
88 // that is in the appropriate namespace. This search should not take long, as
89 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000090 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +000091 if (D->getIdentifierNamespace() == NS)
92 return D;
93
94 // If we didn't find a use of this identifier, and if the identifier
95 // corresponds to a compiler builtin, create the decl object for the builtin
96 // now, injecting it into translation unit scope, and return it.
97 if (NS == Decl::IDNS_Ordinary) {
98 // If this is a builtin on some other target, or if this builtin varies
99 // across targets (e.g. in type), emit a diagnostic and mark the translation
100 // unit non-portable for using it.
101 if (II->isNonPortableBuiltin()) {
102 // Only emit this diagnostic once for this builtin.
103 II->setNonPortableBuiltin(false);
104 Context.Target.DiagnoseNonPortability(IdLoc,
105 diag::port_target_builtin_use);
106 }
107 // If this is a builtin on this (or all) targets, create the decl.
108 if (unsigned BuiltinID = II->getBuiltinID())
109 return LazilyCreateBuiltin(II, BuiltinID, S);
110 }
111 return 0;
112}
113
114/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
115/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000116ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000117 Builtin::ID BID = (Builtin::ID)bid;
118
119 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
120 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000121 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000122
123 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000124 if (Scope *FnS = S->getFnParent())
125 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000126 while (S->getParent())
127 S = S->getParent();
128 S->AddDecl(New);
129
130 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000131 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000132 // Scan until we find the last (outermost) decl in the id chain.
133 while (LastDecl->getNext())
134 LastDecl = LastDecl->getNext();
135 // Insert before (outside) it.
136 LastDecl->setNext(New);
137 } else {
138 II->setFETokenInfo(New);
139 }
140 // Make sure clients iterating over decls see this.
141 LastInGroupList.push_back(New);
142
143 return New;
144}
145
146/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
147/// and scope as a previous declaration 'Old'. Figure out how to resolve this
148/// situation, merging decls or emitting diagnostics as appropriate.
149///
150TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
151 // Verify the old decl was also a typedef.
152 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
153 if (!Old) {
154 Diag(New->getLocation(), diag::err_redefinition_different_kind,
155 New->getName());
156 Diag(OldD->getLocation(), diag::err_previous_definition);
157 return New;
158 }
159
160 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
161 // TODO: This is totally simplistic. It should handle merging functions
162 // together etc, merging extern int X; int X; ...
163 Diag(New->getLocation(), diag::err_redefinition, New->getName());
164 Diag(Old->getLocation(), diag::err_previous_definition);
165 return New;
166}
167
168/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
169/// and scope as a previous declaration 'Old'. Figure out how to resolve this
170/// situation, merging decls or emitting diagnostics as appropriate.
171///
172FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
173 // Verify the old decl was also a function.
174 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
175 if (!Old) {
176 Diag(New->getLocation(), diag::err_redefinition_different_kind,
177 New->getName());
178 Diag(OldD->getLocation(), diag::err_previous_definition);
179 return New;
180 }
181
182 // This is not right, but it's a start. If 'Old' is a function prototype with
183 // the same type as 'New', silently allow this. FIXME: We should link up decl
184 // objects here.
185 if (Old->getBody() == 0 &&
186 Old->getCanonicalType() == New->getCanonicalType()) {
187 return New;
188 }
189
190 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
191 // TODO: This is totally simplistic. It should handle merging functions
192 // together etc, merging extern int X; int X; ...
193 Diag(New->getLocation(), diag::err_redefinition, New->getName());
194 Diag(Old->getLocation(), diag::err_previous_definition);
195 return New;
196}
197
198/// MergeVarDecl - We just parsed a variable 'New' which has the same name
199/// and scope as a previous declaration 'Old'. Figure out how to resolve this
200/// situation, merging decls or emitting diagnostics as appropriate.
201///
202/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
203/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
204///
205VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
206 // Verify the old decl was also a variable.
207 VarDecl *Old = dyn_cast<VarDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
Steve Naroff83c13012007-08-30 01:06:46 +0000214 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
215 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
216 bool OldIsTentative = false;
217
218 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
219 // Handle C "tentative" external object definitions. FIXME: finish!
220 if (!OldFSDecl->getInit() &&
221 (OldFSDecl->getStorageClass() == VarDecl::None ||
222 OldFSDecl->getStorageClass() == VarDecl::Static))
223 OldIsTentative = true;
224 }
Chris Lattner4b009652007-07-25 00:24:17 +0000225 // Verify the types match.
226 if (Old->getCanonicalType() != New->getCanonicalType()) {
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230 }
231 // We've verified the types match, now check if Old is "extern".
232 if (Old->getStorageClass() != VarDecl::Extern) {
233 Diag(New->getLocation(), diag::err_redefinition, New->getName());
234 Diag(Old->getLocation(), diag::err_previous_definition);
235 }
236 return New;
237}
238
239/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
240/// no declarator (e.g. "struct foo;") is parsed.
241Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
242 // TODO: emit error on 'int;' or 'const enum foo;'.
243 // TODO: emit error on 'typedef int;'
244 // if (!DS.isMissingDeclaratorOk()) Diag(...);
245
246 return 0;
247}
248
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000249bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000250 AssignmentCheckResult result;
251 SourceLocation loc = Init->getLocStart();
252 // Get the type before calling CheckSingleAssignmentConstraints(), since
253 // it can promote the expression.
254 QualType rhsType = Init->getType();
255
256 result = CheckSingleAssignmentConstraints(DeclType, Init);
257
258 // decode the result (notice that extensions still return a type).
259 switch (result) {
260 case Compatible:
261 break;
262 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000263 // FIXME: tighten up this check which should allow:
264 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
265 if (rhsType == Context.getPointerType(Context.CharTy))
266 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000267 Diag(loc, diag::err_typecheck_assign_incompatible,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 case PointerFromInt:
272 // check for null pointer constant (C99 6.3.2.3p3)
273 if (!Init->isNullPointerConstant(Context)) {
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 return true;
278 }
279 break;
280 case IntFromPointer:
281 Diag(loc, diag::ext_typecheck_assign_pointer_int,
282 DeclType.getAsString(), rhsType.getAsString(),
283 Init->getSourceRange());
284 break;
285 case IncompatiblePointer:
286 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
287 DeclType.getAsString(), rhsType.getAsString(),
288 Init->getSourceRange());
289 break;
290 case CompatiblePointerDiscardsQualifiers:
291 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
292 DeclType.getAsString(), rhsType.getAsString(),
293 Init->getSourceRange());
294 break;
295 }
296 return false;
297}
298
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000299bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
300 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000301 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000302 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000303
304 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
305 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
306 return true;
307 } else if (CheckSingleInitializer(expr, ElementType)) {
308 return true; // types weren't compatible.
309 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000310 if (savExpr != expr) // The type was promoted, update initializer list.
311 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000312 return false;
313}
314
315void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
316 QualType ElementType, bool isStatic,
317 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000318 for (unsigned i = 0; i < IList->getNumInits(); i++) {
319 Expr *expr = IList->getInit(i);
320
Steve Naroff509d0b52007-09-04 02:20:04 +0000321 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
322 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000323 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000324 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
325 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000326 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000327 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000328 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000329 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000330 nInitializers++;
331 }
332 return;
333}
334
335// FIXME: Doesn't deal with arrays of structures yet.
336void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
337 QualType ElementType, bool isStatic,
338 int &totalInits, bool &hadError) {
339 int maxElementsAtThisLevel = 0;
340 int nInitsAtLevel = 0;
341
342 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
343 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000344 maxElementsAtThisLevel = CAT->getMaximumElements();
345 // Set DeclType, used below to recurse (for multi-dimensional arrays).
346 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000347 } else if (DeclType->isScalarType()) {
348 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
349 IList->getSourceRange());
350 maxElementsAtThisLevel = 1;
351 }
352 // The empty init list "{ }" is treated specially below.
353 unsigned numInits = IList->getNumInits();
354 if (numInits) {
355 for (unsigned i = 0; i < numInits; i++) {
356 Expr *expr = IList->getInit(i);
357
358 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
359 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
360 totalInits, hadError);
361 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000362 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000363 nInitsAtLevel++; // increment the number of initializers at this level.
364 totalInits--; // decrement the total number of initializers.
365
366 // Check if we have space for another initializer.
367 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
368 Diag(expr->getLocStart(), diag::warn_excess_initializers,
369 expr->getSourceRange());
370 }
371 }
372 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
373 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
374 } else {
375 // we have an initializer list with no elements.
376 totalInits -= maxElementsAtThisLevel;
377 if (totalInits < 0)
378 Diag(IList->getLocStart(), diag::warn_excess_initializers,
379 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000380 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000381 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000382}
383
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000384bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000385 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000386 if (!InitList)
387 return CheckSingleInitializer(Init, DeclType);
388
Steve Naroffe14e5542007-09-02 02:04:30 +0000389 // We have an InitListExpr, make sure we set the type.
390 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000391
392 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000393
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000394 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
395 // of unknown size ("[]") or an object type that is not a variable array type.
396 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
397 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000398 if (expr)
399 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
400 expr->getSourceRange());
401
Steve Naroff4f910992007-09-04 21:13:33 +0000402 // We have a VariableArrayType with unknown size. Note that only the first
403 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000404 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000405 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
406 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000407 if (!hadError) {
408 // Return a new array type from the number of initializers (C99 6.7.8p22).
409 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000410 ConstVal = numInits;
411 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000412 ArrayType::Normal, 0);
413 }
414 return hadError;
415 }
416 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000417 int maxElements = CAT->getMaximumElements();
418 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
419 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000420 return hadError;
421 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000422 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
423 int maxElements = 1;
424 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
425 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000426 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000427 }
428 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000429 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000430}
431
Chris Lattner4b009652007-07-25 00:24:17 +0000432Sema::DeclTy *
Steve Naroff6a0e2092007-09-12 14:07:44 +0000433Sema::ParseDeclarator(Scope *S, Declarator &D, DeclTy *lastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000434 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner4b009652007-07-25 00:24:17 +0000435 IdentifierInfo *II = D.getIdentifier();
436
437 // All of these full declarators require an identifier. If it doesn't have
438 // one, the ParsedFreeStandingDeclSpec action should be used.
439 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000440 Diag(D.getDeclSpec().getSourceRange().Begin(),
441 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000442 D.getDeclSpec().getSourceRange(), D.getSourceRange());
443 return 0;
444 }
445
Chris Lattnera7549902007-08-26 06:24:45 +0000446 // The scope passed in may not be a decl scope. Zip up the scope tree until
447 // we find one that is.
448 while ((S->getFlags() & Scope::DeclScope) == 0)
449 S = S->getParent();
450
Chris Lattner4b009652007-07-25 00:24:17 +0000451 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000452 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
453 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000454 if (PrevDecl && !S->isDeclScope(PrevDecl))
455 PrevDecl = 0; // If in outer scope, it isn't the same thing.
456
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000457 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000458 bool InvalidDecl = false;
459
Chris Lattner4b009652007-07-25 00:24:17 +0000460 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000461 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
462 if (!NewTD) return 0;
463
464 // Handle attributes prior to checking for duplicates in MergeVarDecl
465 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
466 D.getAttributes());
467 // Merge the decl with the existing one if appropriate.
468 if (PrevDecl) {
469 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
470 if (NewTD == 0) return 0;
471 }
472 New = NewTD;
473 if (S->getParent() == 0) {
474 // C99 6.7.7p2: If a typedef name specifies a variably modified type
475 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000476 if (const VariableArrayType *VAT =
477 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
478 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
479 VAT->getSizeExpr()->getSourceRange());
480 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000481 }
482 }
483 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000484 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000485 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000486
487 FunctionDecl::StorageClass SC;
488 switch (D.getDeclSpec().getStorageClassSpec()) {
489 default: assert(0 && "Unknown storage class!");
490 case DeclSpec::SCS_auto:
491 case DeclSpec::SCS_register:
492 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
493 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000494 InvalidDecl = true;
495 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000496 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
497 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
498 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
499 }
500
501 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000502 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000503 LastDeclarator);
504
505 // Merge the decl with the existing one if appropriate.
506 if (PrevDecl) {
507 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
508 if (NewFD == 0) return 0;
509 }
510 New = NewFD;
511 } else {
512 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000513 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000514
515 VarDecl *NewVD;
516 VarDecl::StorageClass SC;
517 switch (D.getDeclSpec().getStorageClassSpec()) {
518 default: assert(0 && "Unknown storage class!");
519 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
520 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
521 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
522 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
523 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
524 }
525 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000526 // C99 6.9p2: The storage-class specifiers auto and register shall not
527 // appear in the declaration specifiers in an external declaration.
528 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
529 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
530 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000531 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000532 }
Chris Lattner4b009652007-07-25 00:24:17 +0000533 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000534 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000535 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000536 }
Chris Lattner4b009652007-07-25 00:24:17 +0000537 // Handle attributes prior to checking for duplicates in MergeVarDecl
538 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
539 D.getAttributes());
540
541 // Merge the decl with the existing one if appropriate.
542 if (PrevDecl) {
543 NewVD = MergeVarDecl(NewVD, PrevDecl);
544 if (NewVD == 0) return 0;
545 }
Chris Lattner4b009652007-07-25 00:24:17 +0000546 New = NewVD;
547 }
548
549 // If this has an identifier, add it to the scope stack.
550 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000551 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000552 II->setFETokenInfo(New);
553 S->AddDecl(New);
554 }
555
556 if (S->getParent() == 0)
557 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000558
559 // If any semantic error occurred, mark the decl as invalid.
560 if (D.getInvalidType() || InvalidDecl)
561 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000562
563 return New;
564}
565
Steve Naroff6a0e2092007-09-12 14:07:44 +0000566void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000567 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000568 Expr *Init = static_cast<Expr *>(init);
569
Steve Naroff420d0f52007-09-12 20:13:48 +0000570 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000571
Steve Naroff420d0f52007-09-12 20:13:48 +0000572 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
573 if (!VDecl) {
574 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
575 RealDecl->setInvalidDecl();
576 return;
577 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000578 // Get the decls type and save a reference for later, since
579 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000580 QualType DclT = VDecl->getType(), SavT = DclT;
581 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000582 VarDecl::StorageClass SC = BVD->getStorageClass();
583 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000584 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000585 BVD->setInvalidDecl();
586 } else if (!BVD->isInvalidDecl()) {
587 CheckInitializer(Init, DclT, SC == VarDecl::Static);
588 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000589 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000590 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000591 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000592 if (!FVD->isInvalidDecl())
593 CheckInitializer(Init, DclT, true);
594 }
595 // If the type changed, it means we had an incomplete type that was
596 // completed by the initializer. For example:
597 // int ary[] = { 1, 3, 5 };
598 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000599 if (!VDecl->isInvalidDecl() && (DclT != SavT))
600 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000601
602 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000603 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000604 return;
605}
606
Chris Lattner4b009652007-07-25 00:24:17 +0000607/// The declarators are chained together backwards, reverse the list.
608Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
609 // Often we have single declarators, handle them quickly.
610 Decl *Group = static_cast<Decl*>(group);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000611 if (Group == 0)
612 return 0;
613
Chris Lattner4b009652007-07-25 00:24:17 +0000614 Decl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000615 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000616 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000617 else { // reverse the list.
618 while (Group) {
619 Decl *Next = Group->getNextDeclarator();
620 Group->setNextDeclarator(NewGroup);
621 NewGroup = Group;
622 Group = Next;
623 }
624 }
625 // Perform semantic analysis that depends on having fully processed both
626 // the declarator and initializer.
627 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
628 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
629 if (!IDecl)
630 continue;
631 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
632 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
633 QualType T = IDecl->getType();
634
635 // C99 6.7.5.2p2: If an identifier is declared to be an object with
636 // static storage duration, it shall not have a variable length array.
637 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
638 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
639 if (VLA->getSizeExpr()) {
640 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
641 IDecl->setInvalidDecl();
642 }
643 }
644 }
645 // Block scope. C99 6.7p7: If an identifier for an object is declared with
646 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
647 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
648 if (T->isIncompleteType()) {
649 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
650 T.getAsString());
651 IDecl->setInvalidDecl();
652 }
653 }
654 // File scope. C99 6.9.2p2: A declaration of an identifier for and
655 // object that has file scope without an initializer, and without a
656 // storage-class specifier or with the storage-class specifier "static",
657 // constitutes a tentative definition. Note: A tentative definition with
658 // external linkage is valid (C99 6.2.2p5).
659 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
660 // C99 6.9.2p3: If the declaration of an identifier for an object is
661 // a tentative definition and has internal linkage (C99 6.2.2p3), the
662 // declared type shall not be an incomplete type.
663 if (T->isIncompleteType()) {
664 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
665 T.getAsString());
666 IDecl->setInvalidDecl();
667 }
668 }
Chris Lattner4b009652007-07-25 00:24:17 +0000669 }
670 return NewGroup;
671}
Steve Naroff91b03f72007-08-28 03:03:08 +0000672
673// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000674ParmVarDecl *
675Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
676 Scope *FnScope) {
677 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
678
679 IdentifierInfo *II = PI.Ident;
680 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
681 // Can this happen for params? We already checked that they don't conflict
682 // among each other. Here they can only shadow globals, which is ok.
683 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
684 PI.IdentLoc, FnScope)) {
685
686 }
687
688 // FIXME: Handle storage class (auto, register). No declarator?
689 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000690
691 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
692 // Doing the promotion here has a win and a loss. The win is the type for
693 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
694 // code generator). The loss is the orginal type isn't preserved. For example:
695 //
696 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
697 // int blockvardecl[5];
698 // sizeof(parmvardecl); // size == 4
699 // sizeof(blockvardecl); // size == 20
700 // }
701 //
702 // For expressions, all implicit conversions are captured using the
703 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
704 //
705 // FIXME: If a source translation tool needs to see the original type, then
706 // we need to consider storing both types (in ParmVarDecl)...
707 //
708 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
709 if (const ArrayType *AT = parmDeclType->getAsArrayType())
710 parmDeclType = Context.getPointerType(AT->getElementType());
711 else if (parmDeclType->isFunctionType())
712 parmDeclType = Context.getPointerType(parmDeclType);
713
714 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000715 VarDecl::None, 0);
716 if (PI.InvalidType)
717 New->setInvalidDecl();
718
Chris Lattner4b009652007-07-25 00:24:17 +0000719 // If this has an identifier, add it to the scope stack.
720 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000721 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000722 II->setFETokenInfo(New);
723 FnScope->AddDecl(New);
724 }
725
726 return New;
727}
728
729
730Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
731 assert(CurFunctionDecl == 0 && "Function parsing confused");
732 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
733 "Not a function declarator!");
734 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
735
736 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
737 // for a K&R function.
738 if (!FTI.hasPrototype) {
739 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
740 if (FTI.ArgInfo[i].TypeInfo == 0) {
741 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
742 FTI.ArgInfo[i].Ident->getName());
743 // Implicitly declare the argument as type 'int' for lack of a better
744 // type.
745 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
746 }
747 }
748
749 // Since this is a function definition, act as though we have information
750 // about the arguments.
751 FTI.hasPrototype = true;
752 } else {
753 // FIXME: Diagnose arguments without names in C.
754
755 }
756
757 Scope *GlobalScope = FnBodyScope->getParent();
758
759 FunctionDecl *FD =
Steve Naroff6a0e2092007-09-12 14:07:44 +0000760 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000761 CurFunctionDecl = FD;
762
763 // Create Decl objects for each parameter, adding them to the FunctionDecl.
764 llvm::SmallVector<ParmVarDecl*, 16> Params;
765
766 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
767 // no arguments, not a function that takes a single void argument.
768 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
769 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
770 // empty arg list, don't push any params.
771 } else {
772 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
773 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
774 }
775
776 FD->setParams(&Params[0], Params.size());
777
778 return FD;
779}
780
781Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
782 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
783 FD->setBody((Stmt*)Body);
784
785 assert(FD == CurFunctionDecl && "Function parsing confused");
786 CurFunctionDecl = 0;
787
788 // Verify and clean out per-function state.
789
790 // Check goto/label use.
791 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
792 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
793 // Verify that we have no forward references left. If so, there was a goto
794 // or address of a label taken, but no definition of it. Label fwd
795 // definitions are indicated with a null substmt.
796 if (I->second->getSubStmt() == 0) {
797 LabelStmt *L = I->second;
798 // Emit error.
799 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
800
801 // At this point, we have gotos that use the bogus label. Stitch it into
802 // the function body so that they aren't leaked and that the AST is well
803 // formed.
804 L->setSubStmt(new NullStmt(L->getIdentLoc()));
805 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
806 }
807 }
808 LabelMap.clear();
809
810 return FD;
811}
812
813
814/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
815/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
816Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
817 Scope *S) {
818 if (getLangOptions().C99) // Extension in C99.
819 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
820 else // Legal in C90, but warn about it.
821 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
822
823 // FIXME: handle stuff like:
824 // void foo() { extern float X(); }
825 // void bar() { X(); } <-- implicit decl for X in another scope.
826
827 // Set a Declarator for the implicit definition: int foo();
828 const char *Dummy;
829 DeclSpec DS;
830 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
831 Error = Error; // Silence warning.
832 assert(!Error && "Error setting up implicit decl!");
833 Declarator D(DS, Declarator::BlockContext);
834 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
835 D.SetIdentifier(&II, Loc);
836
837 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000838 if (Scope *FnS = S->getFnParent())
839 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000840 while (S->getParent())
841 S = S->getParent();
842
Steve Naroff6a0e2092007-09-12 14:07:44 +0000843 return static_cast<Decl*>(ParseDeclarator(S, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000844}
845
846
847TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
848 Decl *LastDeclarator) {
849 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
850
851 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000852 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000853
854 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000855 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
856 T, LastDeclarator);
857 if (D.getInvalidType())
858 NewTD->setInvalidDecl();
859 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000860}
861
Steve Naroff81f1bba2007-09-06 21:24:23 +0000862Sema::DeclTy *Sema::ObjcStartClassInterface(SourceLocation AtInterfaceLoc,
863 IdentifierInfo *ClassName, SourceLocation ClassLoc,
864 IdentifierInfo *SuperName, SourceLocation SuperLoc,
865 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
866 AttributeList *AttrList) {
867 assert(ClassName && "Missing class identifier");
868 ObjcInterfaceDecl *IDecl;
869
870 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, ClassName);
871
872 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000873 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000874 ClassName->setFETokenInfo(IDecl);
875 return IDecl;
876}
877
Steve Naroff75494892007-09-11 21:17:26 +0000878void Sema::ObjcAddInstanceVariable(DeclTy *ClassDecl, DeclTy *Ivar,
879 tok::ObjCKeywordKind visibility) {
880 assert((ClassDecl && Ivar) && "missing class or instance variable");
881 ObjcInterfaceDecl *OInterface = dyn_cast<ObjcInterfaceDecl>(
882 static_cast<Decl *>(ClassDecl));
883 ObjcIvarDecl *OIvar = dyn_cast<ObjcIvarDecl>(static_cast<Decl *>(Ivar));
884
885 assert((OInterface && OIvar) && "mistyped class or instance variable");
886
887 switch (visibility) {
888 case tok::objc_private:
889 OIvar->setAccessControl(ObjcIvarDecl::Private);
890 break;
891 case tok::objc_public:
892 OIvar->setAccessControl(ObjcIvarDecl::Public);
893 break;
894 case tok::objc_protected:
895 OIvar->setAccessControl(ObjcIvarDecl::Protected);
896 break;
897 case tok::objc_package:
898 OIvar->setAccessControl(ObjcIvarDecl::Package);
899 break;
900 default:
901 OIvar->setAccessControl(ObjcIvarDecl::None);
902 break;
903 }
904 // FIXME: add to the class...
905}
906
Steve Naroff81f1bba2007-09-06 21:24:23 +0000907/// ObjcClassDeclaration -
908/// Scope will always be top level file scope.
909Action::DeclTy *
910Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
911 IdentifierInfo **IdentList, unsigned NumElts) {
912 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
913
914 for (unsigned i = 0; i != NumElts; ++i) {
915 ObjcInterfaceDecl *IDecl;
916
Steve Narofffaed3bf2007-09-10 20:51:04 +0000917 // FIXME: before we create one, look up the interface decl in a hash table.
Steve Naroff81f1bba2007-09-06 21:24:23 +0000918 IDecl = new ObjcInterfaceDecl(SourceLocation(), IdentList[i], true);
919 // Chain & install the interface decl into the identifier.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000920 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
Steve Naroff81f1bba2007-09-06 21:24:23 +0000921 IdentList[i]->setFETokenInfo(IDecl);
922
923 // Remember that this needs to be removed when the scope is popped.
924 S->AddDecl(IdentList[i]);
925
926 CDecl->setInterfaceDecl((int)i, IDecl);
927 }
928 return CDecl;
929}
930
Chris Lattner4b009652007-07-25 00:24:17 +0000931
932/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
933/// former case, Name will be non-null. In the later case, Name will be null.
934/// TagType indicates what kind of tag this is. TK indicates whether this is a
935/// reference/declaration/definition of a tag.
936Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
937 SourceLocation KWLoc, IdentifierInfo *Name,
938 SourceLocation NameLoc, AttributeList *Attr) {
939 // If this is a use of an existing tag, it must have a name.
940 assert((Name != 0 || TK == TK_Definition) &&
941 "Nameless record must be a definition!");
942
943 Decl::Kind Kind;
944 switch (TagType) {
945 default: assert(0 && "Unknown tag type!");
946 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
947 case DeclSpec::TST_union: Kind = Decl::Union; break;
948//case DeclSpec::TST_class: Kind = Decl::Class; break;
949 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
950 }
951
952 // If this is a named struct, check to see if there was a previous forward
953 // declaration or definition.
954 if (TagDecl *PrevDecl =
955 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
956 NameLoc, S))) {
957
958 // If this is a use of a previous tag, or if the tag is already declared in
959 // the same scope (so that the definition/declaration completes or
960 // rementions the tag), reuse the decl.
961 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
962 // Make sure that this wasn't declared as an enum and now used as a struct
963 // or something similar.
964 if (PrevDecl->getKind() != Kind) {
965 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
966 Diag(PrevDecl->getLocation(), diag::err_previous_use);
967 }
968
969 // If this is a use or a forward declaration, we're good.
970 if (TK != TK_Definition)
971 return PrevDecl;
972
973 // Diagnose attempts to redefine a tag.
974 if (PrevDecl->isDefinition()) {
975 Diag(NameLoc, diag::err_redefinition, Name->getName());
976 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
977 // If this is a redefinition, recover by making this struct be
978 // anonymous, which will make any later references get the previous
979 // definition.
980 Name = 0;
981 } else {
982 // Okay, this is definition of a previously declared or referenced tag.
983 // Move the location of the decl to be the definition site.
984 PrevDecl->setLocation(NameLoc);
985 return PrevDecl;
986 }
987 }
988 // If we get here, this is a definition of a new struct type in a nested
989 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
990 // type.
991 }
992
993 // If there is an identifier, use the location of the identifier as the
994 // location of the decl, otherwise use the location of the struct/union
995 // keyword.
996 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
997
998 // Otherwise, if this is the first time we've seen this tag, create the decl.
999 TagDecl *New;
1000 switch (Kind) {
1001 default: assert(0 && "Unknown tag kind!");
1002 case Decl::Enum:
1003 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1004 // enum X { A, B, C } D; D should chain to X.
1005 New = new EnumDecl(Loc, Name, 0);
1006 // If this is an undefined enum, warn.
1007 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1008 break;
1009 case Decl::Union:
1010 case Decl::Struct:
1011 case Decl::Class:
1012 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1013 // struct X { int A; } D; D should chain to X.
1014 New = new RecordDecl(Kind, Loc, Name, 0);
1015 break;
1016 }
1017
1018 // If this has an identifier, add it to the scope stack.
1019 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001020 // The scope passed in may not be a decl scope. Zip up the scope tree until
1021 // we find one that is.
1022 while ((S->getFlags() & Scope::DeclScope) == 0)
1023 S = S->getParent();
1024
1025 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001026 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001027 Name->setFETokenInfo(New);
1028 S->AddDecl(New);
1029 }
1030
1031 return New;
1032}
1033
1034/// ParseField - Each field of a struct/union/class is passed into this in order
1035/// to create a FieldDecl object for it.
1036Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
1037 SourceLocation DeclStart,
1038 Declarator &D, ExprTy *BitfieldWidth) {
1039 IdentifierInfo *II = D.getIdentifier();
1040 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001041 SourceLocation Loc = DeclStart;
1042 if (II) Loc = D.getIdentifierLoc();
1043
1044 // FIXME: Unnamed fields can be handled in various different ways, for
1045 // example, unnamed unions inject all members into the struct namespace!
1046
1047
1048 if (BitWidth) {
1049 // TODO: Validate.
1050 //printf("WARNING: BITFIELDS IGNORED!\n");
1051
1052 // 6.7.2.1p3
1053 // 6.7.2.1p4
1054
1055 } else {
1056 // Not a bitfield.
1057
1058 // validate II.
1059
1060 }
1061
1062 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001063 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1064 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001065
Chris Lattner4b009652007-07-25 00:24:17 +00001066 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1067 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001068 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1069 Diag(Loc, diag::err_typecheck_illegal_vla,
1070 VAT->getSizeExpr()->getSourceRange());
1071 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
Chris Lattner4b009652007-07-25 00:24:17 +00001073 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001074 FieldDecl *NewFD;
1075
1076 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
1077 NewFD = new FieldDecl(Loc, II, T, 0);
1078 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl)))
1079 NewFD = new ObjcIvarDecl(Loc, II, T, 0);
1080 else
1081 assert(0 && "Sema::ParseField(): Unknown TagDecl");
1082
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001083 if (D.getInvalidType() || InvalidDecl)
1084 NewFD->setInvalidDecl();
1085 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001086}
1087
1088void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
1089 DeclTy **Fields, unsigned NumFields) {
1090 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
1091 if (Record->isDefinition()) {
1092 // Diagnose code like:
1093 // struct S { struct S {} X; };
1094 // We discover this when we complete the outer S. Reject and ignore the
1095 // outer S.
1096 Diag(Record->getLocation(), diag::err_nested_redefinition,
1097 Record->getKindName());
1098 Diag(RecLoc, diag::err_previous_definition);
1099 return;
1100 }
1101
1102 // Verify that all the fields are okay.
1103 unsigned NumNamedMembers = 0;
1104 llvm::SmallVector<FieldDecl*, 32> RecFields;
1105 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
1106
1107 for (unsigned i = 0; i != NumFields; ++i) {
1108 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1109 if (!FD) continue; // Already issued a diagnostic.
1110
1111 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001112 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001113
1114 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001115 if (FDTy->isFunctionType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001116 Diag(FD->getLocation(), diag::err_field_declared_as_function,
1117 FD->getName());
1118 delete FD;
1119 continue;
1120 }
1121
1122 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1123 if (FDTy->isIncompleteType()) {
1124 if (i != NumFields-1 || // ... that the last member ...
1125 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001126 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001127 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
1128 delete FD;
1129 continue;
1130 }
1131 if (NumNamedMembers < 1) { //... must have more than named member ...
1132 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1133 FD->getName());
1134 delete FD;
1135 continue;
1136 }
1137
1138 // Okay, we have a legal flexible array member at the end of the struct.
1139 Record->setHasFlexibleArrayMember(true);
1140 }
1141
1142
1143 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1144 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001145 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001146 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1147 // If this is a member of a union, then entire union becomes "flexible".
1148 if (Record->getKind() == Decl::Union) {
1149 Record->setHasFlexibleArrayMember(true);
1150 } else {
1151 // If this is a struct/class and this is not the last element, reject
1152 // it. Note that GCC supports variable sized arrays in the middle of
1153 // structures.
1154 if (i != NumFields-1) {
1155 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1156 FD->getName());
1157 delete FD;
1158 continue;
1159 }
1160
1161 // We support flexible arrays at the end of structs in other structs
1162 // as an extension.
1163 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1164 FD->getName());
1165 Record->setHasFlexibleArrayMember(true);
1166 }
1167 }
1168 }
1169
1170 // Keep track of the number of named members.
1171 if (IdentifierInfo *II = FD->getIdentifier()) {
1172 // Detect duplicate member names.
1173 if (!FieldIDs.insert(II)) {
1174 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1175 // Find the previous decl.
1176 SourceLocation PrevLoc;
1177 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1178 assert(i != e && "Didn't find previous def!");
1179 if (RecFields[i]->getIdentifier() == II) {
1180 PrevLoc = RecFields[i]->getLocation();
1181 break;
1182 }
1183 }
1184 Diag(PrevLoc, diag::err_previous_definition);
1185 delete FD;
1186 continue;
1187 }
1188 ++NumNamedMembers;
1189 }
1190
1191 // Remember good fields.
1192 RecFields.push_back(FD);
1193 }
1194
1195
1196 // Okay, we successfully defined 'Record'.
1197 Record->defineBody(&RecFields[0], RecFields.size());
1198}
1199
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001200void Sema::ObjcAddMethodsToClass(DeclTy *ClassDecl,
1201 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001202 // FIXME: Fix this when we can handle methods declared in protocols.
1203 // See Parser::ParseObjCAtProtocolDeclaration
1204 if (!ClassDecl)
1205 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001206 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1207 static_cast<Decl*>(ClassDecl));
1208 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1209 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1210
1211 for (unsigned i = 0; i < allNum; i++ ) {
1212 ObjcMethodDecl *Method =
1213 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1214 if (!Method) continue; // Already issued a diagnostic.
1215 if (Method->isInstance())
1216 insMethods.push_back(Method);
1217 else
1218 clsMethods.push_back(Method);
1219 }
1220 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1221 &clsMethods[0], clsMethods.size());
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001222 return;
1223}
1224
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001225Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1226 tok::TokenKind MethodType, TypeTy *ReturnType,
1227 ObjcKeywordInfo *Keywords, unsigned NumKeywords,
1228 AttributeList *AttrList) {
1229 assert(NumKeywords && "Selector must be specified");
1230 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1231 IdentifierInfo *SelectorName = Keywords[0].SelectorName;
1232 llvm::SmallVector<ParmVarDecl*, 16> Params;
1233
1234 for (unsigned i = 0; i < NumKeywords; i++) {
1235 ObjcKeywordInfo *arg = &Keywords[i];
1236 // FIXME: arg->AttrList must be stored too!
1237 ParmVarDecl* Param = new ParmVarDecl(arg->ColonLoc, arg->ArgumentName,
1238 QualType::getFromOpaquePtr(arg->TypeInfo),
1239 VarDecl::None, 0);
1240 // FIXME: 'InvalidType' does not get set by caller yet.
1241 if (arg->InvalidType)
1242 Param->setInvalidDecl();
1243 Params.push_back(Param);
1244 }
1245 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1246 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc,
1247 SelectorName, resultDeclType,
1248 0, -1, AttrList, MethodType == tok::minus);
1249 ObjcMethod->setMethodParams(&Params[0], NumKeywords);
1250 return ObjcMethod;
1251}
1252
1253Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
1254 tok::TokenKind MethodType, TypeTy *ReturnType,
1255 IdentifierInfo *SelectorName, AttributeList *AttrList) {
1256 // FIXME: SelectorName to be changed to comform to objc's abi for method names
1257 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1258 return new ObjcMethodDecl(MethodLoc, SelectorName, resultDeclType, 0, -1,
1259 AttrList, MethodType == tok::minus);
1260}
1261
Chris Lattner4b009652007-07-25 00:24:17 +00001262Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1263 DeclTy *lastEnumConst,
1264 SourceLocation IdLoc, IdentifierInfo *Id,
1265 SourceLocation EqualLoc, ExprTy *val) {
1266 theEnumDecl = theEnumDecl; // silence unused warning.
1267 EnumConstantDecl *LastEnumConst =
1268 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1269 Expr *Val = static_cast<Expr*>(val);
1270
Chris Lattnera7549902007-08-26 06:24:45 +00001271 // The scope passed in may not be a decl scope. Zip up the scope tree until
1272 // we find one that is.
1273 while ((S->getFlags() & Scope::DeclScope) == 0)
1274 S = S->getParent();
1275
Chris Lattner4b009652007-07-25 00:24:17 +00001276 // Verify that there isn't already something declared with this name in this
1277 // scope.
1278 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
1279 if (S->isDeclScope(PrevDecl)) {
1280 if (isa<EnumConstantDecl>(PrevDecl))
1281 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1282 else
1283 Diag(IdLoc, diag::err_redefinition, Id->getName());
1284 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1285 // FIXME: Don't leak memory: delete Val;
1286 return 0;
1287 }
1288 }
1289
1290 llvm::APSInt EnumVal(32);
1291 QualType EltTy;
1292 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001293 // Make sure to promote the operand type to int.
1294 UsualUnaryConversions(Val);
1295
Chris Lattner4b009652007-07-25 00:24:17 +00001296 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1297 SourceLocation ExpLoc;
1298 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1299 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1300 Id->getName());
1301 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001302 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001303 } else {
1304 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001305 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001306 }
1307
1308 if (!Val) {
1309 if (LastEnumConst) {
1310 // Assign the last value + 1.
1311 EnumVal = LastEnumConst->getInitVal();
1312 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001313
1314 // Check for overflow on increment.
1315 if (EnumVal < LastEnumConst->getInitVal())
1316 Diag(IdLoc, diag::warn_enum_value_overflow);
1317
Chris Lattnere7f53a42007-08-27 17:37:24 +00001318 EltTy = LastEnumConst->getType();
1319 } else {
1320 // First value, set to zero.
1321 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001322 EnumVal.zextOrTrunc(
1323 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001324 }
Chris Lattner4b009652007-07-25 00:24:17 +00001325 }
1326
Chris Lattner4b009652007-07-25 00:24:17 +00001327 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1328 LastEnumConst);
1329
1330 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001331 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001332 Id->setFETokenInfo(New);
1333 S->AddDecl(New);
1334 return New;
1335}
1336
1337void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1338 DeclTy **Elements, unsigned NumElements) {
1339 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1340 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1341
Chris Lattner435c3fd2007-08-28 05:10:31 +00001342 // TODO: If the result value doesn't fit in an int, it must be a long or long
1343 // long value. ISO C does not support this, but GCC does as an extension,
1344 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001345 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001346
1347
Chris Lattner206754a2007-08-28 06:15:15 +00001348 // Verify that all the values are okay, compute the size of the values, and
1349 // reverse the list.
1350 unsigned NumNegativeBits = 0;
1351 unsigned NumPositiveBits = 0;
1352
1353 // Keep track of whether all elements have type int.
1354 bool AllElementsInt = true;
1355
Chris Lattner4b009652007-07-25 00:24:17 +00001356 EnumConstantDecl *EltList = 0;
1357 for (unsigned i = 0; i != NumElements; ++i) {
1358 EnumConstantDecl *ECD =
1359 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1360 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001361
1362 // If the enum value doesn't fit in an int, emit an extension warning.
1363 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1364 "Should have promoted value to int");
1365 const llvm::APSInt &InitVal = ECD->getInitVal();
1366 if (InitVal.getBitWidth() > IntWidth) {
1367 llvm::APSInt V(InitVal);
1368 V.trunc(IntWidth);
1369 V.extend(InitVal.getBitWidth());
1370 if (V != InitVal)
1371 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1372 InitVal.toString());
1373 }
Chris Lattner206754a2007-08-28 06:15:15 +00001374
1375 // Keep track of the size of positive and negative values.
1376 if (InitVal.isUnsigned() || !InitVal.isNegative())
1377 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1378 else
1379 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001380
Chris Lattner206754a2007-08-28 06:15:15 +00001381 // Keep track of whether every enum element has type int (very commmon).
1382 if (AllElementsInt)
1383 AllElementsInt = ECD->getType() == Context.IntTy;
1384
Chris Lattner4b009652007-07-25 00:24:17 +00001385 ECD->setNextDeclarator(EltList);
1386 EltList = ECD;
1387 }
1388
Chris Lattner206754a2007-08-28 06:15:15 +00001389 // Figure out the type that should be used for this enum.
1390 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1391 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001392 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001393
1394 if (NumNegativeBits) {
1395 // If there is a negative value, figure out the smallest integer type (of
1396 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001397 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001398 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001399 BestWidth = IntWidth;
1400 } else {
1401 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1402 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001403 BestType = Context.LongTy;
1404 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001405 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1406 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001407 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1408 BestType = Context.LongLongTy;
1409 }
1410 }
1411 } else {
1412 // If there is no negative value, figure out which of uint, ulong, ulonglong
1413 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001414 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001415 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001416 BestWidth = IntWidth;
1417 } else if (NumPositiveBits <=
1418 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001419 BestType = Context.UnsignedLongTy;
1420 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001421 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1422 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001423 "How could an initializer get larger than ULL?");
1424 BestType = Context.UnsignedLongLongTy;
1425 }
1426 }
1427
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001428 // Loop over all of the enumerator constants, changing their types to match
1429 // the type of the enum if needed.
1430 for (unsigned i = 0; i != NumElements; ++i) {
1431 EnumConstantDecl *ECD =
1432 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1433 if (!ECD) continue; // Already issued a diagnostic.
1434
1435 // Standard C says the enumerators have int type, but we allow, as an
1436 // extension, the enumerators to be larger than int size. If each
1437 // enumerator value fits in an int, type it as an int, otherwise type it the
1438 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1439 // that X has type 'int', not 'unsigned'.
1440 if (ECD->getType() == Context.IntTy)
1441 continue; // Already int type.
1442
1443 // Determine whether the value fits into an int.
1444 llvm::APSInt InitVal = ECD->getInitVal();
1445 bool FitsInInt;
1446 if (InitVal.isUnsigned() || !InitVal.isNegative())
1447 FitsInInt = InitVal.getActiveBits() < IntWidth;
1448 else
1449 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1450
1451 // If it fits into an integer type, force it. Otherwise force it to match
1452 // the enum decl type.
1453 QualType NewTy;
1454 unsigned NewWidth;
1455 bool NewSign;
1456 if (FitsInInt) {
1457 NewTy = Context.IntTy;
1458 NewWidth = IntWidth;
1459 NewSign = true;
1460 } else if (ECD->getType() == BestType) {
1461 // Already the right type!
1462 continue;
1463 } else {
1464 NewTy = BestType;
1465 NewWidth = BestWidth;
1466 NewSign = BestType->isSignedIntegerType();
1467 }
1468
1469 // Adjust the APSInt value.
1470 InitVal.extOrTrunc(NewWidth);
1471 InitVal.setIsSigned(NewSign);
1472 ECD->setInitVal(InitVal);
1473
1474 // Adjust the Expr initializer and type.
1475 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1476 ECD->setType(NewTy);
1477 }
Chris Lattner206754a2007-08-28 06:15:15 +00001478
Chris Lattner90a018d2007-08-28 18:24:31 +00001479 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00001480}
1481
1482void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1483 if (!current) return;
1484
1485 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1486 // remember this in the LastInGroupList list.
1487 if (last)
1488 LastInGroupList.push_back((Decl*)last);
1489}
1490
1491void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1492 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1493 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1494 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1495 if (!newType.isNull()) // install the new vector type into the decl
1496 vDecl->setType(newType);
1497 }
1498 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1499 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1500 rawAttr);
1501 if (!newType.isNull()) // install the new vector type into the decl
1502 tDecl->setUnderlyingType(newType);
1503 }
1504 }
1505 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00001506 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1507 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1508 else
Chris Lattner4b009652007-07-25 00:24:17 +00001509 Diag(rawAttr->getAttributeLoc(),
1510 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00001511 }
1512 // FIXME: add other attributes...
1513}
1514
1515void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1516 AttributeList *declarator_postfix) {
1517 while (declspec_prefix) {
1518 HandleDeclAttribute(New, declspec_prefix);
1519 declspec_prefix = declspec_prefix->getNext();
1520 }
1521 while (declarator_postfix) {
1522 HandleDeclAttribute(New, declarator_postfix);
1523 declarator_postfix = declarator_postfix->getNext();
1524 }
1525}
1526
Steve Naroff82113e32007-07-29 16:33:31 +00001527void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1528 AttributeList *rawAttr) {
1529 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00001530 // check the attribute arugments.
1531 if (rawAttr->getNumArgs() != 1) {
1532 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1533 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001534 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001535 }
1536 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1537 llvm::APSInt vecSize(32);
1538 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1539 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1540 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001541 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001542 }
1543 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1544 // in conjunction with complex types (pointers, arrays, functions, etc.).
1545 Type *canonType = curType.getCanonicalType().getTypePtr();
1546 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1547 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1548 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001549 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001550 }
1551 // unlike gcc's vector_size attribute, the size is specified as the
1552 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001553 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001554
1555 if (vectorSize == 0) {
1556 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1557 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001558 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001559 }
Steve Naroff82113e32007-07-29 16:33:31 +00001560 // Instantiate/Install the vector type, the number of elements is > 0.
1561 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1562 // Remember this typedef decl, we will need it later for diagnostics.
1563 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001564}
1565
1566QualType Sema::HandleVectorTypeAttribute(QualType curType,
1567 AttributeList *rawAttr) {
1568 // check the attribute arugments.
1569 if (rawAttr->getNumArgs() != 1) {
1570 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1571 std::string("1"));
1572 return QualType();
1573 }
1574 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1575 llvm::APSInt vecSize(32);
1576 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1577 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1578 sizeExpr->getSourceRange());
1579 return QualType();
1580 }
1581 // navigate to the base type - we need to provide for vector pointers,
1582 // vector arrays, and functions returning vectors.
1583 Type *canonType = curType.getCanonicalType().getTypePtr();
1584
1585 if (canonType->isPointerType() || canonType->isArrayType() ||
1586 canonType->isFunctionType()) {
1587 assert(1 && "HandleVector(): Complex type construction unimplemented");
1588 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1589 do {
1590 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1591 canonType = PT->getPointeeType().getTypePtr();
1592 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1593 canonType = AT->getElementType().getTypePtr();
1594 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1595 canonType = FT->getResultType().getTypePtr();
1596 } while (canonType->isPointerType() || canonType->isArrayType() ||
1597 canonType->isFunctionType());
1598 */
1599 }
1600 // the base type must be integer or float.
1601 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1602 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1603 curType.getCanonicalType().getAsString());
1604 return QualType();
1605 }
Chris Lattner3496d522007-09-04 02:45:27 +00001606 unsigned typeSize = static_cast<unsigned>(
1607 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001608 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001609 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001610
1611 // the vector size needs to be an integral multiple of the type size.
1612 if (vectorSize % typeSize) {
1613 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1614 sizeExpr->getSourceRange());
1615 return QualType();
1616 }
1617 if (vectorSize == 0) {
1618 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1619 sizeExpr->getSourceRange());
1620 return QualType();
1621 }
1622 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1623 // the number of elements to be a power of two (unlike GCC).
1624 // Instantiate the vector type, the number of elements is > 0.
1625 return Context.getVectorType(curType, vectorSize/typeSize);
1626}
1627