blob: 6854aacb9e4d84ce405e4e4ab4017afc9cfbfc82 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-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 Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-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 Kremeneka526c5c2008-01-07 19:49:32 +000042 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000044 if (ObjCCompatibleAliasDecl *ADecl =
45 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000046 return ADecl->getClassInterface();
Steve Naroff3536b442007-09-06 21:24:23 +000047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Steve Naroffb216c882007-10-09 22:01:59 +000050void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000051 if (S->decl_empty()) return;
52 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
55 I != E; ++I) {
Steve Naroffc752d042007-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +000073 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +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 Jahanian4cabdfc2007-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 Jahanian3fe44e42007-10-12 19:53:08 +000096/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahanian4cabdfc2007-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 Kremeneka526c5c2008-01-07 19:49:32 +0000107 if (ObjCCompatibleAliasDecl *ADecl =
108 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000109 return ADecl->getClassInterface();
110 return IDecl;
111}
112
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000113/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000114/// return 0 if one not found.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000115ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000116 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000117 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000118}
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +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 Kremenek9c728dc2007-12-12 22:39:36 +0000144 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Reid Spencer5f016e22007-07-11 17:01:13 +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 Carlsson7c50aca2007-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 Naroff733002f2007-10-18 22:17:45 +0000162 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164}
165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000168ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 Builtin::ID BID = (Builtin::ID)bid;
171
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000172 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000173 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000174 BID == Builtin::BI__builtin_va_end)
175 InitBuiltinVaListType();
176
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000177 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000179 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180
181 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000182 if (Scope *FnS = S->getFnParent())
183 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffc752d042007-09-13 18:10:37 +0000189 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8e74c932007-09-13 21:41:19 +0000205TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroff8ee529b2007-10-31 18:42:27 +0000215 // Allow multiple definitions for ObjC built-in typedefs.
216 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000218 return Old;
Steve Naroff4c49a6c2008-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 Naroffd62701b2008-02-07 03:50:06 +0000232 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
233 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
234 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000235 return New;
Steve Naroff8ee529b2007-10-31 18:42:27 +0000236
Reid Spencer5f016e22007-07-11 17:01:13 +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
Chris Lattnerddee4232008-03-03 03:28:21 +0000245/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
246static bool DeclHasAttr(const Decl *decl, const Attr *target) {
247 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
248 if (attr->getKind() == target->getKind())
249 return true;
250
251 return false;
252}
253
254/// MergeAttributes - append attributes from the Old decl to the New one.
255static void MergeAttributes(Decl *New, Decl *Old) {
256 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
257
258// FIXME: fix this code to cleanup the Old attrs correctly
259 while (attr) {
260 tmp = attr;
261 attr = attr->getNext();
262
263 if (!DeclHasAttr(New, tmp)) {
264 New->addAttr(tmp);
265 } else {
266 tmp->setNext(0);
267 delete(tmp);
268 }
269 }
270}
271
Reid Spencer5f016e22007-07-11 17:01:13 +0000272/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
273/// and scope as a previous declaration 'Old'. Figure out how to resolve this
274/// situation, merging decls or emitting diagnostics as appropriate.
275///
Steve Naroff8e74c932007-09-13 21:41:19 +0000276FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000277 // Verify the old decl was also a function.
278 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
279 if (!Old) {
280 Diag(New->getLocation(), diag::err_redefinition_different_kind,
281 New->getName());
282 Diag(OldD->getLocation(), diag::err_previous_definition);
283 return New;
284 }
Chris Lattner7e669b22008-02-29 16:48:43 +0000285
Chris Lattnerddee4232008-03-03 03:28:21 +0000286 MergeAttributes(New, Old);
287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288
Chris Lattner55196442007-11-20 19:04:50 +0000289 QualType OldQType = Old->getCanonicalType();
290 QualType NewQType = New->getCanonicalType();
291
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000292 // Function types need to be compatible, not identical. This handles
293 // duplicate function decls like "void f(int); void f(enum X);" properly.
294 if (Context.functionTypesAreCompatible(OldQType, NewQType))
295 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000296
Steve Naroff837618c2008-01-16 15:01:34 +0000297 // A function that has already been declared has been redeclared or defined
298 // with a different type- show appropriate diagnostic
299 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
300 diag::err_previous_declaration;
301
Reid Spencer5f016e22007-07-11 17:01:13 +0000302 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
303 // TODO: This is totally simplistic. It should handle merging functions
304 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000305 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
306 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 return New;
308}
309
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000310/// equivalentArrayTypes - Used to determine whether two array types are
311/// equivalent.
312/// We need to check this explicitly as an incomplete array definition is
313/// considered a VariableArrayType, so will not match a complete array
314/// definition that would be otherwise equivalent.
315static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
316 const ArrayType *NewAT = NewQType->getAsArrayType();
317 const ArrayType *OldAT = OldQType->getAsArrayType();
318
319 if (!NewAT || !OldAT)
320 return false;
321
322 // If either (or both) array types in incomplete we need to strip off the
323 // outer VariableArrayType. Once the outer VAT is removed the remaining
324 // types must be identical if the array types are to be considered
325 // equivalent.
326 // eg. int[][1] and int[1][1] become
327 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
328 // removing the outermost VAT gives
329 // CAT(1, int) and CAT(1, int)
330 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000331 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000332 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
333 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000334 NewQType = NewAT->getElementType().getCanonicalType();
335 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000336 }
337
338 return NewQType == OldQType;
339}
340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341/// MergeVarDecl - We just parsed a variable 'New' which has the same name
342/// and scope as a previous declaration 'Old'. Figure out how to resolve this
343/// situation, merging decls or emitting diagnostics as appropriate.
344///
345/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
346/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
347///
Steve Naroff8e74c932007-09-13 21:41:19 +0000348VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000349 // Verify the old decl was also a variable.
350 VarDecl *Old = dyn_cast<VarDecl>(OldD);
351 if (!Old) {
352 Diag(New->getLocation(), diag::err_redefinition_different_kind,
353 New->getName());
354 Diag(OldD->getLocation(), diag::err_previous_definition);
355 return New;
356 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000357
358 MergeAttributes(New, Old);
359
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000361 if (Old->getCanonicalType() != New->getCanonicalType() &&
362 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 Diag(New->getLocation(), diag::err_redefinition, New->getName());
364 Diag(Old->getLocation(), diag::err_previous_definition);
365 return New;
366 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000367 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
368 if (New->getStorageClass() == VarDecl::Static &&
369 (Old->getStorageClass() == VarDecl::None ||
370 Old->getStorageClass() == VarDecl::Extern)) {
371 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
372 Diag(Old->getLocation(), diag::err_previous_definition);
373 return New;
374 }
375 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
376 if (New->getStorageClass() != VarDecl::Static &&
377 Old->getStorageClass() == VarDecl::Static) {
378 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
379 Diag(Old->getLocation(), diag::err_previous_definition);
380 return New;
381 }
382 // We've verified the types match, now handle "tentative" definitions.
383 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
384 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
385
386 if (OldFSDecl && NewFSDecl) {
387 // Handle C "tentative" external object definitions (C99 6.9.2).
388 bool OldIsTentative = false;
389 bool NewIsTentative = false;
390
391 if (!OldFSDecl->getInit() &&
392 (OldFSDecl->getStorageClass() == VarDecl::None ||
393 OldFSDecl->getStorageClass() == VarDecl::Static))
394 OldIsTentative = true;
395
396 // FIXME: this check doesn't work (since the initializer hasn't been
397 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
398 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
399 // thrown out the old decl.
400 if (!NewFSDecl->getInit() &&
401 (NewFSDecl->getStorageClass() == VarDecl::None ||
402 NewFSDecl->getStorageClass() == VarDecl::Static))
403 ; // change to NewIsTentative = true; once the code is moved.
404
405 if (NewIsTentative || OldIsTentative)
406 return New;
407 }
408 if (Old->getStorageClass() != VarDecl::Extern &&
409 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 Diag(New->getLocation(), diag::err_redefinition, New->getName());
411 Diag(Old->getLocation(), diag::err_previous_definition);
412 }
413 return New;
414}
415
416/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
417/// no declarator (e.g. "struct foo;") is parsed.
418Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
419 // TODO: emit error on 'int;' or 'const enum foo;'.
420 // TODO: emit error on 'typedef int;'
421 // if (!DS.isMissingDeclaratorOk()) Diag(...);
422
Steve Naroff92199282007-11-17 21:37:36 +0000423 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
Steve Naroffd0091aa2008-01-10 22:15:12 +0000426bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000427 // Get the type before calling CheckSingleAssignmentConstraints(), since
428 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000429 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000430
Chris Lattner5cf216b2008-01-04 18:04:52 +0000431 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
432 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
433 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000434}
435
Steve Naroff9e8925e2007-09-04 14:36:54 +0000436bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000437 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000438 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000439 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000440 return true; // types weren't compatible.
441
Steve Naroff9e8925e2007-09-04 14:36:54 +0000442 if (savExpr != expr) // The type was promoted, update initializer list.
443 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000444 return false;
445}
446
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000447bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000448 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000449 // C99 6.7.8p14. We have an array of character type with unknown size
450 // being initialized to a string literal.
451 llvm::APSInt ConstVal(32);
452 ConstVal = strLiteral->getByteLength() + 1;
453 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000454 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000455 ArrayType::Normal, 0);
456 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
457 // C99 6.7.8p14. We have an array of character type with known size.
458 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
459 Diag(strLiteral->getSourceRange().getBegin(),
460 diag::warn_initializer_string_for_char_array_too_long,
461 strLiteral->getSourceRange());
462 } else {
463 assert(0 && "HandleStringLiteralInit(): Invalid array type");
464 }
465 // Set type from "char *" to "constant array of char".
466 strLiteral->setType(DeclT);
467 // For now, we always return false (meaning success).
468 return false;
469}
470
471StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000472 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000473 if (AT && AT->getElementType()->isCharType()) {
474 return dyn_cast<StringLiteral>(Init);
475 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000476 return 0;
477}
478
Steve Naroffa9960332008-01-25 00:51:06 +0000479// CheckInitializerListTypes - Checks the types of elements of an initializer
480// list. This function is recursive: it calls itself to initialize subelements
481// of aggregate types. Note that the topLevel parameter essentially refers to
482// whether this expression "owns" the initializer list passed in, or if this
483// initialization is taking elements out of a parent initializer. Each
484// call to this function adds zero or more to startIndex, reports any errors,
485// and returns true if it found any inconsistent types.
486bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
487 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000488 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000489
490 if (DeclType->isScalarType()) {
491 // The simplest case: initializing a single scalar
492 if (topLevel) {
493 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
494 IList->getSourceRange());
495 }
496 if (startIndex < IList->getNumInits()) {
497 Expr* expr = IList->getInit(startIndex);
498 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
499 // FIXME: Should an error be reported here instead?
500 unsigned newIndex = 0;
501 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
502 } else {
503 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
504 }
505 ++startIndex;
506 }
507 // FIXME: Should an error be reported for empty initializer list + scalar?
508 } else if (DeclType->isVectorType()) {
509 if (startIndex < IList->getNumInits()) {
510 const VectorType *VT = DeclType->getAsVectorType();
511 int maxElements = VT->getNumElements();
512 QualType elementType = VT->getElementType();
513
514 for (int i = 0; i < maxElements; ++i) {
515 // Don't attempt to go past the end of the init list
516 if (startIndex >= IList->getNumInits())
517 break;
518 Expr* expr = IList->getInit(startIndex);
519 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
520 unsigned newIndex = 0;
521 hadError |= CheckInitializerListTypes(SubInitList, elementType,
522 true, newIndex);
523 ++startIndex;
524 } else {
525 hadError |= CheckInitializerListTypes(IList, elementType,
526 false, startIndex);
527 }
528 }
529 }
530 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
531 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000532 if (startIndex < IList->getNumInits() && !topLevel &&
533 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
534 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000535 // We found a compatible struct; per the standard, this initializes the
536 // struct. (The C standard technically says that this only applies for
537 // initializers for declarations with automatic scope; however, this
538 // construct is unambiguous anyway because a struct cannot contain
539 // a type compatible with itself. We'll output an error when we check
540 // if the initializer is constant.)
541 // FIXME: Is a call to CheckSingleInitializer required here?
542 ++startIndex;
543 } else {
544 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000545
Steve Naroff406db932008-02-11 21:52:37 +0000546 // If the record is invalid, some of it's members are invalid. To avoid
547 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000548 if (structDecl->isInvalidDecl())
549 return true;
550
Steve Naroffa9960332008-01-25 00:51:06 +0000551 // If structDecl is a forward declaration, this loop won't do anything;
552 // That's okay, because an error should get printed out elsewhere. It
553 // might be worthwhile to skip over the rest of the initializer, though.
554 int numMembers = structDecl->getNumMembers() -
555 structDecl->hasFlexibleArrayMember();
556 for (int i = 0; i < numMembers; i++) {
557 // Don't attempt to go past the end of the init list
558 if (startIndex >= IList->getNumInits())
559 break;
560 FieldDecl * curField = structDecl->getMember(i);
561 if (!curField->getIdentifier()) {
562 // Don't initialize unnamed fields, e.g. "int : 20;"
563 continue;
564 }
565 QualType fieldType = curField->getType();
566 Expr* expr = IList->getInit(startIndex);
567 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
568 unsigned newStart = 0;
569 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
570 true, newStart);
571 ++startIndex;
572 } else {
573 hadError |= CheckInitializerListTypes(IList, fieldType,
574 false, startIndex);
575 }
576 if (DeclType->isUnionType())
577 break;
578 }
579 // FIXME: Implement flexible array initialization GCC extension (it's a
580 // really messy extension to implement, unfortunately...the necessary
581 // information isn't actually even here!)
582 }
583 } else if (DeclType->isArrayType()) {
584 // Check for the special-case of initializing an array with a string.
585 if (startIndex < IList->getNumInits()) {
586 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
587 DeclType)) {
588 CheckStringLiteralInit(lit, DeclType);
589 ++startIndex;
590 if (topLevel && startIndex < IList->getNumInits()) {
591 // We have leftover initializers; warn
592 Diag(IList->getInit(startIndex)->getLocStart(),
593 diag::err_excess_initializers_in_char_array_initializer,
594 IList->getInit(startIndex)->getSourceRange());
595 }
596 return false;
597 }
598 }
599 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000600 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000601 // FIXME: use a proper constant
602 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000603 } else if (const VariableArrayType *VAT =
604 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000605 // Check for VLAs; in standard C it would be possible to check this
606 // earlier, but I don't know where clang accepts VLAs (gcc accepts
607 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000608 Diag(VAT->getSizeExpr()->getLocStart(),
609 diag::err_variable_object_no_init,
610 VAT->getSizeExpr()->getSourceRange());
611 hadError = true;
612 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000613 } else {
614 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
615 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
616 }
617 QualType elementType = DeclType->getAsArrayType()->getElementType();
618 int numElements = 0;
619 for (int i = 0; i < maxElements; ++i, ++numElements) {
620 // Don't attempt to go past the end of the init list
621 if (startIndex >= IList->getNumInits())
622 break;
623 Expr* expr = IList->getInit(startIndex);
624 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
625 unsigned newIndex = 0;
626 hadError |= CheckInitializerListTypes(SubInitList, elementType,
627 true, newIndex);
628 ++startIndex;
629 } else {
630 hadError |= CheckInitializerListTypes(IList, elementType,
631 false, startIndex);
632 }
633 }
Eli Friedman9db13972008-02-15 12:53:51 +0000634 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000635 // If this is an incomplete array type, the actual type needs to
636 // be calculated here
637 if (numElements == 0) {
638 // Sizing an array implicitly to zero is not allowed
639 // (It could in theory be allowed, but it doesn't really matter.)
640 Diag(IList->getLocStart(),
641 diag::err_at_least_one_initializer_needed_to_size_array);
642 hadError = true;
643 } else {
644 llvm::APSInt ConstVal(32);
645 ConstVal = numElements;
646 DeclType = Context.getConstantArrayType(elementType, ConstVal,
647 ArrayType::Normal, 0);
648 }
649 }
650 } else {
651 assert(0 && "Aggregate that isn't a function or array?!");
652 }
653 } else {
654 // In C, all types are either scalars or aggregates, but
655 // additional handling is needed here for C++ (and possibly others?).
656 assert(0 && "Unsupported initializer type");
657 }
658
659 // If this init list is a base list, we set the type; an initializer doesn't
660 // fundamentally have a type, but this makes the ASTs a bit easier to read
661 if (topLevel)
662 IList->setType(DeclType);
663
664 if (topLevel && startIndex < IList->getNumInits()) {
665 // We have leftover initializers; warn
666 Diag(IList->getInit(startIndex)->getLocStart(),
667 diag::warn_excess_initializers,
668 IList->getInit(startIndex)->getSourceRange());
669 }
670 return hadError;
671}
672
673bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000674 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
675 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000676 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000677 return Diag(VAT->getSizeExpr()->getLocStart(),
678 diag::err_variable_object_no_init,
679 VAT->getSizeExpr()->getSourceRange());
680
Steve Naroff2fdc3742007-12-10 22:44:33 +0000681 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
682 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000683 // FIXME: Handle wide strings
684 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
685 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000686
687 if (DeclType->isArrayType())
688 return Diag(Init->getLocStart(),
689 diag::err_array_init_list_required,
690 Init->getSourceRange());
691
Steve Naroffd0091aa2008-01-10 22:15:12 +0000692 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000693 }
Steve Naroffa9960332008-01-25 00:51:06 +0000694 unsigned newIndex = 0;
695 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000696}
697
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000698Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000699Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000700 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 IdentifierInfo *II = D.getIdentifier();
702
Chris Lattnere80a59c2007-07-25 00:24:17 +0000703 // All of these full declarators require an identifier. If it doesn't have
704 // one, the ParsedFreeStandingDeclSpec action should be used.
705 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000706 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000707 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000708 D.getDeclSpec().getSourceRange(), D.getSourceRange());
709 return 0;
710 }
711
Chris Lattner31e05722007-08-26 06:24:45 +0000712 // The scope passed in may not be a decl scope. Zip up the scope tree until
713 // we find one that is.
714 while ((S->getFlags() & Scope::DeclScope) == 0)
715 S = S->getParent();
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000718 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
719 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000720 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000721 bool InvalidDecl = false;
722
Chris Lattner41af0932007-11-14 06:34:38 +0000723 QualType R = GetTypeForDeclarator(D, S);
724 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000727 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 if (!NewTD) return 0;
729
730 // Handle attributes prior to checking for duplicates in MergeVarDecl
731 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
732 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000733 // Merge the decl with the existing one if appropriate. If the decl is
734 // in an outer scope, it isn't the same thing.
735 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
737 if (NewTD == 0) return 0;
738 }
739 New = NewTD;
740 if (S->getParent() == 0) {
741 // C99 6.7.7p2: If a typedef name specifies a variably modified type
742 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000743 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
744 // FIXME: Diagnostic needs to be fixed.
745 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000746 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 }
748 }
Chris Lattner41af0932007-11-14 06:34:38 +0000749 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000750 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 switch (D.getDeclSpec().getStorageClassSpec()) {
752 default: assert(0 && "Unknown storage class!");
753 case DeclSpec::SCS_auto:
754 case DeclSpec::SCS_register:
755 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
756 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000757 InvalidDecl = true;
758 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
760 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
761 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000762 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 }
764
765 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000766 D.getDeclSpec().isInlineSpecified(),
Anders Carlssonf78915f2008-02-15 07:04:12 +0000767 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000768 // Handle attributes.
769
770 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
771 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +0000772
Steve Naroffffce4d52008-01-09 23:34:55 +0000773 // Merge the decl with the existing one if appropriate. Since C functions
774 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 if (PrevDecl) {
776 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
777 if (NewFD == 0) return 0;
778 }
779 New = NewFD;
780 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000781 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000782 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
783 D.getIdentifier()->getName());
784 InvalidDecl = true;
785 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000786
787 VarDecl *NewVD;
788 VarDecl::StorageClass SC;
789 switch (D.getDeclSpec().getStorageClassSpec()) {
790 default: assert(0 && "Unknown storage class!");
Steve Naroffd6326c62008-01-25 22:14:40 +0000791 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
792 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
793 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
794 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
795 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
796 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 }
798 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // C99 6.9p2: The storage-class specifiers auto and register shall not
800 // appear in the declaration specifiers in an external declaration.
801 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
802 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
803 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000804 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000807 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000809 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 // Handle attributes prior to checking for duplicates in MergeVarDecl
811 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
812 D.getAttributes());
813
Steve Naroffffce4d52008-01-09 23:34:55 +0000814 // Merge the decl with the existing one if appropriate. If the decl is
815 // in an outer scope, it isn't the same thing.
816 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000817 NewVD = MergeVarDecl(NewVD, PrevDecl);
818 if (NewVD == 0) return 0;
819 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 New = NewVD;
821 }
822
823 // If this has an identifier, add it to the scope stack.
824 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000825 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000826 II->setFETokenInfo(New);
827 S->AddDecl(New);
828 }
Steve Naroff5912a352007-08-28 20:14:24 +0000829 // If any semantic error occurred, mark the decl as invalid.
830 if (D.getInvalidType() || InvalidDecl)
831 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000832
833 return New;
834}
835
Steve Naroffd0091aa2008-01-10 22:15:12 +0000836bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
837 SourceLocation loc;
838 // FIXME: Remove the isReference check and handle assignment to a reference.
839 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
840 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
841 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
842 return true;
843 }
844 return false;
845}
846
Steve Naroffbb204692007-09-12 14:07:44 +0000847void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000848 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000849 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000850 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000851
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000852 // If there is no declaration, there was an error parsing it. Just ignore
853 // the initializer.
854 if (RealDecl == 0) {
855 delete Init;
856 return;
857 }
Steve Naroffbb204692007-09-12 14:07:44 +0000858
Steve Naroff410e3e22007-09-12 20:13:48 +0000859 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
860 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000861 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
862 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000863 RealDecl->setInvalidDecl();
864 return;
865 }
Steve Naroffbb204692007-09-12 14:07:44 +0000866 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000867 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000868 QualType DclT = VDecl->getType(), SavT = DclT;
869 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000870 VarDecl::StorageClass SC = BVD->getStorageClass();
871 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000872 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000873 BVD->setInvalidDecl();
874 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000875 if (CheckInitializerTypes(Init, DclT))
876 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000877 if (SC == VarDecl::Static) // C99 6.7.8p4.
878 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000879 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000880 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000881 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000882 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000883 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000884 if (CheckInitializerTypes(Init, DclT))
885 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000886
887 // C99 6.7.8p4. All file scoped initializers need to be constant.
888 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000889 }
890 // If the type changed, it means we had an incomplete type that was
891 // completed by the initializer. For example:
892 // int ary[] = { 1, 3, 5 };
893 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000894 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000895 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000896 Init->setType(DclT);
897 }
Steve Naroffbb204692007-09-12 14:07:44 +0000898
899 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000900 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000901 return;
902}
903
Reid Spencer5f016e22007-07-11 17:01:13 +0000904/// The declarators are chained together backwards, reverse the list.
905Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
906 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000907 Decl *GroupDecl = static_cast<Decl*>(group);
908 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000909 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000910
911 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
912 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000913 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000915 else { // reverse the list.
916 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000917 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000918 Group->setNextDeclarator(NewGroup);
919 NewGroup = Group;
920 Group = Next;
921 }
922 }
923 // Perform semantic analysis that depends on having fully processed both
924 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000925 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000926 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
927 if (!IDecl)
928 continue;
929 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
930 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
931 QualType T = IDecl->getType();
932
933 // C99 6.7.5.2p2: If an identifier is declared to be an object with
934 // static storage duration, it shall not have a variable length array.
935 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +0000936 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000937 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
938 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +0000939 }
940 }
941 // Block scope. C99 6.7p7: If an identifier for an object is declared with
942 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
943 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
944 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000945 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
946 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000947 IDecl->setInvalidDecl();
948 }
949 }
950 // File scope. C99 6.9.2p2: A declaration of an identifier for and
951 // object that has file scope without an initializer, and without a
952 // storage-class specifier or with the storage-class specifier "static",
953 // constitutes a tentative definition. Note: A tentative definition with
954 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000955 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
956 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +0000957 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000958 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
959 // array to be completed. Don't issue a diagnostic.
960 } else if (T->isIncompleteType()) {
961 // C99 6.9.2p3: If the declaration of an identifier for an object is
962 // a tentative definition and has internal linkage (C99 6.2.2p3), the
963 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000964 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
965 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000966 IDecl->setInvalidDecl();
967 }
968 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 }
970 return NewGroup;
971}
Steve Naroffe1223f72007-08-28 03:03:08 +0000972
973// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000974ParmVarDecl *
Nate Begeman6d20d032008-02-17 21:02:04 +0000975Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
976 Scope *FnScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000977 IdentifierInfo *II = PI.Ident;
978 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
979 // Can this happen for params? We already checked that they don't conflict
980 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000981 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000982 PI.IdentLoc, FnScope)) {
983
984 }
985
986 // FIXME: Handle storage class (auto, register). No declarator?
987 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000988
989 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
990 // Doing the promotion here has a win and a loss. The win is the type for
991 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
992 // code generator). The loss is the orginal type isn't preserved. For example:
993 //
994 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
995 // int blockvardecl[5];
996 // sizeof(parmvardecl); // size == 4
997 // sizeof(blockvardecl); // size == 20
998 // }
999 //
1000 // For expressions, all implicit conversions are captured using the
1001 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1002 //
1003 // FIXME: If a source translation tool needs to see the original type, then
1004 // we need to consider storing both types (in ParmVarDecl)...
1005 //
1006 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +00001007 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
1008 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001009 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +00001010 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
1011 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001012 parmDeclType = Context.getPointerType(parmDeclType);
1013
1014 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Anders Carlssonf78915f2008-02-15 07:04:12 +00001015 VarDecl::None, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001016
Steve Naroff53a32342007-08-28 18:45:29 +00001017 if (PI.InvalidType)
1018 New->setInvalidDecl();
1019
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 // If this has an identifier, add it to the scope stack.
1021 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001022 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 II->setFETokenInfo(New);
1024 FnScope->AddDecl(New);
1025 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001026
1027 HandleDeclAttributes(New, PI.AttrList, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001028 return New;
1029}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001030
Chris Lattnerb652cea2007-10-09 17:14:05 +00001031Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 assert(CurFunctionDecl == 0 && "Function parsing confused");
1033 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1034 "Not a function declarator!");
1035 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1036
1037 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1038 // for a K&R function.
1039 if (!FTI.hasPrototype) {
1040 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1041 if (FTI.ArgInfo[i].TypeInfo == 0) {
1042 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1043 FTI.ArgInfo[i].Ident->getName());
1044 // Implicitly declare the argument as type 'int' for lack of a better
1045 // type.
1046 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1047 }
1048 }
Chris Lattner52804082008-02-17 19:31:09 +00001049
Reid Spencer5f016e22007-07-11 17:01:13 +00001050 // Since this is a function definition, act as though we have information
1051 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001052 if (FTI.NumArgs)
1053 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 } else {
1055 // FIXME: Diagnose arguments without names in C.
1056
1057 }
1058
1059 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001060
1061 // See if this is a redefinition.
1062 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1063 D.getIdentifierLoc(), GlobalScope);
1064 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1065 if (FD->getBody()) {
1066 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1067 D.getIdentifier()->getName());
1068 Diag(FD->getLocation(), diag::err_previous_definition);
1069 }
1070 }
Steve Narofffabbc342008-02-12 01:09:36 +00001071 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001072 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 CurFunctionDecl = FD;
1074
1075 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1076 llvm::SmallVector<ParmVarDecl*, 16> Params;
1077
1078 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1079 // no arguments, not a function that takes a single void argument.
1080 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerf46699c2008-02-20 20:55:12 +00001081 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001082 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 // empty arg list, don't push any params.
1084 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001085 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001086 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001087 FnBodyScope));
1088 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 }
1090
1091 FD->setParams(&Params[0], Params.size());
1092
1093 return FD;
1094}
1095
Steve Naroffd6d054d2007-11-11 23:20:51 +00001096Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1097 Decl *dcl = static_cast<Decl *>(D);
1098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1099 FD->setBody((Stmt*)Body);
1100 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001101 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001102 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001103 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001104 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001105 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 // Verify and clean out per-function state.
1107
1108 // Check goto/label use.
1109 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1110 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1111 // Verify that we have no forward references left. If so, there was a goto
1112 // or address of a label taken, but no definition of it. Label fwd
1113 // definitions are indicated with a null substmt.
1114 if (I->second->getSubStmt() == 0) {
1115 LabelStmt *L = I->second;
1116 // Emit error.
1117 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1118
1119 // At this point, we have gotos that use the bogus label. Stitch it into
1120 // the function body so that they aren't leaked and that the AST is well
1121 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001122 if (Body) {
1123 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1124 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1125 } else {
1126 // The whole function wasn't parsed correctly, just delete this.
1127 delete L;
1128 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 }
1130 }
1131 LabelMap.clear();
1132
Steve Naroffd6d054d2007-11-11 23:20:51 +00001133 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001134}
1135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1137/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001138ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1139 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 if (getLangOptions().C99) // Extension in C99.
1141 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1142 else // Legal in C90, but warn about it.
1143 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1144
1145 // FIXME: handle stuff like:
1146 // void foo() { extern float X(); }
1147 // void bar() { X(); } <-- implicit decl for X in another scope.
1148
1149 // Set a Declarator for the implicit definition: int foo();
1150 const char *Dummy;
1151 DeclSpec DS;
1152 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1153 Error = Error; // Silence warning.
1154 assert(!Error && "Error setting up implicit decl!");
1155 Declarator D(DS, Declarator::BlockContext);
1156 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1157 D.SetIdentifier(&II, Loc);
1158
1159 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001160 if (Scope *FnS = S->getFnParent())
1161 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 while (S->getParent())
1163 S = S->getParent();
1164
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001165 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001166}
1167
1168
Chris Lattner41af0932007-11-14 06:34:38 +00001169TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001170 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001172 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001173
1174 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +00001175 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1176 T, LastDeclarator);
1177 if (D.getInvalidType())
1178 NewTD->setInvalidDecl();
1179 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001180}
1181
Steve Naroff08d92e42007-09-15 18:49:24 +00001182/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001183/// former case, Name will be non-null. In the later case, Name will be null.
1184/// TagType indicates what kind of tag this is. TK indicates whether this is a
1185/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001186Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 SourceLocation KWLoc, IdentifierInfo *Name,
1188 SourceLocation NameLoc, AttributeList *Attr) {
1189 // If this is a use of an existing tag, it must have a name.
1190 assert((Name != 0 || TK == TK_Definition) &&
1191 "Nameless record must be a definition!");
1192
1193 Decl::Kind Kind;
1194 switch (TagType) {
1195 default: assert(0 && "Unknown tag type!");
1196 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1197 case DeclSpec::TST_union: Kind = Decl::Union; break;
1198//case DeclSpec::TST_class: Kind = Decl::Class; break;
1199 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1200 }
1201
1202 // If this is a named struct, check to see if there was a previous forward
1203 // declaration or definition.
1204 if (TagDecl *PrevDecl =
1205 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1206 NameLoc, S))) {
1207
1208 // If this is a use of a previous tag, or if the tag is already declared in
1209 // the same scope (so that the definition/declaration completes or
1210 // rementions the tag), reuse the decl.
1211 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1212 // Make sure that this wasn't declared as an enum and now used as a struct
1213 // or something similar.
1214 if (PrevDecl->getKind() != Kind) {
1215 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1216 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1217 }
1218
1219 // If this is a use or a forward declaration, we're good.
1220 if (TK != TK_Definition)
1221 return PrevDecl;
1222
1223 // Diagnose attempts to redefine a tag.
1224 if (PrevDecl->isDefinition()) {
1225 Diag(NameLoc, diag::err_redefinition, Name->getName());
1226 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1227 // If this is a redefinition, recover by making this struct be
1228 // anonymous, which will make any later references get the previous
1229 // definition.
1230 Name = 0;
1231 } else {
1232 // Okay, this is definition of a previously declared or referenced tag.
1233 // Move the location of the decl to be the definition site.
1234 PrevDecl->setLocation(NameLoc);
1235 return PrevDecl;
1236 }
1237 }
1238 // If we get here, this is a definition of a new struct type in a nested
1239 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1240 // type.
1241 }
1242
1243 // If there is an identifier, use the location of the identifier as the
1244 // location of the decl, otherwise use the location of the struct/union
1245 // keyword.
1246 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1247
1248 // Otherwise, if this is the first time we've seen this tag, create the decl.
1249 TagDecl *New;
1250 switch (Kind) {
1251 default: assert(0 && "Unknown tag kind!");
1252 case Decl::Enum:
1253 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1254 // enum X { A, B, C } D; D should chain to X.
1255 New = new EnumDecl(Loc, Name, 0);
1256 // If this is an undefined enum, warn.
1257 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1258 break;
1259 case Decl::Union:
1260 case Decl::Struct:
1261 case Decl::Class:
1262 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1263 // struct X { int A; } D; D should chain to X.
1264 New = new RecordDecl(Kind, Loc, Name, 0);
1265 break;
1266 }
1267
1268 // If this has an identifier, add it to the scope stack.
1269 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001270 // The scope passed in may not be a decl scope. Zip up the scope tree until
1271 // we find one that is.
1272 while ((S->getFlags() & Scope::DeclScope) == 0)
1273 S = S->getParent();
1274
1275 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001276 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001277 Name->setFETokenInfo(New);
1278 S->AddDecl(New);
1279 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001280
Anders Carlssonad148062008-02-16 00:29:18 +00001281 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 return New;
1283}
1284
Steve Naroff08d92e42007-09-15 18:49:24 +00001285/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001287Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 SourceLocation DeclStart,
1289 Declarator &D, ExprTy *BitfieldWidth) {
1290 IdentifierInfo *II = D.getIdentifier();
1291 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 SourceLocation Loc = DeclStart;
1293 if (II) Loc = D.getIdentifierLoc();
1294
1295 // FIXME: Unnamed fields can be handled in various different ways, for
1296 // example, unnamed unions inject all members into the struct namespace!
1297
1298
1299 if (BitWidth) {
1300 // TODO: Validate.
1301 //printf("WARNING: BITFIELDS IGNORED!\n");
1302
1303 // 6.7.2.1p3
1304 // 6.7.2.1p4
1305
1306 } else {
1307 // Not a bitfield.
1308
1309 // validate II.
1310
1311 }
1312
1313 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001314 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1315 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001316
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1318 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001319 if (T->isVariablyModifiedType()) {
1320 // FIXME: This diagnostic needs work
1321 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001322 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001324 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001325 FieldDecl *NewFD;
1326
1327 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001328 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001329 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1330 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1331 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001332 // FIXME: ivars are currently used to model properties, and
1333 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001334 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1335 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1336 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001337 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001338 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001339
Anders Carlssonad148062008-02-16 00:29:18 +00001340 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1341 D.getAttributes());
1342
Steve Naroff5912a352007-08-28 20:14:24 +00001343 if (D.getInvalidType() || InvalidDecl)
1344 NewFD->setInvalidDecl();
1345 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346}
1347
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001348/// TranslateIvarVisibility - Translate visibility from a token ID to an
1349/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001350static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001351TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001352 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001353 case tok::objc_private: return ObjCIvarDecl::Private;
1354 case tok::objc_public: return ObjCIvarDecl::Public;
1355 case tok::objc_protected: return ObjCIvarDecl::Protected;
1356 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001357 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001358 }
1359}
1360
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001361void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001362 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001363 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001364 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001365 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001366 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1367 assert(EnclosingDecl && "missing record or interface decl");
1368 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1369
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001370 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001371 // Diagnose code like:
1372 // struct S { struct S {} X; };
1373 // We discover this when we complete the outer S. Reject and ignore the
1374 // outer S.
1375 Diag(Record->getLocation(), diag::err_nested_redefinition,
1376 Record->getKindName());
1377 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001378 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 return;
1380 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 // Verify that all the fields are okay.
1382 unsigned NumNamedMembers = 0;
1383 llvm::SmallVector<FieldDecl*, 32> RecFields;
1384 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001385
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001387
Steve Naroff74216642007-09-14 22:20:54 +00001388 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1389 assert(FD && "missing field decl");
1390
1391 // Remember all fields.
1392 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393
1394 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001395 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001396
Steve Narofff13271f2007-09-14 23:09:53 +00001397 // If we have visibility info, make sure the AST is set accordingly.
1398 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001399 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001400 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001401
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001403 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001404 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001405 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001406 FD->setInvalidDecl();
1407 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001408 continue;
1409 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001410 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1411 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001412 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001413 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001414 FD->setInvalidDecl();
1415 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001416 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001417 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 if (i != NumFields-1 || // ... that the last member ...
1419 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001420 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001422 FD->setInvalidDecl();
1423 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 continue;
1425 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001426 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1428 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001429 FD->setInvalidDecl();
1430 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 continue;
1432 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001434 if (Record)
1435 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001436 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1438 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001439 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1441 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001442 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001443 Record->setHasFlexibleArrayMember(true);
1444 } else {
1445 // If this is a struct/class and this is not the last element, reject
1446 // it. Note that GCC supports variable sized arrays in the middle of
1447 // structures.
1448 if (i != NumFields-1) {
1449 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1450 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001451 FD->setInvalidDecl();
1452 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 continue;
1454 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 // We support flexible arrays at the end of structs in other structs
1456 // as an extension.
1457 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1458 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001459 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001460 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 }
1462 }
1463 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001464 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001465 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001466 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1467 FD->getName());
1468 FD->setInvalidDecl();
1469 EnclosingDecl->setInvalidDecl();
1470 continue;
1471 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // Keep track of the number of named members.
1473 if (IdentifierInfo *II = FD->getIdentifier()) {
1474 // Detect duplicate member names.
1475 if (!FieldIDs.insert(II)) {
1476 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1477 // Find the previous decl.
1478 SourceLocation PrevLoc;
1479 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1480 assert(i != e && "Didn't find previous def!");
1481 if (RecFields[i]->getIdentifier() == II) {
1482 PrevLoc = RecFields[i]->getLocation();
1483 break;
1484 }
1485 }
1486 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001487 FD->setInvalidDecl();
1488 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 continue;
1490 }
1491 ++NumNamedMembers;
1492 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 }
1494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001496 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001497 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001498 Consumer.HandleTagDeclDefinition(Record);
1499 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001500 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1501 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1502 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1503 else if (ObjCImplementationDecl *IMPDecl =
1504 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001505 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1506 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001507 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001508 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001509 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001510}
1511
Steve Naroff08d92e42007-09-15 18:49:24 +00001512Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 DeclTy *lastEnumConst,
1514 SourceLocation IdLoc, IdentifierInfo *Id,
1515 SourceLocation EqualLoc, ExprTy *val) {
1516 theEnumDecl = theEnumDecl; // silence unused warning.
1517 EnumConstantDecl *LastEnumConst =
1518 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1519 Expr *Val = static_cast<Expr*>(val);
1520
Chris Lattner31e05722007-08-26 06:24:45 +00001521 // The scope passed in may not be a decl scope. Zip up the scope tree until
1522 // we find one that is.
1523 while ((S->getFlags() & Scope::DeclScope) == 0)
1524 S = S->getParent();
1525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // Verify that there isn't already something declared with this name in this
1527 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001528 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1529 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 if (S->isDeclScope(PrevDecl)) {
1531 if (isa<EnumConstantDecl>(PrevDecl))
1532 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1533 else
1534 Diag(IdLoc, diag::err_redefinition, Id->getName());
1535 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001536 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 return 0;
1538 }
1539 }
1540
1541 llvm::APSInt EnumVal(32);
1542 QualType EltTy;
1543 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001544 // Make sure to promote the operand type to int.
1545 UsualUnaryConversions(Val);
1546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1548 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001549 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1551 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001552 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001553 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001554 } else {
1555 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001557 }
1558
1559 if (!Val) {
1560 if (LastEnumConst) {
1561 // Assign the last value + 1.
1562 EnumVal = LastEnumConst->getInitVal();
1563 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001564
1565 // Check for overflow on increment.
1566 if (EnumVal < LastEnumConst->getInitVal())
1567 Diag(IdLoc, diag::warn_enum_value_overflow);
1568
Chris Lattnerb7416f92007-08-27 17:37:24 +00001569 EltTy = LastEnumConst->getType();
1570 } else {
1571 // First value, set to zero.
1572 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001573 EnumVal.zextOrTrunc(
1574 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 }
1577
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1579 LastEnumConst);
1580
1581 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001582 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 Id->setFETokenInfo(New);
1584 S->AddDecl(New);
1585 return New;
1586}
1587
Steve Naroff08d92e42007-09-15 18:49:24 +00001588void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 DeclTy **Elements, unsigned NumElements) {
1590 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1591 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1592
Chris Lattnere37f0be2007-08-28 05:10:31 +00001593 // TODO: If the result value doesn't fit in an int, it must be a long or long
1594 // long value. ISO C does not support this, but GCC does as an extension,
1595 // emit a warning.
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001596 unsigned IntWidth =
1597 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattnere37f0be2007-08-28 05:10:31 +00001598
1599
Chris Lattnerac609682007-08-28 06:15:15 +00001600 // Verify that all the values are okay, compute the size of the values, and
1601 // reverse the list.
1602 unsigned NumNegativeBits = 0;
1603 unsigned NumPositiveBits = 0;
1604
1605 // Keep track of whether all elements have type int.
1606 bool AllElementsInt = true;
1607
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 EnumConstantDecl *EltList = 0;
1609 for (unsigned i = 0; i != NumElements; ++i) {
1610 EnumConstantDecl *ECD =
1611 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1612 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001613
1614 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001615 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001616 assert(InitVal.getBitWidth() >= IntWidth &&
1617 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001618 if (InitVal.getBitWidth() > IntWidth) {
1619 llvm::APSInt V(InitVal);
1620 V.trunc(IntWidth);
1621 V.extend(InitVal.getBitWidth());
1622 if (V != InitVal)
1623 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1624 InitVal.toString());
1625 }
Chris Lattnerac609682007-08-28 06:15:15 +00001626
1627 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001628 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001629 NumPositiveBits = std::max(NumPositiveBits,
1630 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001631 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001632 NumNegativeBits = std::max(NumNegativeBits,
1633 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001634
Chris Lattnerac609682007-08-28 06:15:15 +00001635 // Keep track of whether every enum element has type int (very commmon).
1636 if (AllElementsInt)
1637 AllElementsInt = ECD->getType() == Context.IntTy;
1638
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 ECD->setNextDeclarator(EltList);
1640 EltList = ECD;
1641 }
1642
Chris Lattnerac609682007-08-28 06:15:15 +00001643 // Figure out the type that should be used for this enum.
1644 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1645 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001646 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001647
1648 if (NumNegativeBits) {
1649 // If there is a negative value, figure out the smallest integer type (of
1650 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001651 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001652 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001653 BestWidth = IntWidth;
1654 } else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001655 BestWidth =
1656 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1657
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001658 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001659 BestType = Context.LongTy;
1660 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001661 BestWidth = Context.Target.getLongLongWidth(
1662 Context.getFullLoc(Enum->getLocation()));
1663
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001664 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001665 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1666 BestType = Context.LongLongTy;
1667 }
1668 }
1669 } else {
1670 // If there is no negative value, figure out which of uint, ulong, ulonglong
1671 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001672 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001673 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001674 BestWidth = IntWidth;
1675 } else if (NumPositiveBits <=
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001676 (BestWidth = Context.Target.getLongWidth(
1677 Context.getFullLoc(Enum->getLocation()))))
1678
Chris Lattnerac609682007-08-28 06:15:15 +00001679 BestType = Context.UnsignedLongTy;
1680 else {
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001681 BestWidth =
1682 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1683
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001684 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001685 "How could an initializer get larger than ULL?");
1686 BestType = Context.UnsignedLongLongTy;
1687 }
1688 }
1689
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001690 // Loop over all of the enumerator constants, changing their types to match
1691 // the type of the enum if needed.
1692 for (unsigned i = 0; i != NumElements; ++i) {
1693 EnumConstantDecl *ECD =
1694 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1695 if (!ECD) continue; // Already issued a diagnostic.
1696
1697 // Standard C says the enumerators have int type, but we allow, as an
1698 // extension, the enumerators to be larger than int size. If each
1699 // enumerator value fits in an int, type it as an int, otherwise type it the
1700 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1701 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001702 if (ECD->getType() == Context.IntTy) {
1703 // Make sure the init value is signed.
1704 llvm::APSInt IV = ECD->getInitVal();
1705 IV.setIsSigned(true);
1706 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001707 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001708 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001709
1710 // Determine whether the value fits into an int.
1711 llvm::APSInt InitVal = ECD->getInitVal();
1712 bool FitsInInt;
1713 if (InitVal.isUnsigned() || !InitVal.isNegative())
1714 FitsInInt = InitVal.getActiveBits() < IntWidth;
1715 else
1716 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1717
1718 // If it fits into an integer type, force it. Otherwise force it to match
1719 // the enum decl type.
1720 QualType NewTy;
1721 unsigned NewWidth;
1722 bool NewSign;
1723 if (FitsInInt) {
1724 NewTy = Context.IntTy;
1725 NewWidth = IntWidth;
1726 NewSign = true;
1727 } else if (ECD->getType() == BestType) {
1728 // Already the right type!
1729 continue;
1730 } else {
1731 NewTy = BestType;
1732 NewWidth = BestWidth;
1733 NewSign = BestType->isSignedIntegerType();
1734 }
1735
1736 // Adjust the APSInt value.
1737 InitVal.extOrTrunc(NewWidth);
1738 InitVal.setIsSigned(NewSign);
1739 ECD->setInitVal(InitVal);
1740
1741 // Adjust the Expr initializer and type.
1742 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1743 ECD->setType(NewTy);
1744 }
Chris Lattnerac609682007-08-28 06:15:15 +00001745
Chris Lattnere00b18c2007-08-28 18:24:31 +00001746 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001747 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001748}
1749
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001750Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1751 ExprTy *expr) {
1752 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1753
1754 return new FileScopeAsmDecl(Loc, AsmString);
1755}
1756
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001757Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001758 SourceLocation LBrace,
1759 SourceLocation RBrace,
1760 const char *Lang,
1761 unsigned StrSize,
1762 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001763 LinkageSpecDecl::LanguageIDs Language;
1764 Decl *dcl = static_cast<Decl *>(D);
1765 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1766 Language = LinkageSpecDecl::lang_c;
1767 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1768 Language = LinkageSpecDecl::lang_cxx;
1769 else {
1770 Diag(Loc, diag::err_bad_language);
1771 return 0;
1772 }
1773
1774 // FIXME: Add all the various semantics of linkage specifications
1775 return new LinkageSpecDecl(Loc, Language, dcl);
1776}
1777
Chris Lattner74788ba2008-02-21 00:48:22 +00001778void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001779
Chris Lattner74788ba2008-02-21 00:48:22 +00001780 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001781 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001783 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001784 if (!newType.isNull()) // install the new vector type into the decl
1785 vDecl->setType(newType);
1786 }
1787 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1788 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001789 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 if (!newType.isNull()) // install the new vector type into the decl
1791 tDecl->setUnderlyingType(newType);
1792 }
Chris Lattner212839c2008-02-20 23:17:35 +00001793 break;
1794 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001795 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001796 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001797 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001798 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001799 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001800 break;
1801 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001802 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1803 QualType newType = HandleAddressSpaceTypeAttribute(
1804 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001805 Attr);
1806 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001807 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1808 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001809 Attr);
1810 // install the new addr spaced type into the decl
1811 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001812 }
Chris Lattner212839c2008-02-20 23:17:35 +00001813 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001814 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001815 HandleDeprecatedAttribute(New, Attr);
1816 break;
1817 case AttributeList::AT_visibility:
1818 HandleVisibilityAttribute(New, Attr);
1819 break;
1820 case AttributeList::AT_weak:
1821 HandleWeakAttribute(New, Attr);
1822 break;
1823 case AttributeList::AT_dllimport:
1824 HandleDLLImportAttribute(New, Attr);
1825 break;
1826 case AttributeList::AT_dllexport:
1827 HandleDLLExportAttribute(New, Attr);
1828 break;
1829 case AttributeList::AT_nothrow:
1830 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001831 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001832 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001833 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001834 break;
1835 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001836 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001837 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001838 case AttributeList::AT_annotate:
1839 HandleAnnotateAttribute(New, Attr);
1840 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001841 case AttributeList::AT_noreturn:
1842 HandleNoReturnAttribute(New, Attr);
1843 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001844 case AttributeList::AT_format:
1845 HandleFormatAttribute(New, Attr);
1846 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001847 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001848#if 0
1849 // TODO: when we have the full set of attributes, warn about unknown ones.
1850 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1851 Attr->getName()->getName());
1852#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001853 break;
1854 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001855}
1856
1857void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1858 AttributeList *declarator_postfix) {
1859 while (declspec_prefix) {
1860 HandleDeclAttribute(New, declspec_prefix);
1861 declspec_prefix = declspec_prefix->getNext();
1862 }
1863 while (declarator_postfix) {
1864 HandleDeclAttribute(New, declarator_postfix);
1865 declarator_postfix = declarator_postfix->getNext();
1866 }
1867}
1868
Steve Naroffbea0b342007-07-29 16:33:31 +00001869void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1870 AttributeList *rawAttr) {
1871 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001872 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001873 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001874 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00001875 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001876 return;
Steve Naroff73322922007-07-18 18:00:27 +00001877 }
1878 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1879 llvm::APSInt vecSize(32);
1880 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001881 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001882 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001883 return;
Steve Naroff73322922007-07-18 18:00:27 +00001884 }
1885 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1886 // in conjunction with complex types (pointers, arrays, functions, etc.).
1887 Type *canonType = curType.getCanonicalType().getTypePtr();
1888 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001889 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00001890 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001891 return;
Steve Naroff73322922007-07-18 18:00:27 +00001892 }
1893 // unlike gcc's vector_size attribute, the size is specified as the
1894 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001895 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001896
1897 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001898 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00001899 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001900 return;
Steve Naroff73322922007-07-18 18:00:27 +00001901 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001902 // Instantiate/Install the vector type, the number of elements is > 0.
1903 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1904 // Remember this typedef decl, we will need it later for diagnostics.
1905 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001906}
1907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001909 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // check the attribute arugments.
1911 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001912 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 std::string("1"));
1914 return QualType();
1915 }
1916 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1917 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001918 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001919 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001920 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 return QualType();
1922 }
1923 // navigate to the base type - we need to provide for vector pointers,
1924 // vector arrays, and functions returning vectors.
1925 Type *canonType = curType.getCanonicalType().getTypePtr();
1926
Steve Naroff73322922007-07-18 18:00:27 +00001927 if (canonType->isPointerType() || canonType->isArrayType() ||
1928 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001929 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001930 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1931 do {
1932 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1933 canonType = PT->getPointeeType().getTypePtr();
1934 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1935 canonType = AT->getElementType().getTypePtr();
1936 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1937 canonType = FT->getResultType().getTypePtr();
1938 } while (canonType->isPointerType() || canonType->isArrayType() ||
1939 canonType->isFunctionType());
1940 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 }
1942 // the base type must be integer or float.
1943 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001944 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00001945 curType.getCanonicalType().getAsString());
1946 return QualType();
1947 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00001948 unsigned typeSize = static_cast<unsigned>(
Chris Lattner2070d802008-02-20 23:25:22 +00001949 Context.getTypeSize(curType, rawAttr->getLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001951 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001952
1953 // the vector size needs to be an integral multiple of the type size.
1954 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00001955 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 sizeExpr->getSourceRange());
1957 return QualType();
1958 }
1959 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001960 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 sizeExpr->getSourceRange());
1962 return QualType();
1963 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00001964 // Instantiate the vector type, the number of elements is > 0, and not
1965 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00001966 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001967}
1968
Chris Lattner2070d802008-02-20 23:25:22 +00001969void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00001970 // check the attribute arguments.
1971 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001972 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00001973 std::string("0"));
1974 return;
1975 }
1976
1977 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1978 TD->addAttr(new PackedAttr);
1979 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1980 // If the alignment is less than or equal to 8 bits, the packed attribute
1981 // has no effect.
1982 if (Context.getTypeAlign(FD->getType(), SourceLocation()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00001983 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00001984 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00001985 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00001986 else
Anders Carlsson425a6092008-02-16 00:39:40 +00001987 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00001988 } else
Chris Lattner2070d802008-02-20 23:25:22 +00001989 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
1990 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00001991}
Nate Begemanc398f0b2008-02-21 19:30:49 +00001992
Ted Kremenekaecb3832008-02-27 20:43:06 +00001993void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
1994 // check the attribute arguments.
1995 if (rawAttr->getNumArgs() != 0) {
1996 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1997 std::string("0"));
1998 return;
1999 }
2000
2001 d->addAttr(new NoReturnAttr());
2002}
2003
Chris Lattnerddee4232008-03-03 03:28:21 +00002004void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2005 // check the attribute arguments.
2006 if (rawAttr->getNumArgs() != 0) {
2007 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2008 std::string("0"));
2009 return;
2010 }
2011
2012 d->addAttr(new DeprecatedAttr());
2013}
2014
2015void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2016 // check the attribute arguments.
2017 if (rawAttr->getNumArgs() != 0) {
2018 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2019 std::string("1"));
2020 return;
2021 }
2022
2023 if (!rawAttr->getParameterName()) {
2024 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2025 "visibility", std::string("1"));
2026 return;
2027 }
2028
2029 const char *typeStr = rawAttr->getParameterName()->getName();
2030 llvm::GlobalValue::VisibilityTypes type;
2031
2032 if (!memcmp(typeStr, "default", 7))
2033 type = llvm::GlobalValue::DefaultVisibility;
2034 else if (!memcmp(typeStr, "hidden", 6))
2035 type = llvm::GlobalValue::HiddenVisibility;
2036 else if (!memcmp(typeStr, "internal", 8))
2037 type = llvm::GlobalValue::HiddenVisibility; // FIXME
2038 else if (!memcmp(typeStr, "protected", 9))
2039 type = llvm::GlobalValue::ProtectedVisibility;
2040 else {
2041 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2042 "visibility", typeStr);
2043 return;
2044 }
2045
2046 d->addAttr(new VisibilityAttr(type));
2047}
2048
2049void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2050 // check the attribute arguments.
2051 if (rawAttr->getNumArgs() != 0) {
2052 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2053 std::string("0"));
2054 return;
2055 }
2056
2057 d->addAttr(new WeakAttr());
2058}
2059
2060void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2061 // check the attribute arguments.
2062 if (rawAttr->getNumArgs() != 0) {
2063 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2064 std::string("0"));
2065 return;
2066 }
2067
2068 d->addAttr(new DLLImportAttr());
2069}
2070
2071void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2072 // check the attribute arguments.
2073 if (rawAttr->getNumArgs() != 0) {
2074 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2075 std::string("0"));
2076 return;
2077 }
2078
2079 d->addAttr(new DLLExportAttr());
2080}
2081
2082void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2083 // check the attribute arguments.
2084 if (rawAttr->getNumArgs() != 0) {
2085 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2086 std::string("0"));
2087 return;
2088 }
2089
2090 d->addAttr(new NoThrowAttr());
2091}
2092
2093void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2094
2095 if (!rawAttr->getParameterName()) {
2096 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2097 "format", std::string("1"));
2098 return;
2099 }
2100
2101 if (rawAttr->getNumArgs() != 2) {
2102 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2103 std::string("3"));
2104 return;
2105 }
2106
2107 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2108 if (!Fn) {
2109 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2110 "format", "function");
2111 return;
2112 }
2113
2114 // FIXME: in C++ the implicit 'this' function parameter also counts.
2115 // the index must start in 1 and the limit is numargs+1
2116 unsigned NumArgs = Fn->getNumParams()+1; // +1 for ...
2117
2118 const char *Format = rawAttr->getParameterName()->getName();
2119 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2120
2121 // Normalize the argument, __foo__ becomes foo.
2122 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2123 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2124 Format += 2;
2125 FormatLen -= 4;
2126 }
2127
2128 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2129 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2130 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2131 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2132 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2133 "format", rawAttr->getParameterName()->getName());
2134 return;
2135 }
2136
2137 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
2138 llvm::APSInt Idx(32);
2139 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2140 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2141 "format", std::string("2"), IdxExpr->getSourceRange());
2142 return;
2143 }
2144
2145 if (Idx.getZExtValue() < 1 || Idx.getZExtValue() > NumArgs) {
2146 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2147 "format", std::string("2"), IdxExpr->getSourceRange());
2148 return;
2149 }
2150
2151 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
2152 llvm::APSInt FirstArg(32);
2153 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2154 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2155 "format", std::string("3"), FirstArgExpr->getSourceRange());
2156 return;
2157 }
2158
2159 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
2160 if (FirstArg.getZExtValue() != 0) {
2161 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2162 FirstArgExpr->getSourceRange());
2163 return;
2164 }
2165 } else if (FirstArg.getZExtValue() > NumArgs) {
2166 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2167 "format", std::string("3"), FirstArgExpr->getSourceRange());
2168 return;
2169 }
2170
2171 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2172 Idx.getZExtValue(), FirstArg.getZExtValue()));
2173}
2174
Nate Begemanc398f0b2008-02-21 19:30:49 +00002175void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2176 // check the attribute arguments.
2177 if (rawAttr->getNumArgs() != 1) {
2178 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2179 std::string("1"));
2180 return;
2181 }
2182 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2183 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002184
Nate Begemanc398f0b2008-02-21 19:30:49 +00002185 // Make sure that there is a string literal as the annotation's single
2186 // argument.
2187 if (!SE) {
2188 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2189 return;
2190 }
2191 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2192 SE->getByteLength())));
2193}
2194
Anders Carlsson78aaae92007-12-19 07:19:40 +00002195void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2196{
2197 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002198 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002199 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002200 std::string("1"));
2201 return;
2202 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002203
Anders Carlsson042c4e72008-02-16 19:51:27 +00002204 unsigned Align = 0;
2205
2206 if (rawAttr->getNumArgs() == 0) {
2207 // FIXME: This should be the target specific maximum alignment.
2208 // (For now we just use 128 bits which is the maximum on X86.
2209 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002210 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002211 } else {
2212 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2213 llvm::APSInt alignment(32);
2214 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002215 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002216 "aligned", alignmentExpr->getSourceRange());
2217 return;
2218 }
2219
2220 Align = alignment.getZExtValue() * 8;
2221 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002222
Anders Carlsson042c4e72008-02-16 19:51:27 +00002223 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002224}