blob: 51d6547aa5c7a78aa7d62f38e1dcc213ee47addf [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
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"
Chris Lattnerac18be92006-11-20 06:49:47 +000022#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroffd54978b2007-09-18 23:55:05 +000024#include "llvm/ADT/SmallString.h"
Chris Lattner38047f92007-01-27 06:24:01 +000025#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian458f7112007-10-05 18:00:57 +000026#include "llvm/ADT/DenseSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000027using namespace clang;
28
Chris Lattner2ebe4bb2006-11-20 01:29:42 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 // Find first occurance of none-tagged declaration
32 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
33 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
34 if (!IIDecl)
35 return 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000036 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000037 return IIDecl;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000038 if (ObjCCompatibleAliasDecl *ADecl =
39 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000040 return ADecl->getClassInterface();
Steve Naroff09bf8152007-09-06 21:24:23 +000041 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000042}
43
Steve Naroffc62adb62007-10-09 22:01:59 +000044void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000045 if (S->decl_empty()) return;
46 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
47
Chris Lattner302b4be2006-11-19 02:31:38 +000048 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
49 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000050 Decl *TmpD = static_cast<Decl*>(*I);
51 assert(TmpD && "This decl didn't get pushed??");
52 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
53 assert(D && "This decl isn't a ScopedDecl?");
54
Chris Lattnerff65b6b2007-01-23 01:33:16 +000055 IdentifierInfo *II = D->getIdentifier();
56 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000057
Chris Lattnerff65b6b2007-01-23 01:33:16 +000058 // Unlink this decl from the identifier. Because the scope contains decls
59 // in an unordered collection, and because we have multiple identifier
60 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
61 if (II->getFETokenInfo<Decl>() == D) {
62 // Normal case, no multiple decls in different namespaces.
63 II->setFETokenInfo(D->getNext());
64 } else {
65 // Scan ahead. There are only three namespaces in C, so this loop can
66 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000067 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000068 while (SomeDecl->getNext() != D) {
69 SomeDecl = SomeDecl->getNext();
70 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
71 }
72 SomeDecl->setNext(D->getNext());
73 }
Chris Lattner302b4be2006-11-19 02:31:38 +000074
Chris Lattner740b2f32006-11-21 01:32:20 +000075 // This will have to be revisited for C++: there we want to nest stuff in
76 // namespace decls etc. Even for C, we might want a top-level translation
77 // unit decl or something.
78 if (!CurFunctionDecl)
79 continue;
80
81 // Chain this decl to the containing function, it now owns the memory for
82 // the decl.
83 D->setNext(CurFunctionDecl->getDeclChain());
84 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000085 }
86}
87
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000088/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
89/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian02fbb682007-10-12 19:53:08 +000090/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000091/// Bypassing the alias of a class by returning the aliased class.
92ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
93 ScopedDecl *IDecl;
94 // Scan up the scope chain looking for a decl that matches this identifier
95 // that is in the appropriate namespace.
96 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
97 IDecl = IDecl->getNext())
98 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
99 break;
100
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000101 if (ObjCCompatibleAliasDecl *ADecl =
102 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000103 return ADecl->getClassInterface();
104 return IDecl;
105}
106
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000107/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000108/// return 0 if one not found.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000109ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000110 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000111 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian343f7092007-09-29 00:54:24 +0000112}
113
Chris Lattner18b19622007-01-22 07:39:13 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroff9324db12007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Chris Lattner18b19622007-01-22 07:39:13 +0000118 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +0000120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000127
Chris Lattner9561a0b2007-01-28 08:20:04 +0000128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
Ted Kremenek1daa3cf2007-12-12 22:39:36 +0000138 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner9561a0b2007-01-28 08:20:04 +0000139 diag::port_target_builtin_use);
140 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
Chris Lattner18b19622007-01-22 07:39:13 +0000145 return 0;
146}
147
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000148void Sema::InitBuiltinVaListType()
149{
150 if (!Context.getBuiltinVaListType().isNull())
151 return;
152
153 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
154 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
155 SourceLocation(), TUScope);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000156 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000157 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
158}
159
Chris Lattner9561a0b2007-01-28 08:20:04 +0000160/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
161/// lazily create a decl for it.
Chris Lattner9c7a0362007-10-10 23:42:28 +0000162ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
163 Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000164 Builtin::ID BID = (Builtin::ID)bid;
165
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000166 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson24ebce62007-10-12 23:56:29 +0000167 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000168 BID == Builtin::BI__builtin_va_end)
169 InitBuiltinVaListType();
170
Anders Carlsson87c149b2007-10-11 01:00:40 +0000171 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner776fac82007-06-09 00:53:06 +0000172 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattnerb677a932007-08-26 04:02:13 +0000173 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000174
175 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000176 if (Scope *FnS = S->getFnParent())
177 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000178 while (S->getParent())
179 S = S->getParent();
180 S->AddDecl(New);
181
182 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000183 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000184 // Scan until we find the last (outermost) decl in the id chain.
185 while (LastDecl->getNext())
186 LastDecl = LastDecl->getNext();
187 // Insert before (outside) it.
188 LastDecl->setNext(New);
189 } else {
190 II->setFETokenInfo(New);
191 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000192 return New;
193}
194
Chris Lattner01564d92007-01-27 19:27:06 +0000195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
Steve Naroff9def2b12007-09-13 21:41:19 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
Steve Naroff6d40db02007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff6d40db02007-10-31 18:42:27 +0000212 return Old;
213
Chris Lattner01564d92007-01-27 19:27:06 +0000214 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
215 // TODO: This is totally simplistic. It should handle merging functions
216 // together etc, merging extern int X; int X; ...
217 Diag(New->getLocation(), diag::err_redefinition, New->getName());
218 Diag(Old->getLocation(), diag::err_previous_definition);
219 return New;
220}
221
222/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
223/// and scope as a previous declaration 'Old'. Figure out how to resolve this
224/// situation, merging decls or emitting diagnostics as appropriate.
225///
Steve Naroff9def2b12007-09-13 21:41:19 +0000226FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000227 // Verify the old decl was also a function.
228 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
229 if (!Old) {
230 Diag(New->getLocation(), diag::err_redefinition_different_kind,
231 New->getName());
232 Diag(OldD->getLocation(), diag::err_previous_definition);
233 return New;
234 }
235
Chris Lattner5c3f1542007-11-20 19:04:50 +0000236 QualType OldQType = Old->getCanonicalType();
237 QualType NewQType = New->getCanonicalType();
238
239 // This is not right, but it's a start.
240 // If Old is a function prototype with no defined arguments we only compare
241 // the return type; If arguments are defined on the prototype we validate the
242 // entire function type.
243 // FIXME: We should link up decl objects here.
244 if (Old->getBody() == 0) {
245 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
246 Old->getResultType() == New->getResultType())
247 return New;
Chris Lattnerefe4aea2007-01-27 19:35:39 +0000248 }
Steve Naroff012484d2008-01-14 20:51:29 +0000249 // Function types need to be compatible, not identical. This handles
250 // duplicate function decls like "void f(int); void f(enum X);" properly.
251 if (Context.functionTypesAreCompatible(OldQType, NewQType))
252 return New;
Chris Lattner45d561a2007-11-06 06:07:26 +0000253
Steve Naroff17832a42008-01-16 15:01:34 +0000254 // A function that has already been declared has been redeclared or defined
255 // with a different type- show appropriate diagnostic
256 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
257 diag::err_previous_declaration;
258
Chris Lattner01564d92007-01-27 19:27:06 +0000259 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
260 // TODO: This is totally simplistic. It should handle merging functions
261 // together etc, merging extern int X; int X; ...
Steve Naroff17832a42008-01-16 15:01:34 +0000262 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
263 Diag(Old->getLocation(), PrevDiag);
Chris Lattner01564d92007-01-27 19:27:06 +0000264 return New;
265}
266
Chris Lattner32097252007-11-06 04:28:31 +0000267
268/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
269/// the outermost VariableArrayType has no size defined.
270static bool hasUndefinedLength(const ArrayType *Array) {
271 const VariableArrayType *VAT = Array->getAsVariableArrayType();
272 return VAT && !VAT->getSizeExpr();
273}
274
275/// equivalentArrayTypes - Used to determine whether two array types are
276/// equivalent.
277/// We need to check this explicitly as an incomplete array definition is
278/// considered a VariableArrayType, so will not match a complete array
279/// definition that would be otherwise equivalent.
280static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
281 const ArrayType *NewAT = NewQType->getAsArrayType();
282 const ArrayType *OldAT = OldQType->getAsArrayType();
283
284 if (!NewAT || !OldAT)
285 return false;
286
287 // If either (or both) array types in incomplete we need to strip off the
288 // outer VariableArrayType. Once the outer VAT is removed the remaining
289 // types must be identical if the array types are to be considered
290 // equivalent.
291 // eg. int[][1] and int[1][1] become
292 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
293 // removing the outermost VAT gives
294 // CAT(1, int) and CAT(1, int)
295 // which are equal, therefore the array types are equivalent.
296 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
297 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
298 return false;
299 NewQType = NewAT->getElementType();
300 OldQType = OldAT->getElementType();
301 }
302
303 return NewQType == OldQType;
304}
305
Chris Lattner01564d92007-01-27 19:27:06 +0000306/// MergeVarDecl - We just parsed a variable 'New' which has the same name
307/// and scope as a previous declaration 'Old'. Figure out how to resolve this
308/// situation, merging decls or emitting diagnostics as appropriate.
309///
Steve Narofffc49d672007-04-01 21:27:45 +0000310/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
311/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
312///
Steve Naroff9def2b12007-09-13 21:41:19 +0000313VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000314 // Verify the old decl was also a variable.
315 VarDecl *Old = dyn_cast<VarDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
Steve Naroff5c131802007-08-30 01:06:46 +0000322 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
323 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
324 bool OldIsTentative = false;
325
326 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
327 // Handle C "tentative" external object definitions. FIXME: finish!
328 if (!OldFSDecl->getInit() &&
329 (OldFSDecl->getStorageClass() == VarDecl::None ||
330 OldFSDecl->getStorageClass() == VarDecl::Static))
331 OldIsTentative = true;
332 }
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000333 // Verify the types match.
Chris Lattner32097252007-11-06 04:28:31 +0000334 if (Old->getCanonicalType() != New->getCanonicalType() &&
335 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000336 Diag(New->getLocation(), diag::err_redefinition, New->getName());
337 Diag(Old->getLocation(), diag::err_previous_definition);
338 return New;
339 }
340 // We've verified the types match, now check if Old is "extern".
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000341 if (Old->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000342 Diag(New->getLocation(), diag::err_redefinition, New->getName());
343 Diag(Old->getLocation(), diag::err_previous_definition);
344 }
Chris Lattner01564d92007-01-27 19:27:06 +0000345 return New;
346}
347
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000348/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
349/// no declarator (e.g. "struct foo;") is parsed.
350Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
351 // TODO: emit error on 'int;' or 'const enum foo;'.
352 // TODO: emit error on 'typedef int;'
353 // if (!DS.isMissingDeclaratorOk()) Diag(...);
354
Steve Naroff14f5f792007-11-17 21:37:36 +0000355 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000356}
357
Steve Naroff98f72032008-01-10 22:15:12 +0000358bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000359 // Get the type before calling CheckSingleAssignmentConstraints(), since
360 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +0000361 QualType InitType = Init->getType();
Steve Naroff2fea1392007-09-02 02:04:30 +0000362
Chris Lattner9bad62c2008-01-04 18:04:52 +0000363 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
364 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
365 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +0000366}
367
Steve Naroff77b97002007-09-04 14:36:54 +0000368bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroff98f72032008-01-10 22:15:12 +0000369 QualType ElementType) {
Chris Lattnerf6412552007-12-11 23:15:04 +0000370 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff98f72032008-01-10 22:15:12 +0000371 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerf6412552007-12-11 23:15:04 +0000372 return true; // types weren't compatible.
373
Steve Naroff77b97002007-09-04 14:36:54 +0000374 if (savExpr != expr) // The type was promoted, update initializer list.
375 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000376 return false;
377}
378
379void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
Steve Naroff98f72032008-01-10 22:15:12 +0000380 QualType ElementType,
Steve Naroffac074b42007-09-04 02:20:04 +0000381 int &nInitializers, bool &hadError) {
Steve Naroff91f78082007-12-10 22:44:33 +0000382 unsigned numInits = IList->getNumInits();
383
384 if (numInits) {
385 if (CheckForCharArrayInitializer(IList, ElementType, nInitializers,
386 false, hadError))
387 return;
388
389 for (unsigned i = 0; i < numInits; i++) {
390 Expr *expr = IList->getInit(i);
Steve Narofff33527a2007-09-02 15:34:30 +0000391
Steve Naroff91f78082007-12-10 22:44:33 +0000392 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
393 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
394 int maxElements = CAT->getMaximumElements();
Steve Naroff98f72032008-01-10 22:15:12 +0000395 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroff91f78082007-12-10 22:44:33 +0000396 maxElements, hadError);
397 }
398 } else {
Steve Naroff98f72032008-01-10 22:15:12 +0000399 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroff91f78082007-12-10 22:44:33 +0000400 }
401 nInitializers++;
402 }
403 } else {
404 Diag(IList->getLocStart(),
405 diag::err_at_least_one_initializer_needed_to_size_array);
406 hadError = true;
407 }
408}
409
410bool Sema::CheckForCharArrayInitializer(InitListExpr *IList,
411 QualType ElementType,
412 int &nInitializers, bool isConstant,
413 bool &hadError)
414{
415 if (ElementType->isPointerType())
416 return false;
417
418 if (StringLiteral *literal = dyn_cast<StringLiteral>(IList->getInit(0))) {
419 // FIXME: Handle wide strings
420 if (ElementType->isCharType()) {
421 if (isConstant) {
422 if (literal->getByteLength() > (unsigned)nInitializers) {
423 Diag(literal->getSourceRange().getBegin(),
424 diag::warn_initializer_string_for_char_array_too_long,
425 literal->getSourceRange());
426 }
427 } else {
428 nInitializers = literal->getByteLength() + 1;
Steve Narofff33527a2007-09-02 15:34:30 +0000429 }
Steve Naroffac074b42007-09-04 02:20:04 +0000430 } else {
Steve Naroff91f78082007-12-10 22:44:33 +0000431 // FIXME: It might be better if we could point to the declaration
432 // here, instead of the string literal.
433 Diag(literal->getSourceRange().getBegin(),
434 diag::array_of_wrong_type_initialized_from_string,
435 ElementType.getAsString());
436 hadError = true;
Steve Narofff33527a2007-09-02 15:34:30 +0000437 }
Steve Naroff91f78082007-12-10 22:44:33 +0000438
439 // Check for excess initializers
440 for (unsigned i = 1; i < IList->getNumInits(); i++) {
441 Expr *expr = IList->getInit(i);
442 Diag(expr->getLocStart(),
443 diag::err_excess_initializers_in_char_array_initializer,
444 expr->getSourceRange());
445 }
446
447 return true;
Steve Naroffac074b42007-09-04 02:20:04 +0000448 }
Steve Naroff91f78082007-12-10 22:44:33 +0000449
450 return false;
Steve Naroffac074b42007-09-04 02:20:04 +0000451}
452
453// FIXME: Doesn't deal with arrays of structures yet.
454void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
Steve Naroff98f72032008-01-10 22:15:12 +0000455 QualType ElementType,
Steve Naroffac074b42007-09-04 02:20:04 +0000456 int &totalInits, bool &hadError) {
457 int maxElementsAtThisLevel = 0;
458 int nInitsAtLevel = 0;
459
Steve Naroff2c20c382007-12-07 21:12:53 +0000460 if (ElementType->isRecordType()) // FIXME: until we support structures...
461 return;
462
Steve Naroffac074b42007-09-04 02:20:04 +0000463 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
464 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff67ae4432007-09-04 21:13:33 +0000465 maxElementsAtThisLevel = CAT->getMaximumElements();
466 // Set DeclType, used below to recurse (for multi-dimensional arrays).
467 DeclType = CAT->getElementType();
Steve Naroffac074b42007-09-04 02:20:04 +0000468 } else if (DeclType->isScalarType()) {
Anders Carlsson5dd106b2007-12-03 01:01:28 +0000469 if (const VectorType *VT = DeclType->getAsVectorType())
470 maxElementsAtThisLevel = VT->getNumElements();
471 else {
472 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
473 IList->getSourceRange());
474 maxElementsAtThisLevel = 1;
475 }
Steve Naroffac074b42007-09-04 02:20:04 +0000476 }
477 // The empty init list "{ }" is treated specially below.
478 unsigned numInits = IList->getNumInits();
479 if (numInits) {
Steve Naroff91f78082007-12-10 22:44:33 +0000480 if (CheckForCharArrayInitializer(IList, ElementType,
481 maxElementsAtThisLevel,
482 true, hadError))
483 return;
484
Steve Naroffac074b42007-09-04 02:20:04 +0000485 for (unsigned i = 0; i < numInits; i++) {
486 Expr *expr = IList->getInit(i);
487
488 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
Steve Naroff98f72032008-01-10 22:15:12 +0000489 CheckConstantInitList(DeclType, InitList, ElementType,
Steve Naroffac074b42007-09-04 02:20:04 +0000490 totalInits, hadError);
491 } else {
Steve Naroff98f72032008-01-10 22:15:12 +0000492 hadError = CheckInitExpr(expr, IList, i, ElementType);
Steve Naroffac074b42007-09-04 02:20:04 +0000493 nInitsAtLevel++; // increment the number of initializers at this level.
494 totalInits--; // decrement the total number of initializers.
495
496 // Check if we have space for another initializer.
Anders Carlssoncbdb6f52007-12-05 04:57:06 +0000497 if (((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0)))
Steve Naroffac074b42007-09-04 02:20:04 +0000498 Diag(expr->getLocStart(), diag::warn_excess_initializers,
499 expr->getSourceRange());
500 }
501 }
502 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
503 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
504 } else {
505 // we have an initializer list with no elements.
506 totalInits -= maxElementsAtThisLevel;
507 if (totalInits < 0)
508 Diag(IList->getLocStart(), diag::warn_excess_initializers,
509 IList->getSourceRange());
Steve Narofff33527a2007-09-02 15:34:30 +0000510 }
Steve Narofff33527a2007-09-02 15:34:30 +0000511}
512
Steve Naroffaf2a0222008-01-22 00:55:40 +0000513bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
514 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
515 // C99 6.7.8p14. We have an array of character type with unknown size
516 // being initialized to a string literal.
517 llvm::APSInt ConstVal(32);
518 ConstVal = strLiteral->getByteLength() + 1;
519 // Return a new array type (C99 6.7.8p22).
520 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
521 ArrayType::Normal, 0);
522 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
523 // C99 6.7.8p14. We have an array of character type with known size.
524 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
525 Diag(strLiteral->getSourceRange().getBegin(),
526 diag::warn_initializer_string_for_char_array_too_long,
527 strLiteral->getSourceRange());
528 } else {
529 assert(0 && "HandleStringLiteralInit(): Invalid array type");
530 }
531 // Set type from "char *" to "constant array of char".
532 strLiteral->setType(DeclT);
533 // For now, we always return false (meaning success).
534 return false;
535}
536
537StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
538 StringLiteral *strLiteral = dyn_cast<StringLiteral>(Init);
539 const ArrayType *AT = DeclType->getAsArrayType();
540 if (strLiteral && (AT && AT->getElementType()->isCharType()))
541 return strLiteral;
542 return 0;
543}
544
Steve Naroff98f72032008-01-10 22:15:12 +0000545bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff91f78082007-12-10 22:44:33 +0000546 bool hadError = false;
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000547
Steve Narofff9eb5982008-01-21 23:53:58 +0000548 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
549 // of unknown size ("[]") or an object type that is not a variable array type.
550 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
551 return Diag(VAT->getSizeExpr()->getLocStart(),
552 diag::err_variable_object_no_init,
553 VAT->getSizeExpr()->getSourceRange());
554
Steve Naroff91f78082007-12-10 22:44:33 +0000555 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
556 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000557 // FIXME: Handle wide strings
558 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
559 return CheckStringLiteralInit(strLiteral, DeclType);
Steve Naroff98f72032008-01-10 22:15:12 +0000560 return CheckSingleInitializer(Init, DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000561 }
Steve Naroff2fea1392007-09-02 02:04:30 +0000562 // We have an InitListExpr, make sure we set the type.
563 Init->setType(DeclType);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000564
Steve Naroffb03f5942007-09-02 20:30:18 +0000565 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
566 // of unknown size ("[]") or an object type that is not a variable array type.
Steve Narofff9eb5982008-01-21 23:53:58 +0000567 if (const VariableArrayType *VAT = DeclType->getAsIncompleteArrayType()) {
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000568
Steve Naroff67ae4432007-09-04 21:13:33 +0000569 // We have a VariableArrayType with unknown size. Note that only the first
570 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroffac074b42007-09-04 02:20:04 +0000571 int numInits = 0;
Steve Naroff67ae4432007-09-04 21:13:33 +0000572 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
Steve Naroff98f72032008-01-10 22:15:12 +0000573 numInits, hadError);
Steve Naroff91f78082007-12-10 22:44:33 +0000574 llvm::APSInt ConstVal(32);
575
576 if (!hadError)
Steve Naroffac074b42007-09-04 02:20:04 +0000577 ConstVal = numInits;
Steve Naroff91f78082007-12-10 22:44:33 +0000578
579 // Return a new array type from the number of initializers (C99 6.7.8p22).
580
581 // Note that if there was an error, we will still set the decl type,
582 // to an array type with 0 elements.
583 // This is to avoid "incomplete type foo[]" errors when we've already
584 // reported the real cause of the error.
585 DeclType = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
586 ArrayType::Normal, 0);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000587 return hadError;
588 }
589 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff67ae4432007-09-04 21:13:33 +0000590 int maxElements = CAT->getMaximumElements();
591 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
Steve Naroff98f72032008-01-10 22:15:12 +0000592 maxElements, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000593 return hadError;
594 }
Anders Carlsson5dd106b2007-12-03 01:01:28 +0000595 if (const VectorType *VT = DeclType->getAsVectorType()) {
596 int maxElements = VT->getNumElements();
597 CheckConstantInitList(DeclType, InitList, VT->getElementType(),
Steve Naroff98f72032008-01-10 22:15:12 +0000598 maxElements, hadError);
Anders Carlsson5dd106b2007-12-03 01:01:28 +0000599 return hadError;
600 }
Steve Naroffac074b42007-09-04 02:20:04 +0000601 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
602 int maxElements = 1;
Steve Naroff98f72032008-01-10 22:15:12 +0000603 CheckConstantInitList(DeclType, InitList, DeclType, maxElements, hadError);
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000604 return hadError;
Steve Naroffb03f5942007-09-02 20:30:18 +0000605 }
Steve Naroff2644aaf2007-12-05 04:00:10 +0000606 // FIXME: Handle struct/union types, including those appearing in a
607 // CompoundLiteralExpr...
Steve Naroff7d2c5ed2007-09-03 01:24:23 +0000608 return hadError;
Steve Naroff2fea1392007-09-02 02:04:30 +0000609}
610
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000611Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000612Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000613 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000614 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000615
Chris Lattner02c04392007-07-25 00:24:17 +0000616 // All of these full declarators require an identifier. If it doesn't have
617 // one, the ParsedFreeStandingDeclSpec action should be used.
618 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000619 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000620 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000621 D.getDeclSpec().getSourceRange(), D.getSourceRange());
622 return 0;
623 }
624
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000625 // The scope passed in may not be a decl scope. Zip up the scope tree until
626 // we find one that is.
627 while ((S->getFlags() & Scope::DeclScope) == 0)
628 S = S->getParent();
629
Chris Lattner01564d92007-01-27 19:27:06 +0000630 // See if this is a redefinition of a variable in the same scope.
Steve Naroff9324db12007-09-13 18:10:37 +0000631 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
632 D.getIdentifierLoc(), S);
Steve Naroff9324db12007-09-13 18:10:37 +0000633 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000634 bool InvalidDecl = false;
635
Chris Lattner07b201d2007-11-14 06:34:38 +0000636 QualType R = GetTypeForDeclarator(D, S);
637 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
638
Chris Lattner01a7c532007-01-25 23:09:03 +0000639 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner07b201d2007-11-14 06:34:38 +0000640 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000641 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000642
643 // Handle attributes prior to checking for duplicates in MergeVarDecl
644 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
645 D.getAttributes());
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000646 // Merge the decl with the existing one if appropriate. If the decl is
647 // in an outer scope, it isn't the same thing.
648 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000649 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
650 if (NewTD == 0) return 0;
651 }
652 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000653 if (S->getParent() == 0) {
654 // C99 6.7.7p2: If a typedef name specifies a variably modified type
655 // then it shall have block scope.
Steve Naroff096dd942007-08-31 17:20:07 +0000656 if (const VariableArrayType *VAT =
657 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
658 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
659 VAT->getSizeExpr()->getSourceRange());
660 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000661 }
662 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000663 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000664 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000665 switch (D.getDeclSpec().getStorageClassSpec()) {
666 default: assert(0 && "Unknown storage class!");
667 case DeclSpec::SCS_auto:
668 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000669 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
670 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000671 InvalidDecl = true;
672 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000673 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
674 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
675 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
676 }
677
Chris Lattner776fac82007-06-09 00:53:06 +0000678 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattnerb677a932007-08-26 04:02:13 +0000679 D.getDeclSpec().isInlineSpecified(),
Nate Begemana0f78972007-11-13 22:14:47 +0000680 LastDeclarator,
681 D.getDeclSpec().getAttributes());
682
683 // Transfer ownership of DeclSpec attributes to FunctionDecl
684 D.getDeclSpec().clearAttributes();
Chris Lattner01564d92007-01-27 19:27:06 +0000685
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000686 // Merge the decl with the existing one if appropriate. Since C functions
687 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner01564d92007-01-27 19:27:06 +0000688 if (PrevDecl) {
689 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
690 if (NewFD == 0) return 0;
691 }
692 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000693 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000694 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000695 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
696 D.getIdentifier()->getName());
697 InvalidDecl = true;
698 }
Chris Lattner01564d92007-01-27 19:27:06 +0000699
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000700 VarDecl *NewVD;
701 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000702 switch (D.getDeclSpec().getStorageClassSpec()) {
703 default: assert(0 && "Unknown storage class!");
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000704 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
705 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
706 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
707 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
708 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
709 }
Steve Narofffc49d672007-04-01 21:27:45 +0000710 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000711 // C99 6.9p2: The storage-class specifiers auto and register shall not
712 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000713 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000714 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
715 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000716 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000717 }
Chris Lattner776fac82007-06-09 00:53:06 +0000718 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000719 } else {
Chris Lattner776fac82007-06-09 00:53:06 +0000720 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000721 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000722 // Handle attributes prior to checking for duplicates in MergeVarDecl
723 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
724 D.getAttributes());
725
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000726 // Merge the decl with the existing one if appropriate. If the decl is
727 // in an outer scope, it isn't the same thing.
728 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000729 NewVD = MergeVarDecl(NewVD, PrevDecl);
730 if (NewVD == 0) return 0;
731 }
732 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000733 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000734
Chris Lattnere168f762006-11-10 05:29:30 +0000735 // If this has an identifier, add it to the scope stack.
736 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000737 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000738 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000739 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000740 }
Steve Narofff93b6722007-08-28 20:14:24 +0000741 // If any semantic error occurred, mark the decl as invalid.
742 if (D.getInvalidType() || InvalidDecl)
743 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000744
745 return New;
746}
747
Steve Naroff98f72032008-01-10 22:15:12 +0000748bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
749 SourceLocation loc;
750 // FIXME: Remove the isReference check and handle assignment to a reference.
751 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
752 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
753 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
754 return true;
755 }
756 return false;
757}
758
Steve Naroff61091402007-09-12 14:07:44 +0000759void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000760 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000761 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +0000762 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000763
Chris Lattner8beb9de2007-10-19 20:10:30 +0000764 // If there is no declaration, there was an error parsing it. Just ignore
765 // the initializer.
766 if (RealDecl == 0) {
767 delete Init;
768 return;
769 }
Steve Naroff61091402007-09-12 14:07:44 +0000770
Steve Naroff437b4d82007-09-12 20:13:48 +0000771 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
772 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000773 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
774 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000775 RealDecl->setInvalidDecl();
776 return;
777 }
Steve Naroff61091402007-09-12 14:07:44 +0000778 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +0000779 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000780 QualType DclT = VDecl->getType(), SavT = DclT;
781 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000782 VarDecl::StorageClass SC = BVD->getStorageClass();
783 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000784 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000785 BVD->setInvalidDecl();
786 } else if (!BVD->isInvalidDecl()) {
Steve Naroff98f72032008-01-10 22:15:12 +0000787 CheckInitializerTypes(Init, DclT);
788 if (SC == VarDecl::Static) // C99 6.7.8p4.
789 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000790 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000791 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000792 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000793 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000794 if (!FVD->isInvalidDecl())
Steve Naroff98f72032008-01-10 22:15:12 +0000795 CheckInitializerTypes(Init, DclT);
796
797 // C99 6.7.8p4. All file scoped initializers need to be constant.
798 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000799 }
800 // If the type changed, it means we had an incomplete type that was
801 // completed by the initializer. For example:
802 // int ary[] = { 1, 3, 5 };
803 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000804 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000805 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000806 Init->setType(DclT);
807 }
Steve Naroff61091402007-09-12 14:07:44 +0000808
809 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000810 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000811 return;
812}
813
Chris Lattner776fac82007-06-09 00:53:06 +0000814/// The declarators are chained together backwards, reverse the list.
815Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
816 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000817 Decl *GroupDecl = static_cast<Decl*>(group);
818 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000819 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000820
821 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
822 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000823 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000824 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000825 else { // reverse the list.
826 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000827 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000828 Group->setNextDeclarator(NewGroup);
829 NewGroup = Group;
830 Group = Next;
831 }
832 }
833 // Perform semantic analysis that depends on having fully processed both
834 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000835 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000836 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
837 if (!IDecl)
838 continue;
839 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
840 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
841 QualType T = IDecl->getType();
842
843 // C99 6.7.5.2p2: If an identifier is declared to be an object with
844 // static storage duration, it shall not have a variable length array.
845 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
846 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
847 if (VLA->getSizeExpr()) {
848 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
849 IDecl->setInvalidDecl();
850 }
851 }
852 }
853 // Block scope. C99 6.7p7: If an identifier for an object is declared with
854 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
855 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
856 if (T->isIncompleteType()) {
Chris Lattner310369f2007-12-02 07:50:03 +0000857 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
858 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000859 IDecl->setInvalidDecl();
860 }
861 }
862 // File scope. C99 6.9.2p2: A declaration of an identifier for and
863 // object that has file scope without an initializer, and without a
864 // storage-class specifier or with the storage-class specifier "static",
865 // constitutes a tentative definition. Note: A tentative definition with
866 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb716fba2008-01-18 00:39:39 +0000867 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
868 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroffacb6fa62008-01-18 20:40:52 +0000869 const VariableArrayType *VAT = T->getAsVariableArrayType();
870
871 if (VAT && VAT->getSizeExpr() == 0) {
872 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
873 // array to be completed. Don't issue a diagnostic.
874 } else if (T->isIncompleteType()) {
875 // C99 6.9.2p3: If the declaration of an identifier for an object is
876 // a tentative definition and has internal linkage (C99 6.2.2p3), the
877 // declared type shall not be an incomplete type.
Chris Lattner310369f2007-12-02 07:50:03 +0000878 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
879 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000880 IDecl->setInvalidDecl();
881 }
882 }
Chris Lattner776fac82007-06-09 00:53:06 +0000883 }
884 return NewGroup;
885}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000886
887// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000888ParmVarDecl *
Nate Begeman313f8ca2007-11-13 21:49:48 +0000889Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroffd0bf5162007-11-12 03:44:46 +0000890{
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000891 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000892 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
893 // Can this happen for params? We already checked that they don't conflict
894 // among each other. Here they can only shadow globals, which is ok.
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000895 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Chris Lattner9561a0b2007-01-28 08:20:04 +0000896 PI.IdentLoc, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000897
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000898 }
899
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000900 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000901 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000902
903 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
904 // Doing the promotion here has a win and a loss. The win is the type for
905 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
906 // code generator). The loss is the orginal type isn't preserved. For example:
907 //
908 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
909 // int blockvardecl[5];
910 // sizeof(parmvardecl); // size == 4
911 // sizeof(blockvardecl); // size == 20
912 // }
913 //
914 // For expressions, all implicit conversions are captured using the
915 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
916 //
917 // FIXME: If a source translation tool needs to see the original type, then
918 // we need to consider storing both types (in ParmVarDecl)...
919 //
920 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner4f203512008-01-02 22:50:48 +0000921 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
922 // int x[restrict 4] -> int *restrict
Steve Naroff773df5c2007-08-07 22:44:21 +0000923 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner4f203512008-01-02 22:50:48 +0000924 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
925 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +0000926 parmDeclType = Context.getPointerType(parmDeclType);
927
928 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begemana0f78972007-11-13 22:14:47 +0000929 VarDecl::None, 0, PI.AttrList);
Steve Naroffcf871f52007-08-28 18:45:29 +0000930 if (PI.InvalidType)
931 New->setInvalidDecl();
932
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000933 // If this has an identifier, add it to the scope stack.
934 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000935 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000936 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000937 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000938 }
Chris Lattner229ce602006-11-21 01:21:07 +0000939
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000940 return New;
941}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000942
Chris Lattnera55a2cc2007-10-09 17:14:05 +0000943Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +0000944 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000945 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
946 "Not a function declarator!");
947 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
948
949 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
950 // for a K&R function.
951 if (!FTI.hasPrototype) {
952 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
953 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +0000954 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000955 FTI.ArgInfo[i].Ident->getName());
956 // Implicitly declare the argument as type 'int' for lack of a better
957 // type.
958 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
959 }
960 }
961
962 // Since this is a function definition, act as though we have information
963 // about the arguments.
964 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000965 } else {
966 // FIXME: Diagnose arguments without names in C.
967
Chris Lattner5c5fbcc2006-12-03 08:41:30 +0000968 }
969
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000970 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +0000971
972 // See if this is a redefinition.
973 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
974 D.getIdentifierLoc(), GlobalScope);
975 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
976 if (FD->getBody()) {
977 Diag(D.getIdentifierLoc(), diag::err_redefinition,
978 D.getIdentifier()->getName());
979 Diag(FD->getLocation(), diag::err_previous_definition);
980 }
981 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000982 FunctionDecl *FD =
Steve Naroff30d242c2007-09-15 18:49:24 +0000983 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroff012484d2008-01-14 20:51:29 +0000984 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner229ce602006-11-21 01:21:07 +0000985 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +0000986
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000987 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000988 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000989
990 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
991 // no arguments, not a function that takes a single void argument.
992 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerdb2a6ef2007-11-28 18:51:29 +0000993 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
994 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner99d31772007-01-21 22:37:37 +0000995 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +0000996 } else {
Steve Naroffd0bf5162007-11-12 03:44:46 +0000997 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman313f8ca2007-11-13 21:49:48 +0000998 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroffd0bf5162007-11-12 03:44:46 +0000999 FnBodyScope));
1000 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001001 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001002
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001003 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +00001004
Chris Lattnere168f762006-11-10 05:29:30 +00001005 return FD;
1006}
1007
Steve Naroffb313fc32007-11-11 23:20:51 +00001008Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1009 Decl *dcl = static_cast<Decl *>(D);
1010 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1011 FD->setBody((Stmt*)Body);
1012 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroffd78c81b2007-12-13 18:18:56 +00001013 CurFunctionDecl = 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001014 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001015 MD->setBody((Stmt*)Body);
Steve Naroffe3d1ab22007-11-12 13:56:41 +00001016 CurMethodDecl = 0;
Steve Naroffd78c81b2007-12-13 18:18:56 +00001017 }
Chris Lattnere2473062007-05-28 06:28:18 +00001018 // Verify and clean out per-function state.
1019
1020 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001021 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1022 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001023 // Verify that we have no forward references left. If so, there was a goto
1024 // or address of a label taken, but no definition of it. Label fwd
1025 // definitions are indicated with a null substmt.
1026 if (I->second->getSubStmt() == 0) {
1027 LabelStmt *L = I->second;
1028 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001029 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001030
1031 // At this point, we have gotos that use the bogus label. Stitch it into
1032 // the function body so that they aren't leaked and that the AST is well
1033 // formed.
1034 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1035 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1036 }
1037 }
1038 LabelMap.clear();
1039
Steve Naroffb313fc32007-11-11 23:20:51 +00001040 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001041}
1042
Chris Lattnerac18be92006-11-20 06:49:47 +00001043/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1044/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001045ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1046 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +00001047 if (getLangOptions().C99) // Extension in C99.
1048 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1049 else // Legal in C90, but warn about it.
1050 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1051
1052 // FIXME: handle stuff like:
1053 // void foo() { extern float X(); }
1054 // void bar() { X(); } <-- implicit decl for X in another scope.
1055
1056 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001057 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001058 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001059 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001060 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001061 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001062 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001063 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001064 D.SetIdentifier(&II, Loc);
1065
Chris Lattner62d2e662007-01-28 00:21:37 +00001066 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001067 if (Scope *FnS = S->getFnParent())
1068 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +00001069 while (S->getParent())
1070 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +00001071
Steve Naroff2f742082007-09-16 16:16:00 +00001072 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +00001073}
1074
Chris Lattner302b4be2006-11-19 02:31:38 +00001075
Chris Lattner07b201d2007-11-14 06:34:38 +00001076TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001077 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001078 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001079 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001080
Chris Lattner18b19622007-01-22 07:39:13 +00001081 // Scope manipulation handled by caller.
Steve Narofff93b6722007-08-28 20:14:24 +00001082 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1083 T, LastDeclarator);
1084 if (D.getInvalidType())
1085 NewTD->setInvalidDecl();
1086 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001087}
1088
Steve Naroff30d242c2007-09-15 18:49:24 +00001089/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001090/// former case, Name will be non-null. In the later case, Name will be null.
1091/// TagType indicates what kind of tag this is. TK indicates whether this is a
1092/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001093Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001094 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001095 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001096 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001097 assert((Name != 0 || TK == TK_Definition) &&
1098 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001099
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001100 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001101 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001102 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001103 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1104 case DeclSpec::TST_union: Kind = Decl::Union; break;
1105//case DeclSpec::TST_class: Kind = Decl::Class; break;
1106 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001107 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001108
Chris Lattner18b19622007-01-22 07:39:13 +00001109 // If this is a named struct, check to see if there was a previous forward
1110 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001111 if (TagDecl *PrevDecl =
Chris Lattner9561a0b2007-01-28 08:20:04 +00001112 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1113 NameLoc, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001114
1115 // If this is a use of a previous tag, or if the tag is already declared in
1116 // the same scope (so that the definition/declaration completes or
1117 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001118 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001119 // Make sure that this wasn't declared as an enum and now used as a struct
1120 // or something similar.
1121 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001122 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001123 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1124 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001125
1126 // If this is a use or a forward declaration, we're good.
1127 if (TK != TK_Definition)
1128 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001129
Chris Lattner7b9ace62007-01-23 20:11:08 +00001130 // Diagnose attempts to redefine a tag.
1131 if (PrevDecl->isDefinition()) {
1132 Diag(NameLoc, diag::err_redefinition, Name->getName());
1133 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1134 // If this is a redefinition, recover by making this struct be
1135 // anonymous, which will make any later references get the previous
1136 // definition.
1137 Name = 0;
1138 } else {
1139 // Okay, this is definition of a previously declared or referenced tag.
1140 // Move the location of the decl to be the definition site.
1141 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001142 return PrevDecl;
1143 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001144 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001145 // If we get here, this is a definition of a new struct type in a nested
1146 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1147 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001148 }
1149
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001150 // If there is an identifier, use the location of the identifier as the
1151 // location of the decl, otherwise use the location of the struct/union
1152 // keyword.
1153 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1154
Chris Lattner18b19622007-01-22 07:39:13 +00001155 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001156 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001157 switch (Kind) {
1158 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001159 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001160 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1161 // enum X { A, B, C } D; D should chain to X.
1162 New = new EnumDecl(Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001163 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001164 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001165 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001166 case Decl::Union:
1167 case Decl::Struct:
1168 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001169 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1170 // struct X { int A; } D; D should chain to X.
1171 New = new RecordDecl(Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001172 break;
1173 }
Chris Lattner18b19622007-01-22 07:39:13 +00001174
1175 // If this has an identifier, add it to the scope stack.
1176 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001177 // The scope passed in may not be a decl scope. Zip up the scope tree until
1178 // we find one that is.
1179 while ((S->getFlags() & Scope::DeclScope) == 0)
1180 S = S->getParent();
1181
1182 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001183 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001184 Name->setFETokenInfo(New);
1185 S->AddDecl(New);
1186 }
Steve Naroff197616c2007-11-28 22:54:11 +00001187
Chris Lattner18b19622007-01-22 07:39:13 +00001188 return New;
1189}
Chris Lattner1300fb92007-01-23 23:42:53 +00001190
Steve Naroff30d242c2007-09-15 18:49:24 +00001191/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001192/// to create a FieldDecl object for it.
Steve Naroff30d242c2007-09-15 18:49:24 +00001193Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001194 SourceLocation DeclStart,
1195 Declarator &D, ExprTy *BitfieldWidth) {
1196 IdentifierInfo *II = D.getIdentifier();
1197 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00001198 SourceLocation Loc = DeclStart;
1199 if (II) Loc = D.getIdentifierLoc();
1200
Chris Lattner62d2e662007-01-28 00:21:37 +00001201 // FIXME: Unnamed fields can be handled in various different ways, for
1202 // example, unnamed unions inject all members into the struct namespace!
1203
1204
Chris Lattner1300fb92007-01-23 23:42:53 +00001205 if (BitWidth) {
1206 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001207 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001208
1209 // 6.7.2.1p3
1210 // 6.7.2.1p4
1211
1212 } else {
1213 // Not a bitfield.
1214
1215 // validate II.
1216
1217 }
1218
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001219 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001220 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1221 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001222
Steve Naroff8eeeb132007-05-08 21:09:37 +00001223 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1224 // than a variably modified type.
Steve Naroff096dd942007-08-31 17:20:07 +00001225 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1226 Diag(Loc, diag::err_typecheck_illegal_vla,
1227 VAT->getSizeExpr()->getSourceRange());
1228 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001229 }
Chris Lattner776fac82007-06-09 00:53:06 +00001230 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001231 FieldDecl *NewFD;
1232
1233 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel32714062007-11-01 16:29:56 +00001234 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001235 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1236 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1237 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff9e0887cf2007-11-14 14:15:31 +00001238 // FIXME: ivars are currently used to model properties, and
1239 // properties can appear within a protocol.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001240 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1241 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1242 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001243 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001244 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001245
Steve Narofff93b6722007-08-28 20:14:24 +00001246 if (D.getInvalidType() || InvalidDecl)
1247 NewFD->setInvalidDecl();
1248 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001249}
1250
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001251/// TranslateIvarVisibility - Translate visibility from a token ID to an
1252/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001253static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001254TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001255 switch (ivarVisibility) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001256 case tok::objc_private: return ObjCIvarDecl::Private;
1257 case tok::objc_public: return ObjCIvarDecl::Public;
1258 case tok::objc_protected: return ObjCIvarDecl::Protected;
1259 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001260 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001261 }
1262}
1263
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001264void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001265 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001266 DeclTy **Fields, unsigned NumFields,
Steve Naroff33a1e802007-10-29 21:38:07 +00001267 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff30d242c2007-09-15 18:49:24 +00001268 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001269 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1270 assert(EnclosingDecl && "missing record or interface decl");
1271 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1272
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001273 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001274 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001275 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001276 // We discover this when we complete the outer S. Reject and ignore the
1277 // outer S.
1278 Diag(Record->getLocation(), diag::err_nested_redefinition,
1279 Record->getKindName());
1280 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001281 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001282 return;
1283 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001284 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001285 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001286 llvm::SmallVector<FieldDecl*, 32> RecFields;
1287 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001288
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001289 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001290
Steve Naroffdb47ee22007-09-14 22:20:54 +00001291 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1292 assert(FD && "missing field decl");
1293
1294 // Remember all fields.
1295 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001296
1297 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001298 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001299
Steve Naroff2e688fd2007-09-14 23:09:53 +00001300 // If we have visibility info, make sure the AST is set accordingly.
1301 if (visibility)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001302 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001303 TranslateIvarVisibility(visibility[i]));
Steve Naroff2e688fd2007-09-14 23:09:53 +00001304
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001305 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001306 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001307 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001308 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001309 FD->setInvalidDecl();
1310 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001311 continue;
1312 }
Chris Lattner82625602007-01-24 02:26:21 +00001313 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001314 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001315 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00001316 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001317 FD->setInvalidDecl();
1318 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00001319 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001320 }
Chris Lattner82625602007-01-24 02:26:21 +00001321 if (i != NumFields-1 || // ... that the last member ...
1322 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001323 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001324 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001325 FD->setInvalidDecl();
1326 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001327 continue;
1328 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001329 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001330 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1331 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001332 FD->setInvalidDecl();
1333 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001334 continue;
1335 }
Chris Lattner720a0542007-01-25 00:44:24 +00001336 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001337 if (Record)
1338 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001339 }
Chris Lattner720a0542007-01-25 00:44:24 +00001340 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1341 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001342 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001343 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1344 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001345 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001346 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001347 } else {
1348 // If this is a struct/class and this is not the last element, reject
1349 // it. Note that GCC supports variable sized arrays in the middle of
1350 // structures.
1351 if (i != NumFields-1) {
1352 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1353 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001354 FD->setInvalidDecl();
1355 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001356 continue;
1357 }
Chris Lattner720a0542007-01-25 00:44:24 +00001358 // We support flexible arrays at the end of structs in other structs
1359 // as an extension.
1360 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1361 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00001362 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001363 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001364 }
1365 }
1366 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001367 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001368 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001369 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1370 FD->getName());
1371 FD->setInvalidDecl();
1372 EnclosingDecl->setInvalidDecl();
1373 continue;
1374 }
Chris Lattner82625602007-01-24 02:26:21 +00001375 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001376 if (IdentifierInfo *II = FD->getIdentifier()) {
1377 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001378 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001379 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1380 // Find the previous decl.
1381 SourceLocation PrevLoc;
1382 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1383 assert(i != e && "Didn't find previous def!");
1384 if (RecFields[i]->getIdentifier() == II) {
1385 PrevLoc = RecFields[i]->getLocation();
1386 break;
1387 }
1388 }
1389 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001390 FD->setInvalidDecl();
1391 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001392 continue;
1393 }
Chris Lattner82625602007-01-24 02:26:21 +00001394 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001395 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001396 }
Chris Lattner82625602007-01-24 02:26:21 +00001397
Chris Lattner82625602007-01-24 02:26:21 +00001398 // Okay, we successfully defined 'Record'.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001399 if (Record)
1400 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001401 else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001402 ObjCIvarDecl **ClsFields =
1403 reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1404 if (isa<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1405 cast<ObjCInterfaceDecl>(static_cast<Decl*>(RecDecl))->
Steve Naroff33a1e802007-10-29 21:38:07 +00001406 addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001407 else if (isa<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1408 ObjCImplementationDecl* IMPDecl =
1409 cast<ObjCImplementationDecl>(static_cast<Decl*>(RecDecl));
1410 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1411 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00001412 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001413 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001414 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001415}
1416
Steve Naroff30d242c2007-09-15 18:49:24 +00001417Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001418 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001419 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001420 SourceLocation EqualLoc, ExprTy *val) {
1421 theEnumDecl = theEnumDecl; // silence unused warning.
1422 EnumConstantDecl *LastEnumConst =
1423 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1424 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001425
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001426 // The scope passed in may not be a decl scope. Zip up the scope tree until
1427 // we find one that is.
1428 while ((S->getFlags() & Scope::DeclScope) == 0)
1429 S = S->getParent();
1430
Chris Lattner8116d1b2007-01-25 22:38:29 +00001431 // Verify that there isn't already something declared with this name in this
1432 // scope.
Steve Naroff9def2b12007-09-13 21:41:19 +00001433 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1434 IdLoc, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001435 if (S->isDeclScope(PrevDecl)) {
1436 if (isa<EnumConstantDecl>(PrevDecl))
1437 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1438 else
1439 Diag(IdLoc, diag::err_redefinition, Id->getName());
1440 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner4ef40012007-06-11 01:28:17 +00001441 // FIXME: Don't leak memory: delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001442 return 0;
1443 }
1444 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001445
Chris Lattner23b7eb62007-06-15 23:05:46 +00001446 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001447 QualType EltTy;
1448 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001449 // Make sure to promote the operand type to int.
1450 UsualUnaryConversions(Val);
1451
Chris Lattner4ef40012007-06-11 01:28:17 +00001452 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1453 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001454 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001455 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1456 Id->getName());
1457 // FIXME: Don't leak memory: delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001458 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001459 } else {
1460 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001461 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001462 }
1463
1464 if (!Val) {
1465 if (LastEnumConst) {
1466 // Assign the last value + 1.
1467 EnumVal = LastEnumConst->getInitVal();
1468 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001469
1470 // Check for overflow on increment.
1471 if (EnumVal < LastEnumConst->getInitVal())
1472 Diag(IdLoc, diag::warn_enum_value_overflow);
1473
Chris Lattnerf283a372007-08-27 17:37:24 +00001474 EltTy = LastEnumConst->getType();
1475 } else {
1476 // First value, set to zero.
1477 EltTy = Context.IntTy;
Chris Lattner9cf21c52007-09-04 02:45:27 +00001478 EnumVal.zextOrTrunc(
1479 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001480 }
Steve Naroff63969212007-05-07 21:22:42 +00001481 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001482
Chris Lattner4ef40012007-06-11 01:28:17 +00001483 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1484 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001485
1486 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001487 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001488 Id->setFETokenInfo(New);
1489 S->AddDecl(New);
1490 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001491}
1492
Steve Naroff30d242c2007-09-15 18:49:24 +00001493void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001494 DeclTy **Elements, unsigned NumElements) {
1495 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1496 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1497
Chris Lattner67933c02007-08-28 05:10:31 +00001498 // TODO: If the result value doesn't fit in an int, it must be a long or long
1499 // long value. ISO C does not support this, but GCC does as an extension,
1500 // emit a warning.
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001501 unsigned IntWidth =
1502 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner67933c02007-08-28 05:10:31 +00001503
1504
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001505 // Verify that all the values are okay, compute the size of the values, and
1506 // reverse the list.
1507 unsigned NumNegativeBits = 0;
1508 unsigned NumPositiveBits = 0;
1509
1510 // Keep track of whether all elements have type int.
1511 bool AllElementsInt = true;
1512
Chris Lattner4ef40012007-06-11 01:28:17 +00001513 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001514 for (unsigned i = 0; i != NumElements; ++i) {
1515 EnumConstantDecl *ECD =
1516 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1517 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001518
1519 // If the enum value doesn't fit in an int, emit an extension warning.
1520 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1521 "Should have promoted value to int");
1522 const llvm::APSInt &InitVal = ECD->getInitVal();
1523 if (InitVal.getBitWidth() > IntWidth) {
1524 llvm::APSInt V(InitVal);
1525 V.trunc(IntWidth);
1526 V.extend(InitVal.getBitWidth());
1527 if (V != InitVal)
1528 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1529 InitVal.toString());
1530 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001531
1532 // Keep track of the size of positive and negative values.
1533 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00001534 NumPositiveBits = std::max(NumPositiveBits,
1535 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001536 else
Chris Lattner49f980c2008-01-14 21:47:29 +00001537 NumNegativeBits = std::max(NumNegativeBits,
1538 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001539
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001540 // Keep track of whether every enum element has type int (very commmon).
1541 if (AllElementsInt)
1542 AllElementsInt = ECD->getType() == Context.IntTy;
1543
Chris Lattner4ef40012007-06-11 01:28:17 +00001544 ECD->setNextDeclarator(EltList);
1545 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001546 }
1547
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001548 // Figure out the type that should be used for this enum.
1549 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1550 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001551 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001552
1553 if (NumNegativeBits) {
1554 // If there is a negative value, figure out the smallest integer type (of
1555 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001556 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001557 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001558 BestWidth = IntWidth;
1559 } else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001560 BestWidth =
1561 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1562
Chris Lattner3a370bf2007-08-29 17:31:48 +00001563 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001564 BestType = Context.LongTy;
1565 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001566 BestWidth = Context.Target.getLongLongWidth(
1567 Context.getFullLoc(Enum->getLocation()));
1568
Chris Lattner3a370bf2007-08-29 17:31:48 +00001569 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001570 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1571 BestType = Context.LongLongTy;
1572 }
1573 }
1574 } else {
1575 // If there is no negative value, figure out which of uint, ulong, ulonglong
1576 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001577 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001578 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001579 BestWidth = IntWidth;
1580 } else if (NumPositiveBits <=
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001581 (BestWidth = Context.Target.getLongWidth(
1582 Context.getFullLoc(Enum->getLocation()))))
1583
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001584 BestType = Context.UnsignedLongTy;
1585 else {
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001586 BestWidth =
1587 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1588
Chris Lattner3a370bf2007-08-29 17:31:48 +00001589 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001590 "How could an initializer get larger than ULL?");
1591 BestType = Context.UnsignedLongLongTy;
1592 }
1593 }
1594
Chris Lattner3a370bf2007-08-29 17:31:48 +00001595 // Loop over all of the enumerator constants, changing their types to match
1596 // the type of the enum if needed.
1597 for (unsigned i = 0; i != NumElements; ++i) {
1598 EnumConstantDecl *ECD =
1599 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1600 if (!ECD) continue; // Already issued a diagnostic.
1601
1602 // Standard C says the enumerators have int type, but we allow, as an
1603 // extension, the enumerators to be larger than int size. If each
1604 // enumerator value fits in an int, type it as an int, otherwise type it the
1605 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1606 // that X has type 'int', not 'unsigned'.
1607 if (ECD->getType() == Context.IntTy)
1608 continue; // Already int type.
1609
1610 // Determine whether the value fits into an int.
1611 llvm::APSInt InitVal = ECD->getInitVal();
1612 bool FitsInInt;
1613 if (InitVal.isUnsigned() || !InitVal.isNegative())
1614 FitsInInt = InitVal.getActiveBits() < IntWidth;
1615 else
1616 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1617
1618 // If it fits into an integer type, force it. Otherwise force it to match
1619 // the enum decl type.
1620 QualType NewTy;
1621 unsigned NewWidth;
1622 bool NewSign;
1623 if (FitsInInt) {
1624 NewTy = Context.IntTy;
1625 NewWidth = IntWidth;
1626 NewSign = true;
1627 } else if (ECD->getType() == BestType) {
1628 // Already the right type!
1629 continue;
1630 } else {
1631 NewTy = BestType;
1632 NewWidth = BestWidth;
1633 NewSign = BestType->isSignedIntegerType();
1634 }
1635
1636 // Adjust the APSInt value.
1637 InitVal.extOrTrunc(NewWidth);
1638 InitVal.setIsSigned(NewSign);
1639 ECD->setInitVal(InitVal);
1640
1641 // Adjust the Expr initializer and type.
1642 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1643 ECD->setType(NewTy);
1644 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001645
Chris Lattner1c1f9322007-08-28 18:24:31 +00001646 Enum->defineElements(EltList, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001647}
Chris Lattner1300fb92007-01-23 23:42:53 +00001648
Chris Lattner38376f12008-01-12 07:05:38 +00001649Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1650 SourceLocation LBrace,
1651 SourceLocation RBrace,
1652 const char *Lang,
1653 unsigned StrSize,
1654 DeclTy *D) {
1655 LinkageSpecDecl::LanguageIDs Language;
1656 Decl *dcl = static_cast<Decl *>(D);
1657 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1658 Language = LinkageSpecDecl::lang_c;
1659 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1660 Language = LinkageSpecDecl::lang_cxx;
1661 else {
1662 Diag(Loc, diag::err_bad_language);
1663 return 0;
1664 }
1665
1666 // FIXME: Add all the various semantics of linkage specifications
1667 return new LinkageSpecDecl(Loc, Language, dcl);
1668}
1669
Steve Naroffa8fd9732007-06-11 00:35:03 +00001670void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson081f1b42007-12-19 06:16:30 +00001671 const char *attrName = rawAttr->getAttributeName()->getName();
1672 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1673
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001674 // Normalize the attribute name, __foo__ becomes foo.
1675 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1676 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1677 attrName += 2;
1678 attrLen -= 4;
1679 }
1680
1681 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001682 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001683 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001684 if (!newType.isNull()) // install the new vector type into the decl
1685 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001686 }
1687 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001688 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1689 rawAttr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001690 if (!newType.isNull()) // install the new vector type into the decl
1691 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001692 }
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001693 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001694 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1695 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1696 else
Steve Naroff91fcddb2007-07-18 18:00:27 +00001697 Diag(rawAttr->getAttributeLoc(),
1698 diag::err_typecheck_ocu_vector_not_typedef);
Anders Carlsson721f6012007-12-19 07:19:40 +00001699 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1700 HandleAlignedAttribute(New, rawAttr);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001701 }
Anders Carlsson721f6012007-12-19 07:19:40 +00001702
Steve Naroffa8fd9732007-06-11 00:35:03 +00001703 // FIXME: add other attributes...
1704}
1705
1706void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1707 AttributeList *declarator_postfix) {
1708 while (declspec_prefix) {
1709 HandleDeclAttribute(New, declspec_prefix);
1710 declspec_prefix = declspec_prefix->getNext();
1711 }
1712 while (declarator_postfix) {
1713 HandleDeclAttribute(New, declarator_postfix);
1714 declarator_postfix = declarator_postfix->getNext();
1715 }
1716}
1717
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001718void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1719 AttributeList *rawAttr) {
1720 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson721f6012007-12-19 07:19:40 +00001721 // check the attribute arguments.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001722 if (rawAttr->getNumArgs() != 1) {
1723 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1724 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001725 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001726 }
1727 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1728 llvm::APSInt vecSize(32);
1729 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1730 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1731 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001732 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001733 }
1734 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1735 // in conjunction with complex types (pointers, arrays, functions, etc.).
1736 Type *canonType = curType.getCanonicalType().getTypePtr();
1737 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1738 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1739 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001740 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001741 }
1742 // unlike gcc's vector_size attribute, the size is specified as the
1743 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001744 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001745
1746 if (vectorSize == 0) {
1747 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1748 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001749 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001750 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001751 // Instantiate/Install the vector type, the number of elements is > 0.
1752 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1753 // Remember this typedef decl, we will need it later for diagnostics.
1754 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001755}
1756
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001757QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001758 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001759 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001760 if (rawAttr->getNumArgs() != 1) {
1761 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1762 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001763 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001764 }
1765 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001766 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001767 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Steve Naroffa8fd9732007-06-11 00:35:03 +00001768 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1769 sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001770 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001771 }
1772 // navigate to the base type - we need to provide for vector pointers,
1773 // vector arrays, and functions returning vectors.
1774 Type *canonType = curType.getCanonicalType().getTypePtr();
1775
Steve Naroff91fcddb2007-07-18 18:00:27 +00001776 if (canonType->isPointerType() || canonType->isArrayType() ||
1777 canonType->isFunctionType()) {
Chris Lattner0f8a39c2007-12-19 05:38:06 +00001778 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff91fcddb2007-07-18 18:00:27 +00001779 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1780 do {
1781 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1782 canonType = PT->getPointeeType().getTypePtr();
1783 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1784 canonType = AT->getElementType().getTypePtr();
1785 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1786 canonType = FT->getResultType().getTypePtr();
1787 } while (canonType->isPointerType() || canonType->isArrayType() ||
1788 canonType->isFunctionType());
1789 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001790 }
1791 // the base type must be integer or float.
1792 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1793 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1794 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001795 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001796 }
Chris Lattner9cf21c52007-09-04 02:45:27 +00001797 unsigned typeSize = static_cast<unsigned>(
1798 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001799 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001800 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001801
1802 // the vector size needs to be an integral multiple of the type size.
1803 if (vectorSize % typeSize) {
1804 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1805 sizeExpr->getSourceRange());
1806 return QualType();
1807 }
1808 if (vectorSize == 0) {
1809 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1810 sizeExpr->getSourceRange());
1811 return QualType();
1812 }
1813 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1814 // the number of elements to be a power of two (unlike GCC).
1815 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001816 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001817}
1818
Anders Carlsson721f6012007-12-19 07:19:40 +00001819void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1820{
1821 // check the attribute arguments.
Anders Carlsson2c26cc22007-12-19 17:43:24 +00001822 // FIXME: Handle the case where are no arguments.
Anders Carlsson721f6012007-12-19 07:19:40 +00001823 if (rawAttr->getNumArgs() != 1) {
1824 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1825 std::string("1"));
1826 return;
1827 }
1828
1829 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1830 llvm::APSInt alignment(32);
1831 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1832 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1833 alignmentExpr->getSourceRange());
1834 return;
1835 }
1836}