blob: c2f03a373c5686f8c89aeb194ca242bb17f2372a [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +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
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000015#include "clang/AST/ASTContext.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000016#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000017#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000018#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000019#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000021#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000023#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner38047f92007-01-27 06:24:01 +000025#include "llvm/ADT/SmallSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000026using namespace clang;
27
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000028Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner32d920b2007-01-26 02:01:53 +000029 return dyn_cast_or_null<TypedefDecl>(II.getFETokenInfo<Decl>());
Chris Lattnere168f762006-11-10 05:29:30 +000030}
31
Chris Lattner302b4be2006-11-19 02:31:38 +000032void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000033 if (S->decl_empty()) return;
34 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
35
Chris Lattner302b4be2006-11-19 02:31:38 +000036 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
37 I != E; ++I) {
Chris Lattner99d31772007-01-21 22:37:37 +000038 Decl *D = static_cast<Decl*>(*I);
Chris Lattner302b4be2006-11-19 02:31:38 +000039 assert(D && "This decl didn't get pushed??");
Chris Lattnerff65b6b2007-01-23 01:33:16 +000040 IdentifierInfo *II = D->getIdentifier();
41 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000042
Chris Lattnerff65b6b2007-01-23 01:33:16 +000043 // Unlink this decl from the identifier. Because the scope contains decls
44 // in an unordered collection, and because we have multiple identifier
45 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
46 if (II->getFETokenInfo<Decl>() == D) {
47 // Normal case, no multiple decls in different namespaces.
48 II->setFETokenInfo(D->getNext());
49 } else {
50 // Scan ahead. There are only three namespaces in C, so this loop can
51 // never execute more than 3 times.
52 Decl *SomeDecl = II->getFETokenInfo<Decl>();
53 while (SomeDecl->getNext() != D) {
54 SomeDecl = SomeDecl->getNext();
55 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
56 }
57 SomeDecl->setNext(D->getNext());
58 }
Chris Lattner302b4be2006-11-19 02:31:38 +000059
Chris Lattner740b2f32006-11-21 01:32:20 +000060 // This will have to be revisited for C++: there we want to nest stuff in
61 // namespace decls etc. Even for C, we might want a top-level translation
62 // unit decl or something.
63 if (!CurFunctionDecl)
64 continue;
65
66 // Chain this decl to the containing function, it now owns the memory for
67 // the decl.
68 D->setNext(CurFunctionDecl->getDeclChain());
69 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000070 }
71}
72
Chris Lattner18b19622007-01-22 07:39:13 +000073/// LookupScopedDecl - Look up the inner-most declaration in the specified
74/// namespace.
Chris Lattner9561a0b2007-01-28 08:20:04 +000075Decl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
76 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +000077 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000078 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +000079
80 // Scan up the scope chain looking for a decl that matches this identifier
81 // that is in the appropriate namespace. This search should not take long, as
82 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
83 for (Decl *D = II->getFETokenInfo<Decl>(); D; D = D->getNext())
84 if (D->getIdentifierNamespace() == NS)
85 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +000086
Chris Lattner9561a0b2007-01-28 08:20:04 +000087 // If we didn't find a use of this identifier, and if the identifier
88 // corresponds to a compiler builtin, create the decl object for the builtin
89 // now, injecting it into translation unit scope, and return it.
90 if (NS == Decl::IDNS_Ordinary) {
91 // If this is a builtin on some other target, or if this builtin varies
92 // across targets (e.g. in type), emit a diagnostic and mark the translation
93 // unit non-portable for using it.
94 if (II->isNonPortableBuiltin()) {
95 // Only emit this diagnostic once for this builtin.
96 II->setNonPortableBuiltin(false);
97 Context.Target.DiagnoseNonPortability(IdLoc,
98 diag::port_target_builtin_use);
99 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000100 // If this is a builtin on this (or all) targets, create the decl.
101 if (unsigned BuiltinID = II->getBuiltinID())
102 return LazilyCreateBuiltin(II, BuiltinID, S);
103 }
Chris Lattner18b19622007-01-22 07:39:13 +0000104 return 0;
105}
106
Chris Lattner9561a0b2007-01-28 08:20:04 +0000107/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
108/// lazily create a decl for it.
109Decl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
110 Builtin::ID BID = (Builtin::ID)bid;
111
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000112 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000113 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000114 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000115
116 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000117 if (Scope *FnS = S->getFnParent())
118 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000119 while (S->getParent())
120 S = S->getParent();
121 S->AddDecl(New);
122
123 // Add this decl to the end of the identifier info.
124 if (Decl *LastDecl = II->getFETokenInfo<Decl>()) {
125 // Scan until we find the last (outermost) decl in the id chain.
126 while (LastDecl->getNext())
127 LastDecl = LastDecl->getNext();
128 // Insert before (outside) it.
129 LastDecl->setNext(New);
130 } else {
131 II->setFETokenInfo(New);
132 }
133 // Make sure clients iterating over decls see this.
134 LastInGroupList.push_back(New);
135
136 return New;
137}
138
Chris Lattner01564d92007-01-27 19:27:06 +0000139/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
140/// and scope as a previous declaration 'Old'. Figure out how to resolve this
141/// situation, merging decls or emitting diagnostics as appropriate.
142///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000143TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
144 // Verify the old decl was also a typedef.
145 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
146 if (!Old) {
147 Diag(New->getLocation(), diag::err_redefinition_different_kind,
148 New->getName());
149 Diag(OldD->getLocation(), diag::err_previous_definition);
150 return New;
151 }
152
Chris Lattner01564d92007-01-27 19:27:06 +0000153 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
154 // TODO: This is totally simplistic. It should handle merging functions
155 // together etc, merging extern int X; int X; ...
156 Diag(New->getLocation(), diag::err_redefinition, New->getName());
157 Diag(Old->getLocation(), diag::err_previous_definition);
158 return New;
159}
160
161/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
162/// and scope as a previous declaration 'Old'. Figure out how to resolve this
163/// situation, merging decls or emitting diagnostics as appropriate.
164///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000165FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
166 // Verify the old decl was also a function.
167 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
168 if (!Old) {
169 Diag(New->getLocation(), diag::err_redefinition_different_kind,
170 New->getName());
171 Diag(OldD->getLocation(), diag::err_previous_definition);
172 return New;
173 }
174
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000175 // This is not right, but it's a start. If 'Old' is a function prototype with
176 // the same type as 'New', silently allow this. FIXME: We should link up decl
177 // objects here.
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000178 if (Old->getBody() == 0 &&
179 Old->getCanonicalType() == New->getCanonicalType()) {
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000180 return New;
181 }
Chris Lattnerc511efb2007-01-27 19:32:14 +0000182
Chris Lattner01564d92007-01-27 19:27:06 +0000183 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
184 // TODO: This is totally simplistic. It should handle merging functions
185 // together etc, merging extern int X; int X; ...
186 Diag(New->getLocation(), diag::err_redefinition, New->getName());
187 Diag(Old->getLocation(), diag::err_previous_definition);
188 return New;
189}
190
191/// MergeVarDecl - We just parsed a variable 'New' which has the same name
192/// and scope as a previous declaration 'Old'. Figure out how to resolve this
193/// situation, merging decls or emitting diagnostics as appropriate.
194///
Steve Narofffc49d672007-04-01 21:27:45 +0000195/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
196/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
197///
Chris Lattnerc511efb2007-01-27 19:32:14 +0000198VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
199 // Verify the old decl was also a variable.
200 VarDecl *Old = dyn_cast<VarDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
Steve Naroff5c131802007-08-30 01:06:46 +0000207 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
208 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
209 bool OldIsTentative = false;
210
211 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
212 // Handle C "tentative" external object definitions. FIXME: finish!
213 if (!OldFSDecl->getInit() &&
214 (OldFSDecl->getStorageClass() == VarDecl::None ||
215 OldFSDecl->getStorageClass() == VarDecl::Static))
216 OldIsTentative = true;
217 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000218 // Verify the types match.
219 if (Old->getCanonicalType() != New->getCanonicalType()) {
220 Diag(New->getLocation(), diag::err_redefinition, New->getName());
221 Diag(Old->getLocation(), diag::err_previous_definition);
222 return New;
223 }
224 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000225 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000226 Diag(New->getLocation(), diag::err_redefinition, New->getName());
227 Diag(Old->getLocation(), diag::err_previous_definition);
228 }
Chris Lattner01564d92007-01-27 19:27:06 +0000229 return New;
230}
231
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000232/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
233/// no declarator (e.g. "struct foo;") is parsed.
234Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
235 // TODO: emit error on 'int;' or 'const enum foo;'.
236 // TODO: emit error on 'typedef int;'
237 // if (!DS.isMissingDeclaratorOk()) Diag(...);
238
239 return 0;
240}
241
Steve Naroff2fea1392007-09-02 02:04:30 +0000242bool Sema::CheckSingleInitializer(Expr *Init, QualType DeclType) {
243 AssignmentCheckResult result;
244 SourceLocation loc = Init->getLocStart();
245 // Get the type before calling CheckSingleAssignmentConstraints(), since
246 // it can promote the expression.
247 QualType rhsType = Init->getType();
248
249 result = CheckSingleAssignmentConstraints(DeclType, Init);
250
251 // decode the result (notice that extensions still return a type).
252 switch (result) {
253 case Compatible:
254 break;
255 case Incompatible:
Steve Narofff33527a2007-09-02 15:34:30 +0000256 // FIXME: tighten up this check which should allow:
257 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
258 if (rhsType == Context.getPointerType(Context.CharTy))
259 break;
Steve Naroff2fea1392007-09-02 02:04:30 +0000260 Diag(loc, diag::err_typecheck_assign_incompatible,
261 DeclType.getAsString(), rhsType.getAsString(),
262 Init->getSourceRange());
263 return true;
264 case PointerFromInt:
265 // check for null pointer constant (C99 6.3.2.3p3)
266 if (!Init->isNullPointerConstant(Context)) {
267 Diag(loc, diag::ext_typecheck_assign_pointer_int,
268 DeclType.getAsString(), rhsType.getAsString(),
269 Init->getSourceRange());
270 return true;
271 }
272 break;
273 case IntFromPointer:
274 Diag(loc, diag::ext_typecheck_assign_pointer_int,
275 DeclType.getAsString(), rhsType.getAsString(),
276 Init->getSourceRange());
277 break;
278 case IncompatiblePointer:
279 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
280 DeclType.getAsString(), rhsType.getAsString(),
281 Init->getSourceRange());
282 break;
283 case CompatiblePointerDiscardsQualifiers:
284 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
285 DeclType.getAsString(), rhsType.getAsString(),
286 Init->getSourceRange());
287 break;
288 }
289 return false;
290}
291
Steve Naroffb03f5942007-09-02 20:30:18 +0000292bool Sema::CheckInitList(InitListExpr *IList, QualType DType, bool isStatic) {
Steve Narofff33527a2007-09-02 15:34:30 +0000293 bool hadError = false;
294 for (unsigned i = 0; i < IList->getNumInits(); i++) {
295 Expr *expr = IList->getInit(i);
296
297 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr))
Steve Naroffb03f5942007-09-02 20:30:18 +0000298 CheckInitList(InitList, DType, isStatic);
Steve Narofff33527a2007-09-02 15:34:30 +0000299 else {
300 SourceLocation loc;
Steve Naroffb03f5942007-09-02 20:30:18 +0000301
302 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
Steve Narofff33527a2007-09-02 15:34:30 +0000303 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
304 hadError = true;
Steve Naroffb03f5942007-09-02 20:30:18 +0000305 } else if (CheckSingleInitializer(expr, DType)) {
306 hadError = true; // types didn't match.
Steve Narofff33527a2007-09-02 15:34:30 +0000307 }
308 }
309 }
310 return hadError;
311}
312
313QualType Sema::CheckInitializer(Expr *Init, QualType DeclType, bool isStatic) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000314 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
315 if (!InitList) {
316 return CheckSingleInitializer(Init, DeclType) ? QualType() : DeclType;
317 }
318 // We have an InitListExpr, make sure we set the type.
319 Init->setType(DeclType);
Steve Narofff33527a2007-09-02 15:34:30 +0000320
Steve Naroffb03f5942007-09-02 20:30:18 +0000321 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
322 // of unknown size ("[]") or an object type that is not a variable array type.
323 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
324 Expr *expr = VAT->getSizeExpr();
325 if (expr) {
326 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
327 expr->getSourceRange());
328 return QualType();
329 }
330 }
331 if (const ArrayType *Ary = DeclType->getAsArrayType()) {
332 // We have a ConstantArrayType or VariableArrayType with unknown size.
333 QualType ElmtType = Ary->getElementType();
334
335 // If we have a multi-dimensional array, navigate to the base type.
336 while ((Ary = ElmtType->getAsArrayType()))
337 ElmtType = Ary->getElementType();
338
339 CheckInitList(InitList, ElmtType, isStatic);
340 }
341 // FIXME: Handle struct/union types.
Steve Naroff2fea1392007-09-02 02:04:30 +0000342 return DeclType;
343}
344
Chris Lattner776fac82007-06-09 00:53:06 +0000345Sema::DeclTy *
Chris Lattner79c57592007-07-12 00:36:32 +0000346Sema::ParseDeclarator(Scope *S, Declarator &D, ExprTy *init,
Chris Lattner776fac82007-06-09 00:53:06 +0000347 DeclTy *lastDeclarator) {
348 Decl *LastDeclarator = (Decl*)lastDeclarator;
Chris Lattner79c57592007-07-12 00:36:32 +0000349 Expr *Init = static_cast<Expr*>(init);
Chris Lattnere168f762006-11-10 05:29:30 +0000350 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000351
Chris Lattner02c04392007-07-25 00:24:17 +0000352 // All of these full declarators require an identifier. If it doesn't have
353 // one, the ParsedFreeStandingDeclSpec action should be used.
354 if (II == 0) {
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000355 Diag(D.getDeclSpec().getSourceRange().Begin(),
356 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000357 D.getDeclSpec().getSourceRange(), D.getSourceRange());
358 return 0;
359 }
360
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000361 // The scope passed in may not be a decl scope. Zip up the scope tree until
362 // we find one that is.
363 while ((S->getFlags() & Scope::DeclScope) == 0)
364 S = S->getParent();
365
Chris Lattner01564d92007-01-27 19:27:06 +0000366 // See if this is a redefinition of a variable in the same scope.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000367 Decl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
368 D.getIdentifierLoc(), S);
Chris Lattner776fac82007-06-09 00:53:06 +0000369 if (PrevDecl && !S->isDeclScope(PrevDecl))
Chris Lattner01564d92007-01-27 19:27:06 +0000370 PrevDecl = 0; // If in outer scope, it isn't the same thing.
371
Chris Lattnere168f762006-11-10 05:29:30 +0000372 Decl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000373 bool InvalidDecl = false;
374
Chris Lattner01a7c532007-01-25 23:09:03 +0000375 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner79c57592007-07-12 00:36:32 +0000376 assert(Init == 0 && "Can't have initializer for a typedef!");
Chris Lattner776fac82007-06-09 00:53:06 +0000377 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000378 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000379
380 // Handle attributes prior to checking for duplicates in MergeVarDecl
381 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
382 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000383 // Merge the decl with the existing one if appropriate.
384 if (PrevDecl) {
385 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
386 if (NewTD == 0) return 0;
387 }
388 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000389 if (S->getParent() == 0) {
390 // C99 6.7.7p2: If a typedef name specifies a variably modified type
391 // then it shall have block scope.
Steve Naroff096dd942007-08-31 17:20:07 +0000392 if (const VariableArrayType *VAT =
393 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
394 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
395 VAT->getSizeExpr()->getSourceRange());
396 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000397 }
398 }
Chris Lattner01a7c532007-01-25 23:09:03 +0000399 } else if (D.isFunctionDeclarator()) {
Chris Lattner79c57592007-07-12 00:36:32 +0000400 assert(Init == 0 && "Can't have an initializer for a functiondecl!");
Steve Narofff93b6722007-08-28 20:14:24 +0000401
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000402 QualType R = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000403 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff7a5af782007-07-13 16:58:59 +0000404
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000405 FunctionDecl::StorageClass SC;
406 switch (D.getDeclSpec().getStorageClassSpec()) {
407 default: assert(0 && "Unknown storage class!");
408 case DeclSpec::SCS_auto:
409 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000410 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
411 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000412 InvalidDecl = true;
413 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000414 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
415 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
416 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
417 }
418
Chris Lattner776fac82007-06-09 00:53:06 +0000419 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000420 D.getDeclSpec().isInlineSpecified(),
Chris Lattner776fac82007-06-09 00:53:06 +0000421 LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000422
423 // Merge the decl with the existing one if appropriate.
424 if (PrevDecl) {
425 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
426 if (NewFD == 0) return 0;
427 }
428 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000429 } else {
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000430 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcf871f52007-08-28 18:45:29 +0000431 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner01564d92007-01-27 19:27:06 +0000432
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000433 VarDecl *NewVD;
434 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000435 switch (D.getDeclSpec().getStorageClassSpec()) {
436 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000437 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
438 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
439 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
440 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
441 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
442 }
Steve Narofffc49d672007-04-01 21:27:45 +0000443 if (S->getParent() == 0) {
Steve Narofff33527a2007-09-02 15:34:30 +0000444 if (Init) {
445 if (SC == VarDecl::Extern)
446 Diag(D.getIdentifierLoc(), diag::warn_extern_init);
447 CheckInitializer(Init, R, true);
448 }
Steve Narofffc49d672007-04-01 21:27:45 +0000449 // File scope. C99 6.9.2p2: A declaration of an identifier for and
450 // object that has file scope without an initializer, and without a
451 // storage-class specifier or with the storage-class specifier "static",
452 // constitutes a tentative definition. Note: A tentative definition with
453 // external linkage is valid (C99 6.2.2p5).
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000454 if (!Init && SC == VarDecl::Static) {
Steve Narofffc49d672007-04-01 21:27:45 +0000455 // C99 6.9.2p3: If the declaration of an identifier for an object is
456 // a tentative definition and has internal linkage (C99 6.2.2p3), the
457 // declared type shall not be an incomplete type.
458 if (R->isIncompleteType()) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000459 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
460 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000461 InvalidDecl = true;
Steve Narofffc49d672007-04-01 21:27:45 +0000462 }
Steve Naroffca8f7122007-04-01 01:41:35 +0000463 }
Bill Wendlingd6de6572007-06-02 09:40:07 +0000464 // C99 6.9p2: The storage-class specifiers auto and register shall not
465 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000466 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000467 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
468 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000469 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000470 }
Steve Naroff096dd942007-08-31 17:20:07 +0000471 if (SC == VarDecl::Static) {
472 // C99 6.7.5.2p2: If an identifier is declared to be an object with
473 // static storage duration, it shall not have a variable length array.
474 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
475 Expr *Size = VLA->getSizeExpr();
476 if (Size || (!Size && !Init)) {
477 // FIXME: Since we don't support initializers yet, we only emit this
478 // error when we don't have an initializer. Once initializers are
479 // implemented, the VLA will change to a CLA.
480 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
481 InvalidDecl = true;
482 }
483 }
Steve Naroff8eeeb132007-05-08 21:09:37 +0000484 }
Chris Lattner776fac82007-06-09 00:53:06 +0000485 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000486 } else {
487 if (Init) {
Steve Narofff33527a2007-09-02 15:34:30 +0000488 if (SC == VarDecl::Extern) { // C99 6.7.8p5
489 Diag(D.getIdentifierLoc(), diag::err_block_extern_cant_init);
490 InvalidDecl = true;
491 } else {
492 CheckInitializer(Init, R, SC == VarDecl::Static);
493 }
Steve Naroff2fea1392007-09-02 02:04:30 +0000494 }
Steve Narofffc49d672007-04-01 21:27:45 +0000495 // Block scope. C99 6.7p7: If an identifier for an object is declared with
496 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000497 if (SC != VarDecl::Extern) {
Steve Narofffc49d672007-04-01 21:27:45 +0000498 if (R->isIncompleteType()) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000499 Diag(D.getIdentifierLoc(), diag::err_typecheck_decl_incomplete_type,
500 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000501 InvalidDecl = true;
Steve Narofffc49d672007-04-01 21:27:45 +0000502 }
503 }
Steve Naroff8eeeb132007-05-08 21:09:37 +0000504 if (SC == VarDecl::Static) {
505 // C99 6.7.5.2p2: If an identifier is declared to be an object with
506 // static storage duration, it shall not have a variable length array.
Steve Naroff096dd942007-08-31 17:20:07 +0000507 if (const VariableArrayType *VLA = R->getAsVariableArrayType()) {
508 Expr *Size = VLA->getSizeExpr();
509 if (Size || (!Size && !Init)) {
510 // FIXME: Since we don't support initializers yet, we only emit this
511 // error when we don't have an initializer. Once initializers are
512 // implemented, the VLA will change to a CLA.
513 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffcf871f52007-08-28 18:45:29 +0000514 InvalidDecl = true;
Steve Naroff096dd942007-08-31 17:20:07 +0000515 }
Steve Naroff8eeeb132007-05-08 21:09:37 +0000516 }
517 }
Chris Lattner776fac82007-06-09 00:53:06 +0000518 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000519 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000520 // Handle attributes prior to checking for duplicates in MergeVarDecl
521 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
522 D.getAttributes());
523
Chris Lattner01564d92007-01-27 19:27:06 +0000524 // Merge the decl with the existing one if appropriate.
525 if (PrevDecl) {
526 NewVD = MergeVarDecl(NewVD, PrevDecl);
527 if (NewVD == 0) return 0;
528 }
Steve Naroff2fea1392007-09-02 02:04:30 +0000529 if (Init) { // FIXME: This will likely move up above...for now, it stays.
Steve Naroff0c1c7ed2007-08-24 22:33:52 +0000530 NewVD->setInit(Init);
531 }
Chris Lattner01564d92007-01-27 19:27:06 +0000532 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000533 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000534
Chris Lattnere168f762006-11-10 05:29:30 +0000535 // If this has an identifier, add it to the scope stack.
536 if (II) {
Chris Lattner18b19622007-01-22 07:39:13 +0000537 New->setNext(II->getFETokenInfo<Decl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000538 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000539 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000540 }
541
Steve Naroff26c8ea52007-03-21 21:08:52 +0000542 if (S->getParent() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000543 AddTopLevelDecl(New, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +0000544
545 // If any semantic error occurred, mark the decl as invalid.
546 if (D.getInvalidType() || InvalidDecl)
547 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000548
549 return New;
550}
551
Chris Lattner776fac82007-06-09 00:53:06 +0000552/// The declarators are chained together backwards, reverse the list.
553Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
554 // Often we have single declarators, handle them quickly.
555 Decl *Group = static_cast<Decl*>(group);
Chris Lattnerb2dd2412007-06-09 06:16:32 +0000556 if (Group == 0 || Group->getNextDeclarator() == 0) return Group;
Chris Lattner776fac82007-06-09 00:53:06 +0000557
558 Decl *NewGroup = 0;
559 while (Group) {
560 Decl *Next = Group->getNextDeclarator();
561 Group->setNextDeclarator(NewGroup);
562 NewGroup = Group;
563 Group = Next;
564 }
565 return NewGroup;
566}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000567
568// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000569ParmVarDecl *
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000570Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
571 Scope *FnScope) {
572 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
Chris Lattner200bdc32006-11-19 02:43:37 +0000573
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000574 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000575 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
576 // Can this happen for params? We already checked that they don't conflict
577 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000578 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000579 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000580
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000581 }
582
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000583 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000584 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000585
586 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
587 // Doing the promotion here has a win and a loss. The win is the type for
588 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
589 // code generator). The loss is the orginal type isn't preserved. For example:
590 //
591 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
592 // int blockvardecl[5];
593 // sizeof(parmvardecl); // size == 4
594 // sizeof(blockvardecl); // size == 20
595 // }
596 //
597 // For expressions, all implicit conversions are captured using the
598 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
599 //
600 // FIXME: If a source translation tool needs to see the original type, then
601 // we need to consider storing both types (in ParmVarDecl)...
602 //
603 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
604 if (const ArrayType *AT = parmDeclType->getAsArrayType())
605 parmDeclType = Context.getPointerType(AT->getElementType());
606 else if (parmDeclType->isFunctionType())
607 parmDeclType = Context.getPointerType(parmDeclType);
608
609 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcf871f52007-08-28 18:45:29 +0000610 VarDecl::None, 0);
611 if (PI.InvalidType)
612 New->setInvalidDecl();
613
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000614 // If this has an identifier, add it to the scope stack.
615 if (II) {
Chris Lattner18b19622007-01-22 07:39:13 +0000616 New->setNext(II->getFETokenInfo<Decl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000617 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000618 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000619 }
Chris Lattner229ce602006-11-21 01:21:07 +0000620
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000621 return New;
622}
623
624
625Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000626 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000627 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
628 "Not a function declarator!");
629 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
630
631 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
632 // for a K&R function.
633 if (!FTI.hasPrototype) {
634 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
635 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000636 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000637 FTI.ArgInfo[i].Ident->getName());
638 // Implicitly declare the argument as type 'int' for lack of a better
639 // type.
640 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
641 }
642 }
643
644 // Since this is a function definition, act as though we have information
645 // about the arguments.
646 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000647 } else {
648 // FIXME: Diagnose arguments without names in C.
649
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000650 }
651
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000652 Scope *GlobalScope = FnBodyScope->getParent();
653
654 FunctionDecl *FD =
655 static_cast<FunctionDecl*>(ParseDeclarator(GlobalScope, D, 0, 0));
Chris Lattner229ce602006-11-21 01:21:07 +0000656 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000657
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000658 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000659 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000660
661 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
662 // no arguments, not a function that takes a single void argument.
663 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
664 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
Chris Lattner99d31772007-01-21 22:37:37 +0000665 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000666 } else {
667 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
668 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
669 }
Chris Lattner2114d5e2006-12-04 07:40:24 +0000670
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000671 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +0000672
Chris Lattnere168f762006-11-10 05:29:30 +0000673 return FD;
674}
675
Chris Lattner229ce602006-11-21 01:21:07 +0000676Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
677 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
678 FD->setBody((Stmt*)Body);
679
680 assert(FD == CurFunctionDecl && "Function parsing confused");
681 CurFunctionDecl = 0;
Chris Lattnere2473062007-05-28 06:28:18 +0000682
683 // Verify and clean out per-function state.
684
685 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000686 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
687 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +0000688 // Verify that we have no forward references left. If so, there was a goto
689 // or address of a label taken, but no definition of it. Label fwd
690 // definitions are indicated with a null substmt.
691 if (I->second->getSubStmt() == 0) {
692 LabelStmt *L = I->second;
693 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +0000694 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +0000695
696 // At this point, we have gotos that use the bogus label. Stitch it into
697 // the function body so that they aren't leaked and that the AST is well
698 // formed.
699 L->setSubStmt(new NullStmt(L->getIdentLoc()));
700 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
701 }
702 }
703 LabelMap.clear();
704
Chris Lattner229ce602006-11-21 01:21:07 +0000705 return FD;
706}
707
708
Chris Lattnerac18be92006-11-20 06:49:47 +0000709/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
710/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
711Decl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
712 Scope *S) {
713 if (getLangOptions().C99) // Extension in C99.
714 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
715 else // Legal in C90, but warn about it.
716 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
717
718 // FIXME: handle stuff like:
719 // void foo() { extern float X(); }
720 // void bar() { X(); } <-- implicit decl for X in another scope.
721
722 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +0000723 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +0000724 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +0000725 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +0000726 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +0000727 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +0000728 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +0000729 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +0000730 D.SetIdentifier(&II, Loc);
731
Chris Lattner62d2e662007-01-28 00:21:37 +0000732 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000733 if (Scope *FnS = S->getFnParent())
734 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +0000735 while (S->getParent())
736 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +0000737
Chris Lattner62d2e662007-01-28 00:21:37 +0000738 return static_cast<Decl*>(ParseDeclarator(S, D, 0, 0));
Chris Lattnerac18be92006-11-20 06:49:47 +0000739}
740
Chris Lattner302b4be2006-11-19 02:31:38 +0000741
Chris Lattner776fac82007-06-09 00:53:06 +0000742TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
743 Decl *LastDeclarator) {
744 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Chris Lattner302b4be2006-11-19 02:31:38 +0000745
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000746 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000747 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +0000748
Chris Lattner18b19622007-01-22 07:39:13 +0000749 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +0000750 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
751 T, LastDeclarator);
752 if (D.getInvalidType())
753 NewTD->setInvalidDecl();
754 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +0000755}
756
Chris Lattner18b19622007-01-22 07:39:13 +0000757
Chris Lattner1300fb92007-01-23 23:42:53 +0000758/// ParseTag - This is invoked when we see 'struct foo' or 'struct {'. In the
759/// former case, Name will be non-null. In the later case, Name will be null.
760/// TagType indicates what kind of tag this is. TK indicates whether this is a
761/// reference/declaration/definition of a tag.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000762Sema::DeclTy *Sema::ParseTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000763 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +0000764 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000765 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000766 assert((Name != 0 || TK == TK_Definition) &&
767 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +0000768
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000769 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000770 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000771 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000772 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
773 case DeclSpec::TST_union: Kind = Decl::Union; break;
774//case DeclSpec::TST_class: Kind = Decl::Class; break;
775 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000776 }
Chris Lattner7e783a12007-01-23 02:05:42 +0000777
Chris Lattner18b19622007-01-22 07:39:13 +0000778 // If this is a named struct, check to see if there was a previous forward
779 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000780 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +0000781 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
782 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +0000783
784 // If this is a use of a previous tag, or if the tag is already declared in
785 // the same scope (so that the definition/declaration completes or
786 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000787 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +0000788 // Make sure that this wasn't declared as an enum and now used as a struct
789 // or something similar.
790 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000791 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +0000792 Diag(PrevDecl->getLocation(), diag::err_previous_use);
793 }
Chris Lattner7b9ace62007-01-23 20:11:08 +0000794
795 // If this is a use or a forward declaration, we're good.
796 if (TK != TK_Definition)
797 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000798
Chris Lattner7b9ace62007-01-23 20:11:08 +0000799 // Diagnose attempts to redefine a tag.
800 if (PrevDecl->isDefinition()) {
801 Diag(NameLoc, diag::err_redefinition, Name->getName());
802 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
803 // If this is a redefinition, recover by making this struct be
804 // anonymous, which will make any later references get the previous
805 // definition.
806 Name = 0;
807 } else {
808 // Okay, this is definition of a previously declared or referenced tag.
809 // Move the location of the decl to be the definition site.
810 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +0000811 return PrevDecl;
812 }
Chris Lattner8799cf22007-01-23 01:57:16 +0000813 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +0000814 // If we get here, this is a definition of a new struct type in a nested
815 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
816 // type.
Chris Lattner18b19622007-01-22 07:39:13 +0000817 }
818
Chris Lattnerbf0b7982007-01-23 04:27:41 +0000819 // If there is an identifier, use the location of the identifier as the
820 // location of the decl, otherwise use the location of the struct/union
821 // keyword.
822 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
823
Chris Lattner18b19622007-01-22 07:39:13 +0000824 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +0000825 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +0000826 switch (Kind) {
827 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +0000828 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +0000829 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
830 // enum X { A, B, C } D; D should chain to X.
831 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +0000832 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +0000833 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +0000834 break;
Chris Lattner720a0542007-01-25 00:44:24 +0000835 case Decl::Union:
836 case Decl::Struct:
837 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +0000838 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
839 // struct X { int A; } D; D should chain to X.
840 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +0000841 break;
842 }
Chris Lattner18b19622007-01-22 07:39:13 +0000843
844 // If this has an identifier, add it to the scope stack.
845 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000846 // The scope passed in may not be a decl scope. Zip up the scope tree until
847 // we find one that is.
848 while ((S->getFlags() & Scope::DeclScope) == 0)
849 S = S->getParent();
850
851 // Add it to the decl chain.
Chris Lattner18b19622007-01-22 07:39:13 +0000852 New->setNext(Name->getFETokenInfo<Decl>());
853 Name->setFETokenInfo(New);
854 S->AddDecl(New);
855 }
856
857 return New;
858}
Chris Lattner1300fb92007-01-23 23:42:53 +0000859
860/// ParseField - Each field of a struct/union/class is passed into this in order
861/// to create a FieldDecl object for it.
862Sema::DeclTy *Sema::ParseField(Scope *S, DeclTy *TagDecl,
863 SourceLocation DeclStart,
864 Declarator &D, ExprTy *BitfieldWidth) {
865 IdentifierInfo *II = D.getIdentifier();
866 Expr *BitWidth = (Expr*)BitfieldWidth;
867
868 SourceLocation Loc = DeclStart;
869 if (II) Loc = D.getIdentifierLoc();
870
Chris Lattner62d2e662007-01-28 00:21:37 +0000871 // FIXME: Unnamed fields can be handled in various different ways, for
872 // example, unnamed unions inject all members into the struct namespace!
873
874
Chris Lattner1300fb92007-01-23 23:42:53 +0000875 if (BitWidth) {
876 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +0000877 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +0000878
879 // 6.7.2.1p3
880 // 6.7.2.1p4
881
882 } else {
883 // Not a bitfield.
884
885 // validate II.
886
887 }
888
Steve Naroffe5aa9be2007-04-05 22:36:20 +0000889 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +0000890 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
891 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +0000892
Steve Naroff8eeeb132007-05-08 21:09:37 +0000893 // C99 6.7.2.1p8: A member of a structure or union may have any type other
894 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +0000895 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
896 Diag(Loc, diag::err_typecheck_illegal_vla,
897 VAT->getSizeExpr()->getSourceRange());
898 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000899 }
Chris Lattner776fac82007-06-09 00:53:06 +0000900 // FIXME: Chain fielddecls together.
Steve Narofff93b6722007-08-28 20:14:24 +0000901 FieldDecl *NewFD = new FieldDecl(Loc, II, T, 0);
902 if (D.getInvalidType() || InvalidDecl)
903 NewFD->setInvalidDecl();
904 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +0000905}
906
907void Sema::ParseRecordBody(SourceLocation RecLoc, DeclTy *RecDecl,
908 DeclTy **Fields, unsigned NumFields) {
Chris Lattnerc1915e22007-01-25 07:29:02 +0000909 RecordDecl *Record = cast<RecordDecl>(static_cast<Decl*>(RecDecl));
Chris Lattner1300fb92007-01-23 23:42:53 +0000910 if (Record->isDefinition()) {
911 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000912 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +0000913 // We discover this when we complete the outer S. Reject and ignore the
914 // outer S.
915 Diag(Record->getLocation(), diag::err_nested_redefinition,
916 Record->getKindName());
917 Diag(RecLoc, diag::err_previous_definition);
918 return;
919 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000920
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000921 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +0000922 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000923 llvm::SmallVector<FieldDecl*, 32> RecFields;
924 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Chris Lattnere5a66562007-01-25 22:48:42 +0000925
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000926 for (unsigned i = 0; i != NumFields; ++i) {
927 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
928 if (!FD) continue; // Already issued a diagnostic.
Chris Lattner720a0542007-01-25 00:44:24 +0000929
930 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000931 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +0000932
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000933 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000934 if (FDTy->isFunctionType()) {
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000935 Diag(FD->getLocation(), diag::err_field_declared_as_function,
936 FD->getName());
Chris Lattner82625602007-01-24 02:26:21 +0000937 delete FD;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000938 continue;
939 }
940
Chris Lattner82625602007-01-24 02:26:21 +0000941 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +0000942 if (FDTy->isIncompleteType()) {
Chris Lattner82625602007-01-24 02:26:21 +0000943 if (i != NumFields-1 || // ... that the last member ...
944 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +0000945 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +0000946 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
947 delete FD;
948 continue;
949 }
Chris Lattner720a0542007-01-25 00:44:24 +0000950 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +0000951 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
952 FD->getName());
953 delete FD;
954 continue;
955 }
Chris Lattner720a0542007-01-25 00:44:24 +0000956
957 // Okay, we have a legal flexible array member at the end of the struct.
Chris Lattner41943152007-01-25 04:52:46 +0000958 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +0000959 }
Chris Lattner720a0542007-01-25 00:44:24 +0000960
961
962 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
963 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +0000964 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +0000965 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
966 // If this is a member of a union, then entire union becomes "flexible".
967 if (Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +0000968 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +0000969 } else {
970 // If this is a struct/class and this is not the last element, reject
971 // it. Note that GCC supports variable sized arrays in the middle of
972 // structures.
973 if (i != NumFields-1) {
974 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
975 FD->getName());
976 delete FD;
977 continue;
978 }
979
980 // We support flexible arrays at the end of structs in other structs
981 // as an extension.
982 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
983 FD->getName());
Chris Lattner41943152007-01-25 04:52:46 +0000984 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +0000985 }
986 }
987 }
988
Chris Lattner82625602007-01-24 02:26:21 +0000989 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +0000990 if (IdentifierInfo *II = FD->getIdentifier()) {
991 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +0000992 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +0000993 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
994 // Find the previous decl.
995 SourceLocation PrevLoc;
996 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
997 assert(i != e && "Didn't find previous def!");
998 if (RecFields[i]->getIdentifier() == II) {
999 PrevLoc = RecFields[i]->getLocation();
1000 break;
1001 }
1002 }
1003 Diag(PrevLoc, diag::err_previous_definition);
1004 delete FD;
1005 continue;
1006 }
Chris Lattner82625602007-01-24 02:26:21 +00001007 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001008 }
Chris Lattner41943152007-01-25 04:52:46 +00001009
1010 // Remember good fields.
1011 RecFields.push_back(FD);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001012 }
Chris Lattner82625602007-01-24 02:26:21 +00001013
1014
1015 // Okay, we successfully defined 'Record'.
Chris Lattner41943152007-01-25 04:52:46 +00001016 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner1300fb92007-01-23 23:42:53 +00001017}
1018
Chris Lattner4ef40012007-06-11 01:28:17 +00001019Sema::DeclTy *Sema::ParseEnumConstant(Scope *S, DeclTy *theEnumDecl,
1020 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001021 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001022 SourceLocation EqualLoc, ExprTy *val) {
1023 theEnumDecl = theEnumDecl; // silence unused warning.
1024 EnumConstantDecl *LastEnumConst =
1025 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1026 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001027
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001028 // The scope passed in may not be a decl scope. Zip up the scope tree until
1029 // we find one that is.
1030 while ((S->getFlags() & Scope::DeclScope) == 0)
1031 S = S->getParent();
1032
Chris Lattner8116d1b2007-01-25 22:38:29 +00001033 // Verify that there isn't already something declared with this name in this
1034 // scope.
Chris Lattner9561a0b2007-01-28 08:20:04 +00001035 if (Decl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001036 if (S->isDeclScope(PrevDecl)) {
1037 if (isa<EnumConstantDecl>(PrevDecl))
1038 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1039 else
1040 Diag(IdLoc, diag::err_redefinition, Id->getName());
1041 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001042 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001043 return 0;
1044 }
1045 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001046
Chris Lattner23b7eb62007-06-15 23:05:46 +00001047 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001048 QualType EltTy;
1049 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001050 // Make sure to promote the operand type to int.
1051 UsualUnaryConversions(Val);
1052
Chris Lattner4ef40012007-06-11 01:28:17 +00001053 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1054 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001055 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001056 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1057 Id->getName());
1058 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001059 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001060 } else {
1061 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001062 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001063 }
1064
1065 if (!Val) {
1066 if (LastEnumConst) {
1067 // Assign the last value + 1.
1068 EnumVal = LastEnumConst->getInitVal();
1069 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001070
1071 // Check for overflow on increment.
1072 if (EnumVal < LastEnumConst->getInitVal())
1073 Diag(IdLoc, diag::warn_enum_value_overflow);
1074
Chris Lattnerf283a372007-08-27 17:37:24 +00001075 EltTy = LastEnumConst->getType();
1076 } else {
1077 // First value, set to zero.
1078 EltTy = Context.IntTy;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001079 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy, IdLoc));
Chris Lattnerf283a372007-08-27 17:37:24 +00001080 }
Steve Naroff63969212007-05-07 21:22:42 +00001081 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001082
Chris Lattner4ef40012007-06-11 01:28:17 +00001083 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1084 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001085
1086 // Register this decl in the current scope stack.
1087 New->setNext(Id->getFETokenInfo<Decl>());
1088 Id->setFETokenInfo(New);
1089 S->AddDecl(New);
1090 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001091}
1092
1093void Sema::ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
1094 DeclTy **Elements, unsigned NumElements) {
1095 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1096 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1097
Chris Lattner67933c02007-08-28 05:10:31 +00001098 // TODO: If the result value doesn't fit in an int, it must be a long or long
1099 // long value. ISO C does not support this, but GCC does as an extension,
1100 // emit a warning.
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001101 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner67933c02007-08-28 05:10:31 +00001102
1103
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001104 // Verify that all the values are okay, compute the size of the values, and
1105 // reverse the list.
1106 unsigned NumNegativeBits = 0;
1107 unsigned NumPositiveBits = 0;
1108
1109 // Keep track of whether all elements have type int.
1110 bool AllElementsInt = true;
1111
Chris Lattner4ef40012007-06-11 01:28:17 +00001112 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001113 for (unsigned i = 0; i != NumElements; ++i) {
1114 EnumConstantDecl *ECD =
1115 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1116 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001117
1118 // If the enum value doesn't fit in an int, emit an extension warning.
1119 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1120 "Should have promoted value to int");
1121 const llvm::APSInt &InitVal = ECD->getInitVal();
1122 if (InitVal.getBitWidth() > IntWidth) {
1123 llvm::APSInt V(InitVal);
1124 V.trunc(IntWidth);
1125 V.extend(InitVal.getBitWidth());
1126 if (V != InitVal)
1127 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1128 InitVal.toString());
1129 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001130
1131 // Keep track of the size of positive and negative values.
1132 if (InitVal.isUnsigned() || !InitVal.isNegative())
1133 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1134 else
1135 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001136
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001137 // Keep track of whether every enum element has type int (very commmon).
1138 if (AllElementsInt)
1139 AllElementsInt = ECD->getType() == Context.IntTy;
1140
Chris Lattner4ef40012007-06-11 01:28:17 +00001141 ECD->setNextDeclarator(EltList);
1142 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001143 }
1144
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001145 // Figure out the type that should be used for this enum.
1146 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1147 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001148 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001149
1150 if (NumNegativeBits) {
1151 // If there is a negative value, figure out the smallest integer type (of
1152 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001153 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001154 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001155 BestWidth = IntWidth;
1156 } else {
1157 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1158 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001159 BestType = Context.LongTy;
1160 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001161 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1162 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001163 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1164 BestType = Context.LongLongTy;
1165 }
1166 }
1167 } else {
1168 // If there is no negative value, figure out which of uint, ulong, ulonglong
1169 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001170 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001171 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001172 BestWidth = IntWidth;
1173 } else if (NumPositiveBits <=
1174 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001175 BestType = Context.UnsignedLongTy;
1176 else {
Chris Lattner3a370bf2007-08-29 17:31:48 +00001177 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1178 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001179 "How could an initializer get larger than ULL?");
1180 BestType = Context.UnsignedLongLongTy;
1181 }
1182 }
1183
Chris Lattner3a370bf2007-08-29 17:31:48 +00001184 // Loop over all of the enumerator constants, changing their types to match
1185 // the type of the enum if needed.
1186 for (unsigned i = 0; i != NumElements; ++i) {
1187 EnumConstantDecl *ECD =
1188 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1189 if (!ECD) continue; // Already issued a diagnostic.
1190
1191 // Standard C says the enumerators have int type, but we allow, as an
1192 // extension, the enumerators to be larger than int size. If each
1193 // enumerator value fits in an int, type it as an int, otherwise type it the
1194 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1195 // that X has type 'int', not 'unsigned'.
1196 if (ECD->getType() == Context.IntTy)
1197 continue; // Already int type.
1198
1199 // Determine whether the value fits into an int.
1200 llvm::APSInt InitVal = ECD->getInitVal();
1201 bool FitsInInt;
1202 if (InitVal.isUnsigned() || !InitVal.isNegative())
1203 FitsInInt = InitVal.getActiveBits() < IntWidth;
1204 else
1205 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1206
1207 // If it fits into an integer type, force it. Otherwise force it to match
1208 // the enum decl type.
1209 QualType NewTy;
1210 unsigned NewWidth;
1211 bool NewSign;
1212 if (FitsInInt) {
1213 NewTy = Context.IntTy;
1214 NewWidth = IntWidth;
1215 NewSign = true;
1216 } else if (ECD->getType() == BestType) {
1217 // Already the right type!
1218 continue;
1219 } else {
1220 NewTy = BestType;
1221 NewWidth = BestWidth;
1222 NewSign = BestType->isSignedIntegerType();
1223 }
1224
1225 // Adjust the APSInt value.
1226 InitVal.extOrTrunc(NewWidth);
1227 InitVal.setIsSigned(NewSign);
1228 ECD->setInitVal(InitVal);
1229
1230 // Adjust the Expr initializer and type.
1231 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1232 ECD->setType(NewTy);
1233 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001234
Chris Lattner1c1f9322007-08-28 18:24:31 +00001235 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001236}
Chris Lattner1300fb92007-01-23 23:42:53 +00001237
Steve Naroff26c8ea52007-03-21 21:08:52 +00001238void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1239 if (!current) return;
1240
1241 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1242 // remember this in the LastInGroupList list.
Chris Lattner776fac82007-06-09 00:53:06 +00001243 if (last)
Steve Naroff26c8ea52007-03-21 21:08:52 +00001244 LastInGroupList.push_back((Decl*)last);
Steve Naroff26c8ea52007-03-21 21:08:52 +00001245}
Steve Naroffa8fd9732007-06-11 00:35:03 +00001246
1247void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1248 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1249 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001250 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001251 if (!newType.isNull()) // install the new vector type into the decl
1252 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001253 }
1254 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001255 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1256 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001257 if (!newType.isNull()) // install the new vector type into the decl
1258 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001259 }
1260 }
Steve Naroff91fcddb2007-07-18 18:00:27 +00001261 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001262 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1263 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1264 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001265 Diag(rawAttr->getAttributeLoc(),
1266 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001267 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001268 // FIXME: add other attributes...
1269}
1270
1271void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1272 AttributeList *declarator_postfix) {
1273 while (declspec_prefix) {
1274 HandleDeclAttribute(New, declspec_prefix);
1275 declspec_prefix = declspec_prefix->getNext();
1276 }
1277 while (declarator_postfix) {
1278 HandleDeclAttribute(New, declarator_postfix);
1279 declarator_postfix = declarator_postfix->getNext();
1280 }
1281}
1282
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001283void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1284 AttributeList *rawAttr) {
1285 QualType curType = tDecl->getUnderlyingType();
Steve Naroff91fcddb2007-07-18 18:00:27 +00001286 // check the attribute arugments.
1287 if (rawAttr->getNumArgs() != 1) {
1288 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1289 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001290 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001291 }
1292 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1293 llvm::APSInt vecSize(32);
1294 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1295 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1296 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001297 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001298 }
1299 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1300 // in conjunction with complex types (pointers, arrays, functions, etc.).
1301 Type *canonType = curType.getCanonicalType().getTypePtr();
1302 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1303 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1304 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001305 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001306 }
1307 // unlike gcc's vector_size attribute, the size is specified as the
1308 // number of elements, not the number of bytes.
1309 unsigned vectorSize = vecSize.getZExtValue();
1310
1311 if (vectorSize == 0) {
1312 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1313 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001314 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001315 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001316 // Instantiate/Install the vector type, the number of elements is > 0.
1317 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1318 // Remember this typedef decl, we will need it later for diagnostics.
1319 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001320}
1321
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001322QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001323 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001324 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001325 if (rawAttr->getNumArgs() != 1) {
1326 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1327 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001328 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001329 }
1330 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001331 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001332 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001333 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1334 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001335 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001336 }
1337 // navigate to the base type - we need to provide for vector pointers,
1338 // vector arrays, and functions returning vectors.
1339 Type *canonType = curType.getCanonicalType().getTypePtr();
1340
Steve Naroff91fcddb2007-07-18 18:00:27 +00001341 if (canonType->isPointerType() || canonType->isArrayType() ||
1342 canonType->isFunctionType()) {
1343 assert(1 && "HandleVector(): Complex type construction unimplemented");
1344 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1345 do {
1346 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1347 canonType = PT->getPointeeType().getTypePtr();
1348 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1349 canonType = AT->getElementType().getTypePtr();
1350 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1351 canonType = FT->getResultType().getTypePtr();
1352 } while (canonType->isPointerType() || canonType->isArrayType() ||
1353 canonType->isFunctionType());
1354 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001355 }
1356 // the base type must be integer or float.
1357 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1358 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1359 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001360 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001361 }
Chris Lattner4481b422007-07-14 01:29:45 +00001362 unsigned typeSize = Context.getTypeSize(curType, rawAttr->getAttributeLoc());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001363 // vecSize is specified in bytes - convert to bits.
1364 unsigned vectorSize = vecSize.getZExtValue() * 8;
1365
1366 // the vector size needs to be an integral multiple of the type size.
1367 if (vectorSize % typeSize) {
1368 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1369 sizeExpr->getSourceRange());
1370 return QualType();
1371 }
1372 if (vectorSize == 0) {
1373 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1374 sizeExpr->getSourceRange());
1375 return QualType();
1376 }
1377 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1378 // the number of elements to be a power of two (unlike GCC).
1379 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001380 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001381}
1382