blob: df6dd5c2e18ffb0ab16bdb840f715cc970ead1c4 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson3f70c542008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000033using namespace clang;
34
Chris Lattner4b009652007-07-25 00:24:17 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000036 Decl *IIDecl = II.getFETokenInfo<Decl>();
37 // Find first occurance of none-tagged declaration
38 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
39 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
40 if (!IIDecl)
41 return 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000042 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000043 return IIDecl;
Ted Kremenek42730c52008-01-07 19:49:32 +000044 if (ObjCCompatibleAliasDecl *ADecl =
45 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000046 return ADecl->getClassInterface();
Steve Naroff81f1bba2007-09-06 21:24:23 +000047 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000048}
49
Steve Naroff9637a9b2007-10-09 22:01:59 +000050void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000051 if (S->decl_empty()) return;
52 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53
Chris Lattner4b009652007-07-25 00:24:17 +000054 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000056 Decl *TmpD = static_cast<Decl*>(*I);
57 assert(TmpD && "This decl didn't get pushed??");
58 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
59 assert(D && "This decl isn't a ScopedDecl?");
60
Chris Lattner4b009652007-07-25 00:24:17 +000061 IdentifierInfo *II = D->getIdentifier();
62 if (!II) continue;
63
64 // Unlink this decl from the identifier. Because the scope contains decls
65 // in an unordered collection, and because we have multiple identifier
66 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
67 if (II->getFETokenInfo<Decl>() == D) {
68 // Normal case, no multiple decls in different namespaces.
69 II->setFETokenInfo(D->getNext());
70 } else {
71 // Scan ahead. There are only three namespaces in C, so this loop can
72 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000073 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000074 while (SomeDecl->getNext() != D) {
75 SomeDecl = SomeDecl->getNext();
76 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
77 }
78 SomeDecl->setNext(D->getNext());
79 }
80
81 // This will have to be revisited for C++: there we want to nest stuff in
82 // namespace decls etc. Even for C, we might want a top-level translation
83 // unit decl or something.
84 if (!CurFunctionDecl)
85 continue;
86
87 // Chain this decl to the containing function, it now owns the memory for
88 // the decl.
89 D->setNext(CurFunctionDecl->getDeclChain());
90 CurFunctionDecl->setDeclChain(D);
91 }
92}
93
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000094/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
95/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian8eaeff52007-10-12 19:53:08 +000096/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000097/// Bypassing the alias of a class by returning the aliased class.
98ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
99 ScopedDecl *IDecl;
100 // Scan up the scope chain looking for a decl that matches this identifier
101 // that is in the appropriate namespace.
102 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
103 IDecl = IDecl->getNext())
104 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
105 break;
106
Ted Kremenek42730c52008-01-07 19:49:32 +0000107 if (ObjCCompatibleAliasDecl *ADecl =
108 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000109 return ADecl->getClassInterface();
110 return IDecl;
111}
112
Ted Kremenek42730c52008-01-07 19:49:32 +0000113/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000114/// return 0 if one not found.
Ted Kremenek42730c52008-01-07 19:49:32 +0000115ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000116 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek42730c52008-01-07 19:49:32 +0000117 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000118}
119
Chris Lattner4b009652007-07-25 00:24:17 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000124 if (II == 0) return 0;
125 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126
127 // Scan up the scope chain looking for a decl that matches this identifier
128 // that is in the appropriate namespace. This search should not take long, as
129 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000131 if (D->getIdentifierNamespace() == NS)
132 return D;
133
134 // If we didn't find a use of this identifier, and if the identifier
135 // corresponds to a compiler builtin, create the decl object for the builtin
136 // now, injecting it into translation unit scope, and return it.
137 if (NS == Decl::IDNS_Ordinary) {
138 // If this is a builtin on some other target, or if this builtin varies
139 // across targets (e.g. in type), emit a diagnostic and mark the translation
140 // unit non-portable for using it.
141 if (II->isNonPortableBuiltin()) {
142 // Only emit this diagnostic once for this builtin.
143 II->setNonPortableBuiltin(false);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000144 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner4b009652007-07-25 00:24:17 +0000145 diag::port_target_builtin_use);
146 }
147 // If this is a builtin on this (or all) targets, create the decl.
148 if (unsigned BuiltinID = II->getBuiltinID())
149 return LazilyCreateBuiltin(II, BuiltinID, S);
150 }
151 return 0;
152}
153
Anders Carlsson36760332007-10-15 20:28:48 +0000154void Sema::InitBuiltinVaListType()
155{
156 if (!Context.getBuiltinVaListType().isNull())
157 return;
158
159 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
160 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
161 SourceLocation(), TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000162 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000163 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164}
165
Chris Lattner4b009652007-07-25 00:24:17 +0000166/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000168ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000170 Builtin::ID BID = (Builtin::ID)bid;
171
Anders Carlsson36760332007-10-15 20:28:48 +0000172 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000173 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000174 BID == Builtin::BI__builtin_va_end)
175 InitBuiltinVaListType();
176
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000177 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000178 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000179 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000180
181 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000182 if (Scope *FnS = S->getFnParent())
183 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000184 while (S->getParent())
185 S = S->getParent();
186 S->AddDecl(New);
187
188 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000189 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000190 // Scan until we find the last (outermost) decl in the id chain.
191 while (LastDecl->getNext())
192 LastDecl = LastDecl->getNext();
193 // Insert before (outside) it.
194 LastDecl->setNext(New);
195 } else {
196 II->setFETokenInfo(New);
197 }
Chris Lattner4b009652007-07-25 00:24:17 +0000198 return New;
199}
200
201/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
202/// and scope as a previous declaration 'Old'. Figure out how to resolve this
203/// situation, merging decls or emitting diagnostics as appropriate.
204///
Steve Naroffcb597472007-09-13 21:41:19 +0000205TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000206 // Verify the old decl was also a typedef.
207 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
214
Steve Naroffae84af82007-10-31 18:42:27 +0000215 // Allow multiple definitions for ObjC built-in typedefs.
216 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000217 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000218 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000219
220 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
221 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
222 // *either* declaration is in a system header. The code below implements
223 // this adhoc compatibility rule. FIXME: The following code will not
224 // work properly when compiling ".i" files (containing preprocessed output).
225 SourceManager &SrcMgr = Context.getSourceManager();
226 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
227 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
228 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
229 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
230 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
231
Steve Naroff73a07032008-02-07 03:50:06 +0000232 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
233 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
234 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000235 return New;
Steve Naroffae84af82007-10-31 18:42:27 +0000236
Chris Lattner4b009652007-07-25 00:24:17 +0000237 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
238 // TODO: This is totally simplistic. It should handle merging functions
239 // together etc, merging extern int X; int X; ...
240 Diag(New->getLocation(), diag::err_redefinition, New->getName());
241 Diag(Old->getLocation(), diag::err_previous_definition);
242 return New;
243}
244
245/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
246/// and scope as a previous declaration 'Old'. Figure out how to resolve this
247/// situation, merging decls or emitting diagnostics as appropriate.
248///
Steve Naroffcb597472007-09-13 21:41:19 +0000249FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000250 // Verify the old decl was also a function.
251 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
252 if (!Old) {
253 Diag(New->getLocation(), diag::err_redefinition_different_kind,
254 New->getName());
255 Diag(OldD->getLocation(), diag::err_previous_definition);
256 return New;
257 }
258
Chris Lattner60476ff2007-11-20 19:04:50 +0000259 QualType OldQType = Old->getCanonicalType();
260 QualType NewQType = New->getCanonicalType();
261
Steve Naroff1d5bd642008-01-14 20:51:29 +0000262 // Function types need to be compatible, not identical. This handles
263 // duplicate function decls like "void f(int); void f(enum X);" properly.
264 if (Context.functionTypesAreCompatible(OldQType, NewQType))
265 return New;
Chris Lattner1470b072007-11-06 06:07:26 +0000266
Steve Naroff6c9e7922008-01-16 15:01:34 +0000267 // A function that has already been declared has been redeclared or defined
268 // with a different type- show appropriate diagnostic
269 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
270 diag::err_previous_declaration;
271
Chris Lattner4b009652007-07-25 00:24:17 +0000272 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
273 // TODO: This is totally simplistic. It should handle merging functions
274 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000275 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
276 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000277 return New;
278}
279
Chris Lattnerf9167d12007-11-06 04:28:31 +0000280/// equivalentArrayTypes - Used to determine whether two array types are
281/// equivalent.
282/// We need to check this explicitly as an incomplete array definition is
283/// considered a VariableArrayType, so will not match a complete array
284/// definition that would be otherwise equivalent.
285static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
286 const ArrayType *NewAT = NewQType->getAsArrayType();
287 const ArrayType *OldAT = OldQType->getAsArrayType();
288
289 if (!NewAT || !OldAT)
290 return false;
291
292 // If either (or both) array types in incomplete we need to strip off the
293 // outer VariableArrayType. Once the outer VAT is removed the remaining
294 // types must be identical if the array types are to be considered
295 // equivalent.
296 // eg. int[][1] and int[1][1] become
297 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
298 // removing the outermost VAT gives
299 // CAT(1, int) and CAT(1, int)
300 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000301 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000302 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
303 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000304 NewQType = NewAT->getElementType().getCanonicalType();
305 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000306 }
307
308 return NewQType == OldQType;
309}
310
Chris Lattner4b009652007-07-25 00:24:17 +0000311/// MergeVarDecl - We just parsed a variable 'New' which has the same name
312/// and scope as a previous declaration 'Old'. Figure out how to resolve this
313/// situation, merging decls or emitting diagnostics as appropriate.
314///
315/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
316/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
317///
Steve Naroffcb597472007-09-13 21:41:19 +0000318VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000319 // Verify the old decl was also a variable.
320 VarDecl *Old = dyn_cast<VarDecl>(OldD);
321 if (!Old) {
322 Diag(New->getLocation(), diag::err_redefinition_different_kind,
323 New->getName());
324 Diag(OldD->getLocation(), diag::err_previous_definition);
325 return New;
326 }
327 // Verify the types match.
Chris Lattnerf9167d12007-11-06 04:28:31 +0000328 if (Old->getCanonicalType() != New->getCanonicalType() &&
329 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Chris Lattner4b009652007-07-25 00:24:17 +0000330 Diag(New->getLocation(), diag::err_redefinition, New->getName());
331 Diag(Old->getLocation(), diag::err_previous_definition);
332 return New;
333 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000334 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
335 if (New->getStorageClass() == VarDecl::Static &&
336 (Old->getStorageClass() == VarDecl::None ||
337 Old->getStorageClass() == VarDecl::Extern)) {
338 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
339 Diag(Old->getLocation(), diag::err_previous_definition);
340 return New;
341 }
342 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
343 if (New->getStorageClass() != VarDecl::Static &&
344 Old->getStorageClass() == VarDecl::Static) {
345 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
346 Diag(Old->getLocation(), diag::err_previous_definition);
347 return New;
348 }
349 // We've verified the types match, now handle "tentative" definitions.
350 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
351 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
352
353 if (OldFSDecl && NewFSDecl) {
354 // Handle C "tentative" external object definitions (C99 6.9.2).
355 bool OldIsTentative = false;
356 bool NewIsTentative = false;
357
358 if (!OldFSDecl->getInit() &&
359 (OldFSDecl->getStorageClass() == VarDecl::None ||
360 OldFSDecl->getStorageClass() == VarDecl::Static))
361 OldIsTentative = true;
362
363 // FIXME: this check doesn't work (since the initializer hasn't been
364 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
365 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
366 // thrown out the old decl.
367 if (!NewFSDecl->getInit() &&
368 (NewFSDecl->getStorageClass() == VarDecl::None ||
369 NewFSDecl->getStorageClass() == VarDecl::Static))
370 ; // change to NewIsTentative = true; once the code is moved.
371
372 if (NewIsTentative || OldIsTentative)
373 return New;
374 }
375 if (Old->getStorageClass() != VarDecl::Extern &&
376 New->getStorageClass() != VarDecl::Extern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000377 Diag(New->getLocation(), diag::err_redefinition, New->getName());
378 Diag(Old->getLocation(), diag::err_previous_definition);
379 }
380 return New;
381}
382
383/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
384/// no declarator (e.g. "struct foo;") is parsed.
385Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
386 // TODO: emit error on 'int;' or 'const enum foo;'.
387 // TODO: emit error on 'typedef int;'
388 // if (!DS.isMissingDeclaratorOk()) Diag(...);
389
Steve Naroffedafc0b2007-11-17 21:37:36 +0000390 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000391}
392
Steve Narofff0b23542008-01-10 22:15:12 +0000393bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000394 // Get the type before calling CheckSingleAssignmentConstraints(), since
395 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000396 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000397
Chris Lattner005ed752008-01-04 18:04:52 +0000398 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
399 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
400 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000401}
402
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000403bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000404 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000405 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000406 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000407 return true; // types weren't compatible.
408
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000409 if (savExpr != expr) // The type was promoted, update initializer list.
410 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000411 return false;
412}
413
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000414bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000415 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000416 // C99 6.7.8p14. We have an array of character type with unknown size
417 // being initialized to a string literal.
418 llvm::APSInt ConstVal(32);
419 ConstVal = strLiteral->getByteLength() + 1;
420 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000421 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000422 ArrayType::Normal, 0);
423 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
424 // C99 6.7.8p14. We have an array of character type with known size.
425 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
426 Diag(strLiteral->getSourceRange().getBegin(),
427 diag::warn_initializer_string_for_char_array_too_long,
428 strLiteral->getSourceRange());
429 } else {
430 assert(0 && "HandleStringLiteralInit(): Invalid array type");
431 }
432 // Set type from "char *" to "constant array of char".
433 strLiteral->setType(DeclT);
434 // For now, we always return false (meaning success).
435 return false;
436}
437
438StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000439 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000440 if (AT && AT->getElementType()->isCharType()) {
441 return dyn_cast<StringLiteral>(Init);
442 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000443 return 0;
444}
445
Steve Narofff3cb5142008-01-25 00:51:06 +0000446// CheckInitializerListTypes - Checks the types of elements of an initializer
447// list. This function is recursive: it calls itself to initialize subelements
448// of aggregate types. Note that the topLevel parameter essentially refers to
449// whether this expression "owns" the initializer list passed in, or if this
450// initialization is taking elements out of a parent initializer. Each
451// call to this function adds zero or more to startIndex, reports any errors,
452// and returns true if it found any inconsistent types.
453bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
454 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000455 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000456
457 if (DeclType->isScalarType()) {
458 // The simplest case: initializing a single scalar
459 if (topLevel) {
460 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
461 IList->getSourceRange());
462 }
463 if (startIndex < IList->getNumInits()) {
464 Expr* expr = IList->getInit(startIndex);
465 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
466 // FIXME: Should an error be reported here instead?
467 unsigned newIndex = 0;
468 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
469 } else {
470 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
471 }
472 ++startIndex;
473 }
474 // FIXME: Should an error be reported for empty initializer list + scalar?
475 } else if (DeclType->isVectorType()) {
476 if (startIndex < IList->getNumInits()) {
477 const VectorType *VT = DeclType->getAsVectorType();
478 int maxElements = VT->getNumElements();
479 QualType elementType = VT->getElementType();
480
481 for (int i = 0; i < maxElements; ++i) {
482 // Don't attempt to go past the end of the init list
483 if (startIndex >= IList->getNumInits())
484 break;
485 Expr* expr = IList->getInit(startIndex);
486 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
487 unsigned newIndex = 0;
488 hadError |= CheckInitializerListTypes(SubInitList, elementType,
489 true, newIndex);
490 ++startIndex;
491 } else {
492 hadError |= CheckInitializerListTypes(IList, elementType,
493 false, startIndex);
494 }
495 }
496 }
497 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
498 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000499 if (startIndex < IList->getNumInits() && !topLevel &&
500 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
501 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000502 // We found a compatible struct; per the standard, this initializes the
503 // struct. (The C standard technically says that this only applies for
504 // initializers for declarations with automatic scope; however, this
505 // construct is unambiguous anyway because a struct cannot contain
506 // a type compatible with itself. We'll output an error when we check
507 // if the initializer is constant.)
508 // FIXME: Is a call to CheckSingleInitializer required here?
509 ++startIndex;
510 } else {
511 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000512
Steve Naroff576df292008-02-11 21:52:37 +0000513 // If the record is invalid, some of it's members are invalid. To avoid
514 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000515 if (structDecl->isInvalidDecl())
516 return true;
517
Steve Narofff3cb5142008-01-25 00:51:06 +0000518 // If structDecl is a forward declaration, this loop won't do anything;
519 // That's okay, because an error should get printed out elsewhere. It
520 // might be worthwhile to skip over the rest of the initializer, though.
521 int numMembers = structDecl->getNumMembers() -
522 structDecl->hasFlexibleArrayMember();
523 for (int i = 0; i < numMembers; i++) {
524 // Don't attempt to go past the end of the init list
525 if (startIndex >= IList->getNumInits())
526 break;
527 FieldDecl * curField = structDecl->getMember(i);
528 if (!curField->getIdentifier()) {
529 // Don't initialize unnamed fields, e.g. "int : 20;"
530 continue;
531 }
532 QualType fieldType = curField->getType();
533 Expr* expr = IList->getInit(startIndex);
534 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
535 unsigned newStart = 0;
536 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
537 true, newStart);
538 ++startIndex;
539 } else {
540 hadError |= CheckInitializerListTypes(IList, fieldType,
541 false, startIndex);
542 }
543 if (DeclType->isUnionType())
544 break;
545 }
546 // FIXME: Implement flexible array initialization GCC extension (it's a
547 // really messy extension to implement, unfortunately...the necessary
548 // information isn't actually even here!)
549 }
550 } else if (DeclType->isArrayType()) {
551 // Check for the special-case of initializing an array with a string.
552 if (startIndex < IList->getNumInits()) {
553 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
554 DeclType)) {
555 CheckStringLiteralInit(lit, DeclType);
556 ++startIndex;
557 if (topLevel && startIndex < IList->getNumInits()) {
558 // We have leftover initializers; warn
559 Diag(IList->getInit(startIndex)->getLocStart(),
560 diag::err_excess_initializers_in_char_array_initializer,
561 IList->getInit(startIndex)->getSourceRange());
562 }
563 return false;
564 }
565 }
566 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000567 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000568 // FIXME: use a proper constant
569 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000570 } else if (const VariableArrayType *VAT =
571 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000572 // Check for VLAs; in standard C it would be possible to check this
573 // earlier, but I don't know where clang accepts VLAs (gcc accepts
574 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000575 Diag(VAT->getSizeExpr()->getLocStart(),
576 diag::err_variable_object_no_init,
577 VAT->getSizeExpr()->getSourceRange());
578 hadError = true;
579 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000580 } else {
581 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
582 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
583 }
584 QualType elementType = DeclType->getAsArrayType()->getElementType();
585 int numElements = 0;
586 for (int i = 0; i < maxElements; ++i, ++numElements) {
587 // Don't attempt to go past the end of the init list
588 if (startIndex >= IList->getNumInits())
589 break;
590 Expr* expr = IList->getInit(startIndex);
591 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
592 unsigned newIndex = 0;
593 hadError |= CheckInitializerListTypes(SubInitList, elementType,
594 true, newIndex);
595 ++startIndex;
596 } else {
597 hadError |= CheckInitializerListTypes(IList, elementType,
598 false, startIndex);
599 }
600 }
Eli Friedmane0079792008-02-15 12:53:51 +0000601 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000602 // If this is an incomplete array type, the actual type needs to
603 // be calculated here
604 if (numElements == 0) {
605 // Sizing an array implicitly to zero is not allowed
606 // (It could in theory be allowed, but it doesn't really matter.)
607 Diag(IList->getLocStart(),
608 diag::err_at_least_one_initializer_needed_to_size_array);
609 hadError = true;
610 } else {
611 llvm::APSInt ConstVal(32);
612 ConstVal = numElements;
613 DeclType = Context.getConstantArrayType(elementType, ConstVal,
614 ArrayType::Normal, 0);
615 }
616 }
617 } else {
618 assert(0 && "Aggregate that isn't a function or array?!");
619 }
620 } else {
621 // In C, all types are either scalars or aggregates, but
622 // additional handling is needed here for C++ (and possibly others?).
623 assert(0 && "Unsupported initializer type");
624 }
625
626 // If this init list is a base list, we set the type; an initializer doesn't
627 // fundamentally have a type, but this makes the ASTs a bit easier to read
628 if (topLevel)
629 IList->setType(DeclType);
630
631 if (topLevel && startIndex < IList->getNumInits()) {
632 // We have leftover initializers; warn
633 Diag(IList->getInit(startIndex)->getLocStart(),
634 diag::warn_excess_initializers,
635 IList->getInit(startIndex)->getSourceRange());
636 }
637 return hadError;
638}
639
640bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000641 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
642 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000643 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000644 return Diag(VAT->getSizeExpr()->getLocStart(),
645 diag::err_variable_object_no_init,
646 VAT->getSizeExpr()->getSourceRange());
647
Steve Naroffcb69fb72007-12-10 22:44:33 +0000648 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
649 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000650 // FIXME: Handle wide strings
651 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
652 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000653
654 if (DeclType->isArrayType())
655 return Diag(Init->getLocStart(),
656 diag::err_array_init_list_required,
657 Init->getSourceRange());
658
Steve Narofff0b23542008-01-10 22:15:12 +0000659 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000660 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000661 unsigned newIndex = 0;
662 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000663}
664
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000665Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000666Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000667 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000668 IdentifierInfo *II = D.getIdentifier();
669
670 // All of these full declarators require an identifier. If it doesn't have
671 // one, the ParsedFreeStandingDeclSpec action should be used.
672 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000673 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000674 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000675 D.getDeclSpec().getSourceRange(), D.getSourceRange());
676 return 0;
677 }
678
Chris Lattnera7549902007-08-26 06:24:45 +0000679 // The scope passed in may not be a decl scope. Zip up the scope tree until
680 // we find one that is.
681 while ((S->getFlags() & Scope::DeclScope) == 0)
682 S = S->getParent();
683
Chris Lattner4b009652007-07-25 00:24:17 +0000684 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000685 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
686 D.getIdentifierLoc(), S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000687 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000688 bool InvalidDecl = false;
689
Chris Lattner82bb4792007-11-14 06:34:38 +0000690 QualType R = GetTypeForDeclarator(D, S);
691 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
692
Chris Lattner4b009652007-07-25 00:24:17 +0000693 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000694 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000695 if (!NewTD) return 0;
696
697 // Handle attributes prior to checking for duplicates in MergeVarDecl
698 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
699 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000700 // Merge the decl with the existing one if appropriate. If the decl is
701 // in an outer scope, it isn't the same thing.
702 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000703 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
704 if (NewTD == 0) return 0;
705 }
706 New = NewTD;
707 if (S->getParent() == 0) {
708 // C99 6.7.7p2: If a typedef name specifies a variably modified type
709 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000710 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
711 // FIXME: Diagnostic needs to be fixed.
712 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000713 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
715 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000716 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000717 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000718 switch (D.getDeclSpec().getStorageClassSpec()) {
719 default: assert(0 && "Unknown storage class!");
720 case DeclSpec::SCS_auto:
721 case DeclSpec::SCS_register:
722 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
723 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000724 InvalidDecl = true;
725 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000726 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
727 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
728 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000729 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000730 }
731
732 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000733 D.getDeclSpec().isInlineSpecified(),
Anders Carlsson3f70c542008-02-15 07:04:12 +0000734 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000735 // Handle attributes.
736
737 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
738 D.getAttributes());
Chris Lattner4b009652007-07-25 00:24:17 +0000739
Steve Narofff8a09432008-01-09 23:34:55 +0000740 // Merge the decl with the existing one if appropriate. Since C functions
741 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000742 if (PrevDecl) {
743 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
744 if (NewFD == 0) return 0;
745 }
746 New = NewFD;
747 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000748 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000749 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
750 D.getIdentifier()->getName());
751 InvalidDecl = true;
752 }
Chris Lattner4b009652007-07-25 00:24:17 +0000753
754 VarDecl *NewVD;
755 VarDecl::StorageClass SC;
756 switch (D.getDeclSpec().getStorageClassSpec()) {
757 default: assert(0 && "Unknown storage class!");
Steve Naroff1cbb2762008-01-25 22:14:40 +0000758 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
759 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
760 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
761 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
762 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
763 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000764 }
765 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000766 // C99 6.9p2: The storage-class specifiers auto and register shall not
767 // appear in the declaration specifiers in an external declaration.
768 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
769 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
770 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000771 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000772 }
Chris Lattner4b009652007-07-25 00:24:17 +0000773 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000774 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000775 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000776 }
Chris Lattner4b009652007-07-25 00:24:17 +0000777 // Handle attributes prior to checking for duplicates in MergeVarDecl
778 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
779 D.getAttributes());
780
Steve Narofff8a09432008-01-09 23:34:55 +0000781 // Merge the decl with the existing one if appropriate. If the decl is
782 // in an outer scope, it isn't the same thing.
783 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000784 NewVD = MergeVarDecl(NewVD, PrevDecl);
785 if (NewVD == 0) return 0;
786 }
Chris Lattner4b009652007-07-25 00:24:17 +0000787 New = NewVD;
788 }
789
790 // If this has an identifier, add it to the scope stack.
791 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000792 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000793 II->setFETokenInfo(New);
794 S->AddDecl(New);
795 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000796 // If any semantic error occurred, mark the decl as invalid.
797 if (D.getInvalidType() || InvalidDecl)
798 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000799
800 return New;
801}
802
Steve Narofff0b23542008-01-10 22:15:12 +0000803bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
804 SourceLocation loc;
805 // FIXME: Remove the isReference check and handle assignment to a reference.
806 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
807 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
808 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
809 return true;
810 }
811 return false;
812}
813
Steve Naroff6a0e2092007-09-12 14:07:44 +0000814void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000815 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000816 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000817 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000818
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000819 // If there is no declaration, there was an error parsing it. Just ignore
820 // the initializer.
821 if (RealDecl == 0) {
822 delete Init;
823 return;
824 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000825
Steve Naroff420d0f52007-09-12 20:13:48 +0000826 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
827 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000828 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
829 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000830 RealDecl->setInvalidDecl();
831 return;
832 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000833 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000834 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000835 QualType DclT = VDecl->getType(), SavT = DclT;
836 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000837 VarDecl::StorageClass SC = BVD->getStorageClass();
838 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000839 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000840 BVD->setInvalidDecl();
841 } else if (!BVD->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000842 if (CheckInitializerTypes(Init, DclT))
843 BVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000844 if (SC == VarDecl::Static) // C99 6.7.8p4.
845 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000846 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000847 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000848 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000849 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000850 if (!FVD->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000851 if (CheckInitializerTypes(Init, DclT))
852 FVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000853
854 // C99 6.7.8p4. All file scoped initializers need to be constant.
855 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000856 }
857 // If the type changed, it means we had an incomplete type that was
858 // completed by the initializer. For example:
859 // int ary[] = { 1, 3, 5 };
860 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000861 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000862 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000863 Init->setType(DclT);
864 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000865
866 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000867 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000868 return;
869}
870
Chris Lattner4b009652007-07-25 00:24:17 +0000871/// The declarators are chained together backwards, reverse the list.
872Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
873 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000874 Decl *GroupDecl = static_cast<Decl*>(group);
875 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000876 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000877
878 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
879 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000880 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000881 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000882 else { // reverse the list.
883 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000884 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000885 Group->setNextDeclarator(NewGroup);
886 NewGroup = Group;
887 Group = Next;
888 }
889 }
890 // Perform semantic analysis that depends on having fully processed both
891 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000892 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000893 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
894 if (!IDecl)
895 continue;
896 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
897 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
898 QualType T = IDecl->getType();
899
900 // C99 6.7.5.2p2: If an identifier is declared to be an object with
901 // static storage duration, it shall not have a variable length array.
902 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +0000903 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000904 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
905 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000906 }
907 }
908 // Block scope. C99 6.7p7: If an identifier for an object is declared with
909 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
910 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
911 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000912 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
913 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000914 IDecl->setInvalidDecl();
915 }
916 }
917 // File scope. C99 6.9.2p2: A declaration of an identifier for and
918 // object that has file scope without an initializer, and without a
919 // storage-class specifier or with the storage-class specifier "static",
920 // constitutes a tentative definition. Note: A tentative definition with
921 // external linkage is valid (C99 6.2.2p5).
Steve Narofffef2f052008-01-18 00:39:39 +0000922 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
923 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +0000924 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +0000925 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
926 // array to be completed. Don't issue a diagnostic.
927 } else if (T->isIncompleteType()) {
928 // C99 6.9.2p3: If the declaration of an identifier for an object is
929 // a tentative definition and has internal linkage (C99 6.2.2p3), the
930 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +0000931 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
932 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000933 IDecl->setInvalidDecl();
934 }
935 }
Chris Lattner4b009652007-07-25 00:24:17 +0000936 }
937 return NewGroup;
938}
Steve Naroff91b03f72007-08-28 03:03:08 +0000939
940// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000941ParmVarDecl *
Nate Begemanef16c252008-02-17 21:02:04 +0000942Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
943 Scope *FnScope) {
Chris Lattner4b009652007-07-25 00:24:17 +0000944 IdentifierInfo *II = PI.Ident;
945 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
946 // Can this happen for params? We already checked that they don't conflict
947 // among each other. Here they can only shadow globals, which is ok.
948 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
949 PI.IdentLoc, FnScope)) {
950
951 }
952
953 // FIXME: Handle storage class (auto, register). No declarator?
954 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000955
956 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
957 // Doing the promotion here has a win and a loss. The win is the type for
958 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
959 // code generator). The loss is the orginal type isn't preserved. For example:
960 //
961 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
962 // int blockvardecl[5];
963 // sizeof(parmvardecl); // size == 4
964 // sizeof(blockvardecl); // size == 20
965 // }
966 //
967 // For expressions, all implicit conversions are captured using the
968 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
969 //
970 // FIXME: If a source translation tool needs to see the original type, then
971 // we need to consider storing both types (in ParmVarDecl)...
972 //
973 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000974 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
975 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000976 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +0000977 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
978 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +0000979 parmDeclType = Context.getPointerType(parmDeclType);
980
981 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Anders Carlsson3f70c542008-02-15 07:04:12 +0000982 VarDecl::None, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +0000983
Steve Naroffcae537d2007-08-28 18:45:29 +0000984 if (PI.InvalidType)
985 New->setInvalidDecl();
986
Chris Lattner4b009652007-07-25 00:24:17 +0000987 // If this has an identifier, add it to the scope stack.
988 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000989 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000990 II->setFETokenInfo(New);
991 FnScope->AddDecl(New);
992 }
Nate Begeman9f3c4bb2008-02-17 21:20:31 +0000993
994 HandleDeclAttributes(New, PI.AttrList, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000995 return New;
996}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000997
Chris Lattnerea148702007-10-09 17:14:05 +0000998Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000999 assert(CurFunctionDecl == 0 && "Function parsing confused");
1000 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1001 "Not a function declarator!");
1002 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1003
1004 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1005 // for a K&R function.
1006 if (!FTI.hasPrototype) {
1007 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1008 if (FTI.ArgInfo[i].TypeInfo == 0) {
1009 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1010 FTI.ArgInfo[i].Ident->getName());
1011 // Implicitly declare the argument as type 'int' for lack of a better
1012 // type.
1013 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1014 }
1015 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001016
Chris Lattner4b009652007-07-25 00:24:17 +00001017 // Since this is a function definition, act as though we have information
1018 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001019 if (FTI.NumArgs)
1020 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001021 } else {
1022 // FIXME: Diagnose arguments without names in C.
1023
1024 }
1025
1026 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001027
1028 // See if this is a redefinition.
1029 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1030 D.getIdentifierLoc(), GlobalScope);
1031 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1032 if (FD->getBody()) {
1033 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1034 D.getIdentifier()->getName());
1035 Diag(FD->getLocation(), diag::err_previous_definition);
1036 }
1037 }
Steve Naroff4a712442008-02-12 01:09:36 +00001038 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001039 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001040 CurFunctionDecl = FD;
1041
1042 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1043 llvm::SmallVector<ParmVarDecl*, 16> Params;
1044
1045 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1046 // no arguments, not a function that takes a single void argument.
1047 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner35fef522008-02-20 20:55:12 +00001048 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +00001049 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001050 // empty arg list, don't push any params.
1051 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +00001052 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +00001053 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +00001054 FnBodyScope));
1055 }
Chris Lattner4b009652007-07-25 00:24:17 +00001056 }
1057
1058 FD->setParams(&Params[0], Params.size());
1059
1060 return FD;
1061}
1062
Steve Naroff99ee4302007-11-11 23:20:51 +00001063Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1064 Decl *dcl = static_cast<Decl *>(D);
1065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1066 FD->setBody((Stmt*)Body);
1067 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001068 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001069 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001070 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001071 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001072 }
Chris Lattner4b009652007-07-25 00:24:17 +00001073 // Verify and clean out per-function state.
1074
1075 // Check goto/label use.
1076 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1077 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1078 // Verify that we have no forward references left. If so, there was a goto
1079 // or address of a label taken, but no definition of it. Label fwd
1080 // definitions are indicated with a null substmt.
1081 if (I->second->getSubStmt() == 0) {
1082 LabelStmt *L = I->second;
1083 // Emit error.
1084 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1085
1086 // At this point, we have gotos that use the bogus label. Stitch it into
1087 // the function body so that they aren't leaked and that the AST is well
1088 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001089 if (Body) {
1090 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1091 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1092 } else {
1093 // The whole function wasn't parsed correctly, just delete this.
1094 delete L;
1095 }
Chris Lattner4b009652007-07-25 00:24:17 +00001096 }
1097 }
1098 LabelMap.clear();
1099
Steve Naroff99ee4302007-11-11 23:20:51 +00001100 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001101}
1102
Chris Lattner4b009652007-07-25 00:24:17 +00001103/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1104/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001105ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1106 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001107 if (getLangOptions().C99) // Extension in C99.
1108 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1109 else // Legal in C90, but warn about it.
1110 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1111
1112 // FIXME: handle stuff like:
1113 // void foo() { extern float X(); }
1114 // void bar() { X(); } <-- implicit decl for X in another scope.
1115
1116 // Set a Declarator for the implicit definition: int foo();
1117 const char *Dummy;
1118 DeclSpec DS;
1119 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1120 Error = Error; // Silence warning.
1121 assert(!Error && "Error setting up implicit decl!");
1122 Declarator D(DS, Declarator::BlockContext);
1123 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1124 D.SetIdentifier(&II, Loc);
1125
1126 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001127 if (Scope *FnS = S->getFnParent())
1128 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001129 while (S->getParent())
1130 S = S->getParent();
1131
Steve Narofff0c31dd2007-09-16 16:16:00 +00001132 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001133}
1134
1135
Chris Lattner82bb4792007-11-14 06:34:38 +00001136TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001137 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001138 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001139 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001140
1141 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001142 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1143 T, LastDeclarator);
1144 if (D.getInvalidType())
1145 NewTD->setInvalidDecl();
1146 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001147}
1148
Steve Naroff0acc9c92007-09-15 18:49:24 +00001149/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001150/// former case, Name will be non-null. In the later case, Name will be null.
1151/// TagType indicates what kind of tag this is. TK indicates whether this is a
1152/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001153Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001154 SourceLocation KWLoc, IdentifierInfo *Name,
1155 SourceLocation NameLoc, AttributeList *Attr) {
1156 // If this is a use of an existing tag, it must have a name.
1157 assert((Name != 0 || TK == TK_Definition) &&
1158 "Nameless record must be a definition!");
1159
1160 Decl::Kind Kind;
1161 switch (TagType) {
1162 default: assert(0 && "Unknown tag type!");
1163 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1164 case DeclSpec::TST_union: Kind = Decl::Union; break;
1165//case DeclSpec::TST_class: Kind = Decl::Class; break;
1166 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1167 }
1168
1169 // If this is a named struct, check to see if there was a previous forward
1170 // declaration or definition.
1171 if (TagDecl *PrevDecl =
1172 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1173 NameLoc, S))) {
1174
1175 // If this is a use of a previous tag, or if the tag is already declared in
1176 // the same scope (so that the definition/declaration completes or
1177 // rementions the tag), reuse the decl.
1178 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1179 // Make sure that this wasn't declared as an enum and now used as a struct
1180 // or something similar.
1181 if (PrevDecl->getKind() != Kind) {
1182 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1183 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1184 }
1185
1186 // If this is a use or a forward declaration, we're good.
1187 if (TK != TK_Definition)
1188 return PrevDecl;
1189
1190 // Diagnose attempts to redefine a tag.
1191 if (PrevDecl->isDefinition()) {
1192 Diag(NameLoc, diag::err_redefinition, Name->getName());
1193 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1194 // If this is a redefinition, recover by making this struct be
1195 // anonymous, which will make any later references get the previous
1196 // definition.
1197 Name = 0;
1198 } else {
1199 // Okay, this is definition of a previously declared or referenced tag.
1200 // Move the location of the decl to be the definition site.
1201 PrevDecl->setLocation(NameLoc);
1202 return PrevDecl;
1203 }
1204 }
1205 // If we get here, this is a definition of a new struct type in a nested
1206 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1207 // type.
1208 }
1209
1210 // If there is an identifier, use the location of the identifier as the
1211 // location of the decl, otherwise use the location of the struct/union
1212 // keyword.
1213 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1214
1215 // Otherwise, if this is the first time we've seen this tag, create the decl.
1216 TagDecl *New;
1217 switch (Kind) {
1218 default: assert(0 && "Unknown tag kind!");
1219 case Decl::Enum:
1220 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1221 // enum X { A, B, C } D; D should chain to X.
1222 New = new EnumDecl(Loc, Name, 0);
1223 // If this is an undefined enum, warn.
1224 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1225 break;
1226 case Decl::Union:
1227 case Decl::Struct:
1228 case Decl::Class:
1229 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1230 // struct X { int A; } D; D should chain to X.
1231 New = new RecordDecl(Kind, Loc, Name, 0);
1232 break;
1233 }
1234
1235 // If this has an identifier, add it to the scope stack.
1236 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001237 // The scope passed in may not be a decl scope. Zip up the scope tree until
1238 // we find one that is.
1239 while ((S->getFlags() & Scope::DeclScope) == 0)
1240 S = S->getParent();
1241
1242 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001243 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001244 Name->setFETokenInfo(New);
1245 S->AddDecl(New);
1246 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001247
Anders Carlsson136cdc32008-02-16 00:29:18 +00001248 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001249 return New;
1250}
1251
Steve Naroff0acc9c92007-09-15 18:49:24 +00001252/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001253/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001254Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001255 SourceLocation DeclStart,
1256 Declarator &D, ExprTy *BitfieldWidth) {
1257 IdentifierInfo *II = D.getIdentifier();
1258 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001259 SourceLocation Loc = DeclStart;
1260 if (II) Loc = D.getIdentifierLoc();
1261
1262 // FIXME: Unnamed fields can be handled in various different ways, for
1263 // example, unnamed unions inject all members into the struct namespace!
1264
1265
1266 if (BitWidth) {
1267 // TODO: Validate.
1268 //printf("WARNING: BITFIELDS IGNORED!\n");
1269
1270 // 6.7.2.1p3
1271 // 6.7.2.1p4
1272
1273 } else {
1274 // Not a bitfield.
1275
1276 // validate II.
1277
1278 }
1279
1280 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001281 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1282 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1285 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001286 if (T->isVariablyModifiedType()) {
1287 // FIXME: This diagnostic needs work
1288 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff5eb879b2007-08-31 17:20:07 +00001289 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001290 }
Chris Lattner4b009652007-07-25 00:24:17 +00001291 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001292 FieldDecl *NewFD;
1293
1294 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001295 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek42730c52008-01-07 19:49:32 +00001296 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1297 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1298 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001299 // FIXME: ivars are currently used to model properties, and
1300 // properties can appear within a protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001301 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1302 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1303 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001304 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001305 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001306
Anders Carlsson136cdc32008-02-16 00:29:18 +00001307 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1308 D.getAttributes());
1309
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001310 if (D.getInvalidType() || InvalidDecl)
1311 NewFD->setInvalidDecl();
1312 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001313}
1314
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001315/// TranslateIvarVisibility - Translate visibility from a token ID to an
1316/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001317static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001318TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001319 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001320 case tok::objc_private: return ObjCIvarDecl::Private;
1321 case tok::objc_public: return ObjCIvarDecl::Public;
1322 case tok::objc_protected: return ObjCIvarDecl::Protected;
1323 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001324 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001325 }
1326}
1327
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001328void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001329 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001330 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001331 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001332 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001333 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1334 assert(EnclosingDecl && "missing record or interface decl");
1335 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1336
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001337 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001338 // Diagnose code like:
1339 // struct S { struct S {} X; };
1340 // We discover this when we complete the outer S. Reject and ignore the
1341 // outer S.
1342 Diag(Record->getLocation(), diag::err_nested_redefinition,
1343 Record->getKindName());
1344 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001345 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001346 return;
1347 }
Chris Lattner4b009652007-07-25 00:24:17 +00001348 // Verify that all the fields are okay.
1349 unsigned NumNamedMembers = 0;
1350 llvm::SmallVector<FieldDecl*, 32> RecFields;
1351 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001352
Chris Lattner4b009652007-07-25 00:24:17 +00001353 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001354
Steve Naroff9bb759f2007-09-14 22:20:54 +00001355 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1356 assert(FD && "missing field decl");
1357
1358 // Remember all fields.
1359 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001360
1361 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001362 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001363
Steve Naroffffeaa552007-09-14 23:09:53 +00001364 // If we have visibility info, make sure the AST is set accordingly.
1365 if (visibility)
Ted Kremenek42730c52008-01-07 19:49:32 +00001366 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001367 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001368
Chris Lattner4b009652007-07-25 00:24:17 +00001369 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001370 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001371 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001372 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001373 FD->setInvalidDecl();
1374 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001375 continue;
1376 }
Chris Lattner4b009652007-07-25 00:24:17 +00001377 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1378 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001379 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001380 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001381 FD->setInvalidDecl();
1382 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001383 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001384 }
Chris Lattner4b009652007-07-25 00:24:17 +00001385 if (i != NumFields-1 || // ... that the last member ...
1386 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001387 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001388 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001389 FD->setInvalidDecl();
1390 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001391 continue;
1392 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001393 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001394 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1395 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001396 FD->setInvalidDecl();
1397 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001398 continue;
1399 }
Chris Lattner4b009652007-07-25 00:24:17 +00001400 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001401 if (Record)
1402 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001403 }
Chris Lattner4b009652007-07-25 00:24:17 +00001404 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1405 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001406 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001407 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1408 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001409 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001410 Record->setHasFlexibleArrayMember(true);
1411 } else {
1412 // If this is a struct/class and this is not the last element, reject
1413 // it. Note that GCC supports variable sized arrays in the middle of
1414 // structures.
1415 if (i != NumFields-1) {
1416 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1417 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001418 FD->setInvalidDecl();
1419 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001420 continue;
1421 }
Chris Lattner4b009652007-07-25 00:24:17 +00001422 // We support flexible arrays at the end of structs in other structs
1423 // as an extension.
1424 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1425 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001426 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001427 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001428 }
1429 }
1430 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001431 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001432 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001433 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1434 FD->getName());
1435 FD->setInvalidDecl();
1436 EnclosingDecl->setInvalidDecl();
1437 continue;
1438 }
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // Keep track of the number of named members.
1440 if (IdentifierInfo *II = FD->getIdentifier()) {
1441 // Detect duplicate member names.
1442 if (!FieldIDs.insert(II)) {
1443 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1444 // Find the previous decl.
1445 SourceLocation PrevLoc;
1446 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1447 assert(i != e && "Didn't find previous def!");
1448 if (RecFields[i]->getIdentifier() == II) {
1449 PrevLoc = RecFields[i]->getLocation();
1450 break;
1451 }
1452 }
1453 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001454 FD->setInvalidDecl();
1455 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001456 continue;
1457 }
1458 ++NumNamedMembers;
1459 }
Chris Lattner4b009652007-07-25 00:24:17 +00001460 }
1461
Chris Lattner4b009652007-07-25 00:24:17 +00001462 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001463 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001464 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001465 Consumer.HandleTagDeclDefinition(Record);
1466 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001467 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1468 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1469 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1470 else if (ObjCImplementationDecl *IMPDecl =
1471 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001472 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1473 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001474 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001475 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001476 }
Chris Lattner4b009652007-07-25 00:24:17 +00001477}
1478
Steve Naroff0acc9c92007-09-15 18:49:24 +00001479Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001480 DeclTy *lastEnumConst,
1481 SourceLocation IdLoc, IdentifierInfo *Id,
1482 SourceLocation EqualLoc, ExprTy *val) {
1483 theEnumDecl = theEnumDecl; // silence unused warning.
1484 EnumConstantDecl *LastEnumConst =
1485 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1486 Expr *Val = static_cast<Expr*>(val);
1487
Chris Lattnera7549902007-08-26 06:24:45 +00001488 // The scope passed in may not be a decl scope. Zip up the scope tree until
1489 // we find one that is.
1490 while ((S->getFlags() & Scope::DeclScope) == 0)
1491 S = S->getParent();
1492
Chris Lattner4b009652007-07-25 00:24:17 +00001493 // Verify that there isn't already something declared with this name in this
1494 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001495 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1496 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001497 if (S->isDeclScope(PrevDecl)) {
1498 if (isa<EnumConstantDecl>(PrevDecl))
1499 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1500 else
1501 Diag(IdLoc, diag::err_redefinition, Id->getName());
1502 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001503 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00001504 return 0;
1505 }
1506 }
1507
1508 llvm::APSInt EnumVal(32);
1509 QualType EltTy;
1510 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001511 // Make sure to promote the operand type to int.
1512 UsualUnaryConversions(Val);
1513
Chris Lattner4b009652007-07-25 00:24:17 +00001514 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1515 SourceLocation ExpLoc;
1516 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1517 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1518 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001519 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001520 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001521 } else {
1522 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001523 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001524 }
1525
1526 if (!Val) {
1527 if (LastEnumConst) {
1528 // Assign the last value + 1.
1529 EnumVal = LastEnumConst->getInitVal();
1530 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001531
1532 // Check for overflow on increment.
1533 if (EnumVal < LastEnumConst->getInitVal())
1534 Diag(IdLoc, diag::warn_enum_value_overflow);
1535
Chris Lattnere7f53a42007-08-27 17:37:24 +00001536 EltTy = LastEnumConst->getType();
1537 } else {
1538 // First value, set to zero.
1539 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001540 EnumVal.zextOrTrunc(
1541 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001542 }
Chris Lattner4b009652007-07-25 00:24:17 +00001543 }
1544
Chris Lattner4b009652007-07-25 00:24:17 +00001545 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1546 LastEnumConst);
1547
1548 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001549 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001550 Id->setFETokenInfo(New);
1551 S->AddDecl(New);
1552 return New;
1553}
1554
Steve Naroff0acc9c92007-09-15 18:49:24 +00001555void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001556 DeclTy **Elements, unsigned NumElements) {
1557 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1558 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1559
Chris Lattner435c3fd2007-08-28 05:10:31 +00001560 // TODO: If the result value doesn't fit in an int, it must be a long or long
1561 // long value. ISO C does not support this, but GCC does as an extension,
1562 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001563 unsigned IntWidth =
1564 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001565
1566
Chris Lattner206754a2007-08-28 06:15:15 +00001567 // Verify that all the values are okay, compute the size of the values, and
1568 // reverse the list.
1569 unsigned NumNegativeBits = 0;
1570 unsigned NumPositiveBits = 0;
1571
1572 // Keep track of whether all elements have type int.
1573 bool AllElementsInt = true;
1574
Chris Lattner4b009652007-07-25 00:24:17 +00001575 EnumConstantDecl *EltList = 0;
1576 for (unsigned i = 0; i != NumElements; ++i) {
1577 EnumConstantDecl *ECD =
1578 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1579 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001580
1581 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001582 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001583 assert(InitVal.getBitWidth() >= IntWidth &&
1584 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00001585 if (InitVal.getBitWidth() > IntWidth) {
1586 llvm::APSInt V(InitVal);
1587 V.trunc(IntWidth);
1588 V.extend(InitVal.getBitWidth());
1589 if (V != InitVal)
1590 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1591 InitVal.toString());
1592 }
Chris Lattner206754a2007-08-28 06:15:15 +00001593
1594 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001595 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001596 NumPositiveBits = std::max(NumPositiveBits,
1597 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001598 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001599 NumNegativeBits = std::max(NumNegativeBits,
1600 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001601
Chris Lattner206754a2007-08-28 06:15:15 +00001602 // Keep track of whether every enum element has type int (very commmon).
1603 if (AllElementsInt)
1604 AllElementsInt = ECD->getType() == Context.IntTy;
1605
Chris Lattner4b009652007-07-25 00:24:17 +00001606 ECD->setNextDeclarator(EltList);
1607 EltList = ECD;
1608 }
1609
Chris Lattner206754a2007-08-28 06:15:15 +00001610 // Figure out the type that should be used for this enum.
1611 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1612 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001613 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001614
1615 if (NumNegativeBits) {
1616 // If there is a negative value, figure out the smallest integer type (of
1617 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001618 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001619 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001620 BestWidth = IntWidth;
1621 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001622 BestWidth =
1623 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1624
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001625 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001626 BestType = Context.LongTy;
1627 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001628 BestWidth = Context.Target.getLongLongWidth(
1629 Context.getFullLoc(Enum->getLocation()));
1630
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001631 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001632 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1633 BestType = Context.LongLongTy;
1634 }
1635 }
1636 } else {
1637 // If there is no negative value, figure out which of uint, ulong, ulonglong
1638 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001639 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001640 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001641 BestWidth = IntWidth;
1642 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001643 (BestWidth = Context.Target.getLongWidth(
1644 Context.getFullLoc(Enum->getLocation()))))
1645
Chris Lattner206754a2007-08-28 06:15:15 +00001646 BestType = Context.UnsignedLongTy;
1647 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001648 BestWidth =
1649 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1650
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001651 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001652 "How could an initializer get larger than ULL?");
1653 BestType = Context.UnsignedLongLongTy;
1654 }
1655 }
1656
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001657 // Loop over all of the enumerator constants, changing their types to match
1658 // the type of the enum if needed.
1659 for (unsigned i = 0; i != NumElements; ++i) {
1660 EnumConstantDecl *ECD =
1661 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1662 if (!ECD) continue; // Already issued a diagnostic.
1663
1664 // Standard C says the enumerators have int type, but we allow, as an
1665 // extension, the enumerators to be larger than int size. If each
1666 // enumerator value fits in an int, type it as an int, otherwise type it the
1667 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1668 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001669 if (ECD->getType() == Context.IntTy) {
1670 // Make sure the init value is signed.
1671 llvm::APSInt IV = ECD->getInitVal();
1672 IV.setIsSigned(true);
1673 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001674 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001675 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001676
1677 // Determine whether the value fits into an int.
1678 llvm::APSInt InitVal = ECD->getInitVal();
1679 bool FitsInInt;
1680 if (InitVal.isUnsigned() || !InitVal.isNegative())
1681 FitsInInt = InitVal.getActiveBits() < IntWidth;
1682 else
1683 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1684
1685 // If it fits into an integer type, force it. Otherwise force it to match
1686 // the enum decl type.
1687 QualType NewTy;
1688 unsigned NewWidth;
1689 bool NewSign;
1690 if (FitsInInt) {
1691 NewTy = Context.IntTy;
1692 NewWidth = IntWidth;
1693 NewSign = true;
1694 } else if (ECD->getType() == BestType) {
1695 // Already the right type!
1696 continue;
1697 } else {
1698 NewTy = BestType;
1699 NewWidth = BestWidth;
1700 NewSign = BestType->isSignedIntegerType();
1701 }
1702
1703 // Adjust the APSInt value.
1704 InitVal.extOrTrunc(NewWidth);
1705 InitVal.setIsSigned(NewSign);
1706 ECD->setInitVal(InitVal);
1707
1708 // Adjust the Expr initializer and type.
1709 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1710 ECD->setType(NewTy);
1711 }
Chris Lattner206754a2007-08-28 06:15:15 +00001712
Chris Lattner90a018d2007-08-28 18:24:31 +00001713 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001714 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001715}
1716
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001717Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1718 ExprTy *expr) {
1719 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1720
1721 return new FileScopeAsmDecl(Loc, AsmString);
1722}
1723
Chris Lattner806a5f52008-01-12 07:05:38 +00001724Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00001725 SourceLocation LBrace,
1726 SourceLocation RBrace,
1727 const char *Lang,
1728 unsigned StrSize,
1729 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00001730 LinkageSpecDecl::LanguageIDs Language;
1731 Decl *dcl = static_cast<Decl *>(D);
1732 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1733 Language = LinkageSpecDecl::lang_c;
1734 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1735 Language = LinkageSpecDecl::lang_cxx;
1736 else {
1737 Diag(Loc, diag::err_bad_language);
1738 return 0;
1739 }
1740
1741 // FIXME: Add all the various semantics of linkage specifications
1742 return new LinkageSpecDecl(Loc, Language, dcl);
1743}
1744
Chris Lattner49d15cb2008-02-21 00:48:22 +00001745void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001746
Chris Lattner49d15cb2008-02-21 00:48:22 +00001747 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00001748 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00001749 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00001750 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001751 if (!newType.isNull()) // install the new vector type into the decl
1752 vDecl->setType(newType);
1753 }
1754 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1755 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001756 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001757 if (!newType.isNull()) // install the new vector type into the decl
1758 tDecl->setUnderlyingType(newType);
1759 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001760 break;
1761 case AttributeList::AT_ocu_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00001762 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner49d15cb2008-02-21 00:48:22 +00001763 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00001764 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00001765 Diag(Attr->getLoc(),
Chris Lattner4b009652007-07-25 00:24:17 +00001766 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001767 break;
1768 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001769 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1770 QualType newType = HandleAddressSpaceTypeAttribute(
1771 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001772 Attr);
1773 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001774 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1775 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001776 Attr);
1777 // install the new addr spaced type into the decl
1778 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001779 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001780 break;
1781 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001782 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001783 break;
1784 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001785 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001786 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00001787 case AttributeList::AT_annotate:
1788 HandleAnnotateAttribute(New, Attr);
1789 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00001790 case AttributeList::AT_noreturn:
1791 HandleNoReturnAttribute(New, Attr);
1792 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00001793 default:
1794 // FIXME: add other attributes...
1795 break;
1796 }
Chris Lattner4b009652007-07-25 00:24:17 +00001797}
1798
1799void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1800 AttributeList *declarator_postfix) {
1801 while (declspec_prefix) {
1802 HandleDeclAttribute(New, declspec_prefix);
1803 declspec_prefix = declspec_prefix->getNext();
1804 }
1805 while (declarator_postfix) {
1806 HandleDeclAttribute(New, declarator_postfix);
1807 declarator_postfix = declarator_postfix->getNext();
1808 }
1809}
1810
Steve Naroff82113e32007-07-29 16:33:31 +00001811void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1812 AttributeList *rawAttr) {
1813 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001814 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001815 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00001816 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00001817 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001818 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001819 }
1820 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1821 llvm::APSInt vecSize(32);
1822 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00001823 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00001824 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001825 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001826 }
1827 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1828 // in conjunction with complex types (pointers, arrays, functions, etc.).
1829 Type *canonType = curType.getCanonicalType().getTypePtr();
1830 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00001831 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00001832 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001833 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001834 }
1835 // unlike gcc's vector_size attribute, the size is specified as the
1836 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001837 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001838
1839 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00001840 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00001841 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001842 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001843 }
Steve Naroff82113e32007-07-29 16:33:31 +00001844 // Instantiate/Install the vector type, the number of elements is > 0.
1845 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1846 // Remember this typedef decl, we will need it later for diagnostics.
1847 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001848}
1849
1850QualType Sema::HandleVectorTypeAttribute(QualType curType,
1851 AttributeList *rawAttr) {
1852 // check the attribute arugments.
1853 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00001854 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00001855 std::string("1"));
1856 return QualType();
1857 }
1858 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1859 llvm::APSInt vecSize(32);
1860 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00001861 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00001862 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001863 return QualType();
1864 }
1865 // navigate to the base type - we need to provide for vector pointers,
1866 // vector arrays, and functions returning vectors.
1867 Type *canonType = curType.getCanonicalType().getTypePtr();
1868
1869 if (canonType->isPointerType() || canonType->isArrayType() ||
1870 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001871 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001872 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1873 do {
1874 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1875 canonType = PT->getPointeeType().getTypePtr();
1876 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1877 canonType = AT->getElementType().getTypePtr();
1878 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1879 canonType = FT->getResultType().getTypePtr();
1880 } while (canonType->isPointerType() || canonType->isArrayType() ||
1881 canonType->isFunctionType());
1882 */
1883 }
1884 // the base type must be integer or float.
1885 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00001886 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00001887 curType.getCanonicalType().getAsString());
1888 return QualType();
1889 }
Chris Lattner3496d522007-09-04 02:45:27 +00001890 unsigned typeSize = static_cast<unsigned>(
Chris Lattner9384f502008-02-20 23:25:22 +00001891 Context.getTypeSize(curType, rawAttr->getLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001892 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001893 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001894
1895 // the vector size needs to be an integral multiple of the type size.
1896 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00001897 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00001898 sizeExpr->getSourceRange());
1899 return QualType();
1900 }
1901 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00001902 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00001903 sizeExpr->getSourceRange());
1904 return QualType();
1905 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00001906 // Instantiate the vector type, the number of elements is > 0, and not
1907 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00001908 return Context.getVectorType(curType, vectorSize/typeSize);
1909}
1910
Chris Lattner9384f502008-02-20 23:25:22 +00001911void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00001912 // check the attribute arguments.
1913 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00001914 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00001915 std::string("0"));
1916 return;
1917 }
1918
1919 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1920 TD->addAttr(new PackedAttr);
1921 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1922 // If the alignment is less than or equal to 8 bits, the packed attribute
1923 // has no effect.
1924 if (Context.getTypeAlign(FD->getType(), SourceLocation()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00001925 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00001926 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00001927 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00001928 else
Anders Carlssonca133d92008-02-16 00:39:40 +00001929 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00001930 } else
Chris Lattner9384f502008-02-20 23:25:22 +00001931 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
1932 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00001933}
Nate Begeman754d3fc2008-02-21 19:30:49 +00001934
Ted Kremenek13bfae62008-02-27 20:43:06 +00001935void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
1936 // check the attribute arguments.
1937 if (rawAttr->getNumArgs() != 0) {
1938 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1939 std::string("0"));
1940 return;
1941 }
1942
1943 d->addAttr(new NoReturnAttr());
1944}
1945
Nate Begeman754d3fc2008-02-21 19:30:49 +00001946void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
1947 // check the attribute arguments.
1948 if (rawAttr->getNumArgs() != 1) {
1949 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1950 std::string("1"));
1951 return;
1952 }
1953 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
1954 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00001955
Nate Begeman754d3fc2008-02-21 19:30:49 +00001956 // Make sure that there is a string literal as the annotation's single
1957 // argument.
1958 if (!SE) {
1959 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
1960 return;
1961 }
1962 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
1963 SE->getByteLength())));
1964}
1965
Anders Carlssonc8b44122007-12-19 07:19:40 +00001966void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1967{
1968 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00001969 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00001970 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00001971 std::string("1"));
1972 return;
1973 }
Eli Friedman74820702008-01-30 17:38:42 +00001974
Anders Carlsson7dce0292008-02-16 19:51:27 +00001975 unsigned Align = 0;
1976
1977 if (rawAttr->getNumArgs() == 0) {
1978 // FIXME: This should be the target specific maximum alignment.
1979 // (For now we just use 128 bits which is the maximum on X86.
1980 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00001981 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00001982 } else {
1983 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1984 llvm::APSInt alignment(32);
1985 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00001986 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00001987 "aligned", alignmentExpr->getSourceRange());
1988 return;
1989 }
1990
1991 Align = alignment.getZExtValue() * 8;
1992 }
Eli Friedman74820702008-01-30 17:38:42 +00001993
Anders Carlsson7dce0292008-02-16 19:51:27 +00001994 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00001995}