blob: 90f9133d4b8272a53c15105a25df84fa8200c1be [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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 // If this is a builtin on this (or all) targets, create the decl.
139 if (unsigned BuiltinID = II->getBuiltinID())
140 return LazilyCreateBuiltin(II, BuiltinID, S);
141 }
142 return 0;
143}
144
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000145void Sema::InitBuiltinVaListType()
146{
147 if (!Context.getBuiltinVaListType().isNull())
148 return;
149
150 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
151 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
152 SourceLocation(), TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000153 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000154 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
155}
156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
158/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000159ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
160 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 Builtin::ID BID = (Builtin::ID)bid;
162
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000164 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000165 BID == Builtin::BI__builtin_va_end)
166 InitBuiltinVaListType();
167
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000168 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000170 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000173 if (Scope *FnS = S->getFnParent())
174 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 while (S->getParent())
176 S = S->getParent();
177 S->AddDecl(New);
178
179 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000180 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 // Scan until we find the last (outermost) decl in the id chain.
182 while (LastDecl->getNext())
183 LastDecl = LastDecl->getNext();
184 // Insert before (outside) it.
185 LastDecl->setNext(New);
186 } else {
187 II->setFETokenInfo(New);
188 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 return New;
190}
191
192/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
193/// and scope as a previous declaration 'Old'. Figure out how to resolve this
194/// situation, merging decls or emitting diagnostics as appropriate.
195///
Steve Naroff8e74c932007-09-13 21:41:19 +0000196TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 // Verify the old decl was also a typedef.
198 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
199 if (!Old) {
200 Diag(New->getLocation(), diag::err_redefinition_different_kind,
201 New->getName());
202 Diag(OldD->getLocation(), diag::err_previous_definition);
203 return New;
204 }
205
Steve Naroff8ee529b2007-10-31 18:42:27 +0000206 // Allow multiple definitions for ObjC built-in typedefs.
207 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000208 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000209 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000210
211 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
212 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
213 // *either* declaration is in a system header. The code below implements
214 // this adhoc compatibility rule. FIXME: The following code will not
215 // work properly when compiling ".i" files (containing preprocessed output).
216 SourceManager &SrcMgr = Context.getSourceManager();
217 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
218 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
219 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
220 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
221 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
222
Steve Naroffd62701b2008-02-07 03:50:06 +0000223 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
224 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
225 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000226 return New;
Steve Naroff8ee529b2007-10-31 18:42:27 +0000227
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
229 // TODO: This is totally simplistic. It should handle merging functions
230 // together etc, merging extern int X; int X; ...
231 Diag(New->getLocation(), diag::err_redefinition, New->getName());
232 Diag(Old->getLocation(), diag::err_previous_definition);
233 return New;
234}
235
Chris Lattnerddee4232008-03-03 03:28:21 +0000236/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
237static bool DeclHasAttr(const Decl *decl, const Attr *target) {
238 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
239 if (attr->getKind() == target->getKind())
240 return true;
241
242 return false;
243}
244
245/// MergeAttributes - append attributes from the Old decl to the New one.
246static void MergeAttributes(Decl *New, Decl *Old) {
247 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
248
249// FIXME: fix this code to cleanup the Old attrs correctly
250 while (attr) {
251 tmp = attr;
252 attr = attr->getNext();
253
254 if (!DeclHasAttr(New, tmp)) {
255 New->addAttr(tmp);
256 } else {
257 tmp->setNext(0);
258 delete(tmp);
259 }
260 }
261}
262
Reid Spencer5f016e22007-07-11 17:01:13 +0000263/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
264/// and scope as a previous declaration 'Old'. Figure out how to resolve this
265/// situation, merging decls or emitting diagnostics as appropriate.
266///
Steve Naroff8e74c932007-09-13 21:41:19 +0000267FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000268 // Verify the old decl was also a function.
269 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
270 if (!Old) {
271 Diag(New->getLocation(), diag::err_redefinition_different_kind,
272 New->getName());
273 Diag(OldD->getLocation(), diag::err_previous_definition);
274 return New;
275 }
Chris Lattner7e669b22008-02-29 16:48:43 +0000276
Chris Lattnerddee4232008-03-03 03:28:21 +0000277 MergeAttributes(New, Old);
278
Reid Spencer5f016e22007-07-11 17:01:13 +0000279
Chris Lattner55196442007-11-20 19:04:50 +0000280 QualType OldQType = Old->getCanonicalType();
281 QualType NewQType = New->getCanonicalType();
282
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000283 // Function types need to be compatible, not identical. This handles
284 // duplicate function decls like "void f(int); void f(enum X);" properly.
285 if (Context.functionTypesAreCompatible(OldQType, NewQType))
286 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000287
Steve Naroff837618c2008-01-16 15:01:34 +0000288 // A function that has already been declared has been redeclared or defined
289 // with a different type- show appropriate diagnostic
290 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
291 diag::err_previous_declaration;
292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
294 // TODO: This is totally simplistic. It should handle merging functions
295 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000296 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
297 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 return New;
299}
300
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000301/// equivalentArrayTypes - Used to determine whether two array types are
302/// equivalent.
303/// We need to check this explicitly as an incomplete array definition is
304/// considered a VariableArrayType, so will not match a complete array
305/// definition that would be otherwise equivalent.
306static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
307 const ArrayType *NewAT = NewQType->getAsArrayType();
308 const ArrayType *OldAT = OldQType->getAsArrayType();
309
310 if (!NewAT || !OldAT)
311 return false;
312
313 // If either (or both) array types in incomplete we need to strip off the
314 // outer VariableArrayType. Once the outer VAT is removed the remaining
315 // types must be identical if the array types are to be considered
316 // equivalent.
317 // eg. int[][1] and int[1][1] become
318 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
319 // removing the outermost VAT gives
320 // CAT(1, int) and CAT(1, int)
321 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000322 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000323 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
324 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000325 NewQType = NewAT->getElementType().getCanonicalType();
326 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000327 }
328
329 return NewQType == OldQType;
330}
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332/// MergeVarDecl - We just parsed a variable 'New' which has the same name
333/// and scope as a previous declaration 'Old'. Figure out how to resolve this
334/// situation, merging decls or emitting diagnostics as appropriate.
335///
336/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
337/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
338///
Steve Naroff8e74c932007-09-13 21:41:19 +0000339VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // Verify the old decl was also a variable.
341 VarDecl *Old = dyn_cast<VarDecl>(OldD);
342 if (!Old) {
343 Diag(New->getLocation(), diag::err_redefinition_different_kind,
344 New->getName());
345 Diag(OldD->getLocation(), diag::err_previous_definition);
346 return New;
347 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000348
349 MergeAttributes(New, Old);
350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000352 if (Old->getCanonicalType() != New->getCanonicalType() &&
353 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 Diag(New->getLocation(), diag::err_redefinition, New->getName());
355 Diag(Old->getLocation(), diag::err_previous_definition);
356 return New;
357 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000358 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
359 if (New->getStorageClass() == VarDecl::Static &&
360 (Old->getStorageClass() == VarDecl::None ||
361 Old->getStorageClass() == VarDecl::Extern)) {
362 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
363 Diag(Old->getLocation(), diag::err_previous_definition);
364 return New;
365 }
366 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
367 if (New->getStorageClass() != VarDecl::Static &&
368 Old->getStorageClass() == VarDecl::Static) {
369 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
370 Diag(Old->getLocation(), diag::err_previous_definition);
371 return New;
372 }
373 // We've verified the types match, now handle "tentative" definitions.
374 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
375 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
376
377 if (OldFSDecl && NewFSDecl) {
378 // Handle C "tentative" external object definitions (C99 6.9.2).
379 bool OldIsTentative = false;
380 bool NewIsTentative = false;
381
382 if (!OldFSDecl->getInit() &&
383 (OldFSDecl->getStorageClass() == VarDecl::None ||
384 OldFSDecl->getStorageClass() == VarDecl::Static))
385 OldIsTentative = true;
386
387 // FIXME: this check doesn't work (since the initializer hasn't been
388 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
389 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
390 // thrown out the old decl.
391 if (!NewFSDecl->getInit() &&
392 (NewFSDecl->getStorageClass() == VarDecl::None ||
393 NewFSDecl->getStorageClass() == VarDecl::Static))
394 ; // change to NewIsTentative = true; once the code is moved.
395
396 if (NewIsTentative || OldIsTentative)
397 return New;
398 }
399 if (Old->getStorageClass() != VarDecl::Extern &&
400 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 Diag(New->getLocation(), diag::err_redefinition, New->getName());
402 Diag(Old->getLocation(), diag::err_previous_definition);
403 }
404 return New;
405}
406
407/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
408/// no declarator (e.g. "struct foo;") is parsed.
409Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
410 // TODO: emit error on 'int;' or 'const enum foo;'.
411 // TODO: emit error on 'typedef int;'
412 // if (!DS.isMissingDeclaratorOk()) Diag(...);
413
Steve Naroff92199282007-11-17 21:37:36 +0000414 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000415}
416
Steve Naroffd0091aa2008-01-10 22:15:12 +0000417bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000418 // Get the type before calling CheckSingleAssignmentConstraints(), since
419 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000420 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000421
Chris Lattner5cf216b2008-01-04 18:04:52 +0000422 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
423 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
424 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000425}
426
Steve Naroff9e8925e2007-09-04 14:36:54 +0000427bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000428 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000429 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000430 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000431 return true; // types weren't compatible.
432
Steve Naroff9e8925e2007-09-04 14:36:54 +0000433 if (savExpr != expr) // The type was promoted, update initializer list.
434 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000435 return false;
436}
437
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000438bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000439 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000440 // C99 6.7.8p14. We have an array of character type with unknown size
441 // being initialized to a string literal.
442 llvm::APSInt ConstVal(32);
443 ConstVal = strLiteral->getByteLength() + 1;
444 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000445 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000446 ArrayType::Normal, 0);
447 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
448 // C99 6.7.8p14. We have an array of character type with known size.
449 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
450 Diag(strLiteral->getSourceRange().getBegin(),
451 diag::warn_initializer_string_for_char_array_too_long,
452 strLiteral->getSourceRange());
453 } else {
454 assert(0 && "HandleStringLiteralInit(): Invalid array type");
455 }
456 // Set type from "char *" to "constant array of char".
457 strLiteral->setType(DeclT);
458 // For now, we always return false (meaning success).
459 return false;
460}
461
462StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000463 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000464 if (AT && AT->getElementType()->isCharType()) {
465 return dyn_cast<StringLiteral>(Init);
466 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000467 return 0;
468}
469
Steve Naroffa9960332008-01-25 00:51:06 +0000470// CheckInitializerListTypes - Checks the types of elements of an initializer
471// list. This function is recursive: it calls itself to initialize subelements
472// of aggregate types. Note that the topLevel parameter essentially refers to
473// whether this expression "owns" the initializer list passed in, or if this
474// initialization is taking elements out of a parent initializer. Each
475// call to this function adds zero or more to startIndex, reports any errors,
476// and returns true if it found any inconsistent types.
477bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
478 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000479 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000480
481 if (DeclType->isScalarType()) {
482 // The simplest case: initializing a single scalar
483 if (topLevel) {
484 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
485 IList->getSourceRange());
486 }
487 if (startIndex < IList->getNumInits()) {
488 Expr* expr = IList->getInit(startIndex);
489 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
490 // FIXME: Should an error be reported here instead?
491 unsigned newIndex = 0;
492 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
493 } else {
494 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
495 }
496 ++startIndex;
497 }
498 // FIXME: Should an error be reported for empty initializer list + scalar?
499 } else if (DeclType->isVectorType()) {
500 if (startIndex < IList->getNumInits()) {
501 const VectorType *VT = DeclType->getAsVectorType();
502 int maxElements = VT->getNumElements();
503 QualType elementType = VT->getElementType();
504
505 for (int i = 0; i < maxElements; ++i) {
506 // Don't attempt to go past the end of the init list
507 if (startIndex >= IList->getNumInits())
508 break;
509 Expr* expr = IList->getInit(startIndex);
510 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
511 unsigned newIndex = 0;
512 hadError |= CheckInitializerListTypes(SubInitList, elementType,
513 true, newIndex);
514 ++startIndex;
515 } else {
516 hadError |= CheckInitializerListTypes(IList, elementType,
517 false, startIndex);
518 }
519 }
520 }
521 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
522 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000523 if (startIndex < IList->getNumInits() && !topLevel &&
524 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
525 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000526 // We found a compatible struct; per the standard, this initializes the
527 // struct. (The C standard technically says that this only applies for
528 // initializers for declarations with automatic scope; however, this
529 // construct is unambiguous anyway because a struct cannot contain
530 // a type compatible with itself. We'll output an error when we check
531 // if the initializer is constant.)
532 // FIXME: Is a call to CheckSingleInitializer required here?
533 ++startIndex;
534 } else {
535 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000536
Steve Naroff406db932008-02-11 21:52:37 +0000537 // If the record is invalid, some of it's members are invalid. To avoid
538 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000539 if (structDecl->isInvalidDecl())
540 return true;
541
Steve Naroffa9960332008-01-25 00:51:06 +0000542 // If structDecl is a forward declaration, this loop won't do anything;
543 // That's okay, because an error should get printed out elsewhere. It
544 // might be worthwhile to skip over the rest of the initializer, though.
545 int numMembers = structDecl->getNumMembers() -
546 structDecl->hasFlexibleArrayMember();
547 for (int i = 0; i < numMembers; i++) {
548 // Don't attempt to go past the end of the init list
549 if (startIndex >= IList->getNumInits())
550 break;
551 FieldDecl * curField = structDecl->getMember(i);
552 if (!curField->getIdentifier()) {
553 // Don't initialize unnamed fields, e.g. "int : 20;"
554 continue;
555 }
556 QualType fieldType = curField->getType();
557 Expr* expr = IList->getInit(startIndex);
558 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
559 unsigned newStart = 0;
560 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
561 true, newStart);
562 ++startIndex;
563 } else {
564 hadError |= CheckInitializerListTypes(IList, fieldType,
565 false, startIndex);
566 }
567 if (DeclType->isUnionType())
568 break;
569 }
570 // FIXME: Implement flexible array initialization GCC extension (it's a
571 // really messy extension to implement, unfortunately...the necessary
572 // information isn't actually even here!)
573 }
574 } else if (DeclType->isArrayType()) {
575 // Check for the special-case of initializing an array with a string.
576 if (startIndex < IList->getNumInits()) {
577 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
578 DeclType)) {
579 CheckStringLiteralInit(lit, DeclType);
580 ++startIndex;
581 if (topLevel && startIndex < IList->getNumInits()) {
582 // We have leftover initializers; warn
583 Diag(IList->getInit(startIndex)->getLocStart(),
584 diag::err_excess_initializers_in_char_array_initializer,
585 IList->getInit(startIndex)->getSourceRange());
586 }
587 return false;
588 }
589 }
590 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000591 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000592 // FIXME: use a proper constant
593 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000594 } else if (const VariableArrayType *VAT =
595 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000596 // Check for VLAs; in standard C it would be possible to check this
597 // earlier, but I don't know where clang accepts VLAs (gcc accepts
598 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000599 Diag(VAT->getSizeExpr()->getLocStart(),
600 diag::err_variable_object_no_init,
601 VAT->getSizeExpr()->getSourceRange());
602 hadError = true;
603 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000604 } else {
605 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
606 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
607 }
608 QualType elementType = DeclType->getAsArrayType()->getElementType();
609 int numElements = 0;
610 for (int i = 0; i < maxElements; ++i, ++numElements) {
611 // Don't attempt to go past the end of the init list
612 if (startIndex >= IList->getNumInits())
613 break;
614 Expr* expr = IList->getInit(startIndex);
615 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
616 unsigned newIndex = 0;
617 hadError |= CheckInitializerListTypes(SubInitList, elementType,
618 true, newIndex);
619 ++startIndex;
620 } else {
621 hadError |= CheckInitializerListTypes(IList, elementType,
622 false, startIndex);
623 }
624 }
Eli Friedman9db13972008-02-15 12:53:51 +0000625 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000626 // If this is an incomplete array type, the actual type needs to
627 // be calculated here
628 if (numElements == 0) {
629 // Sizing an array implicitly to zero is not allowed
630 // (It could in theory be allowed, but it doesn't really matter.)
631 Diag(IList->getLocStart(),
632 diag::err_at_least_one_initializer_needed_to_size_array);
633 hadError = true;
634 } else {
635 llvm::APSInt ConstVal(32);
636 ConstVal = numElements;
637 DeclType = Context.getConstantArrayType(elementType, ConstVal,
638 ArrayType::Normal, 0);
639 }
640 }
641 } else {
642 assert(0 && "Aggregate that isn't a function or array?!");
643 }
644 } else {
645 // In C, all types are either scalars or aggregates, but
646 // additional handling is needed here for C++ (and possibly others?).
647 assert(0 && "Unsupported initializer type");
648 }
649
650 // If this init list is a base list, we set the type; an initializer doesn't
651 // fundamentally have a type, but this makes the ASTs a bit easier to read
652 if (topLevel)
653 IList->setType(DeclType);
654
655 if (topLevel && startIndex < IList->getNumInits()) {
656 // We have leftover initializers; warn
657 Diag(IList->getInit(startIndex)->getLocStart(),
658 diag::warn_excess_initializers,
659 IList->getInit(startIndex)->getSourceRange());
660 }
661 return hadError;
662}
663
664bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000665 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
666 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000667 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000668 return Diag(VAT->getSizeExpr()->getLocStart(),
669 diag::err_variable_object_no_init,
670 VAT->getSizeExpr()->getSourceRange());
671
Steve Naroff2fdc3742007-12-10 22:44:33 +0000672 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
673 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000674 // FIXME: Handle wide strings
675 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
676 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000677
678 if (DeclType->isArrayType())
679 return Diag(Init->getLocStart(),
680 diag::err_array_init_list_required,
681 Init->getSourceRange());
682
Steve Naroffd0091aa2008-01-10 22:15:12 +0000683 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000684 }
Steve Naroffa9960332008-01-25 00:51:06 +0000685 unsigned newIndex = 0;
686 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000687}
688
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000689Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000690Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000691 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 IdentifierInfo *II = D.getIdentifier();
693
Chris Lattnere80a59c2007-07-25 00:24:17 +0000694 // All of these full declarators require an identifier. If it doesn't have
695 // one, the ParsedFreeStandingDeclSpec action should be used.
696 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000697 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000698 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000699 D.getDeclSpec().getSourceRange(), D.getSourceRange());
700 return 0;
701 }
702
Chris Lattner31e05722007-08-26 06:24:45 +0000703 // The scope passed in may not be a decl scope. Zip up the scope tree until
704 // we find one that is.
705 while ((S->getFlags() & Scope::DeclScope) == 0)
706 S = S->getParent();
707
Reid Spencer5f016e22007-07-11 17:01:13 +0000708 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000709 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
710 D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000711 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000712 bool InvalidDecl = false;
713
Chris Lattner41af0932007-11-14 06:34:38 +0000714 QualType R = GetTypeForDeclarator(D, S);
715 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000718 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 if (!NewTD) return 0;
720
721 // Handle attributes prior to checking for duplicates in MergeVarDecl
722 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
723 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000724 // Merge the decl with the existing one if appropriate. If the decl is
725 // in an outer scope, it isn't the same thing.
726 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
728 if (NewTD == 0) return 0;
729 }
730 New = NewTD;
731 if (S->getParent() == 0) {
732 // C99 6.7.7p2: If a typedef name specifies a variably modified type
733 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000734 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
735 // FIXME: Diagnostic needs to be fixed.
736 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000737 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000738 }
739 }
Chris Lattner41af0932007-11-14 06:34:38 +0000740 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000741 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 switch (D.getDeclSpec().getStorageClassSpec()) {
743 default: assert(0 && "Unknown storage class!");
744 case DeclSpec::SCS_auto:
745 case DeclSpec::SCS_register:
746 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
747 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000748 InvalidDecl = true;
749 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
751 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
752 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000753 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 }
755
756 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000757 D.getDeclSpec().isInlineSpecified(),
Anders Carlssonf78915f2008-02-15 07:04:12 +0000758 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000759 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000760 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
761 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +0000762
Steve Naroffffce4d52008-01-09 23:34:55 +0000763 // Merge the decl with the existing one if appropriate. Since C functions
764 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 if (PrevDecl) {
766 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
767 if (NewFD == 0) return 0;
768 }
769 New = NewFD;
770 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000771 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000772 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
773 D.getIdentifier()->getName());
774 InvalidDecl = true;
775 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000776
777 VarDecl *NewVD;
778 VarDecl::StorageClass SC;
779 switch (D.getDeclSpec().getStorageClassSpec()) {
780 default: assert(0 && "Unknown storage class!");
Steve Naroffd6326c62008-01-25 22:14:40 +0000781 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
782 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
783 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
784 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
785 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
786 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 }
788 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 // C99 6.9p2: The storage-class specifiers auto and register shall not
790 // appear in the declaration specifiers in an external declaration.
791 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
792 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
793 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000794 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000797 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000799 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 // Handle attributes prior to checking for duplicates in MergeVarDecl
801 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
802 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000803
804 // Emit an error if an address space was applied to decl with local storage.
805 // This includes arrays of objects with address space qualifiers, but not
806 // automatic variables that point to other address spaces.
807 // ISO/IEC TR 18037 S5.1.2
808 if (NewVD->hasLocalStorage()) {
809 QualType AutoTy = NewVD->getCanonicalType();
810 if (const ArrayType *AT = AutoTy->getAsArrayType())
811 AutoTy = AT->getElementType().getCanonicalType();
812 if (AutoTy.getAddressSpace() != 0) {
813 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
814 InvalidDecl = true;
815 }
Nate Begeman5af27e02008-03-14 00:22:18 +0000816 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000817 // Merge the decl with the existing one if appropriate. If the decl is
818 // in an outer scope, it isn't the same thing.
819 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 NewVD = MergeVarDecl(NewVD, PrevDecl);
821 if (NewVD == 0) return 0;
822 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 New = NewVD;
824 }
825
826 // If this has an identifier, add it to the scope stack.
827 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000828 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 II->setFETokenInfo(New);
830 S->AddDecl(New);
831 }
Steve Naroff5912a352007-08-28 20:14:24 +0000832 // If any semantic error occurred, mark the decl as invalid.
833 if (D.getInvalidType() || InvalidDecl)
834 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
836 return New;
837}
838
Steve Naroffd0091aa2008-01-10 22:15:12 +0000839bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
840 SourceLocation loc;
841 // FIXME: Remove the isReference check and handle assignment to a reference.
842 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
843 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
844 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
845 return true;
846 }
847 return false;
848}
849
Steve Naroffbb204692007-09-12 14:07:44 +0000850void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000851 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000852 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000853 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000854
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000855 // If there is no declaration, there was an error parsing it. Just ignore
856 // the initializer.
857 if (RealDecl == 0) {
858 delete Init;
859 return;
860 }
Steve Naroffbb204692007-09-12 14:07:44 +0000861
Steve Naroff410e3e22007-09-12 20:13:48 +0000862 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
863 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000864 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
865 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000866 RealDecl->setInvalidDecl();
867 return;
868 }
Steve Naroffbb204692007-09-12 14:07:44 +0000869 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000870 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000871 QualType DclT = VDecl->getType(), SavT = DclT;
872 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000873 VarDecl::StorageClass SC = BVD->getStorageClass();
874 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000875 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000876 BVD->setInvalidDecl();
877 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000878 if (CheckInitializerTypes(Init, DclT))
879 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000880 if (SC == VarDecl::Static) // C99 6.7.8p4.
881 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000882 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000883 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000884 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000885 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000886 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000887 if (CheckInitializerTypes(Init, DclT))
888 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000889
890 // C99 6.7.8p4. All file scoped initializers need to be constant.
891 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000892 }
893 // If the type changed, it means we had an incomplete type that was
894 // completed by the initializer. For example:
895 // int ary[] = { 1, 3, 5 };
896 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000897 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000898 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000899 Init->setType(DclT);
900 }
Steve Naroffbb204692007-09-12 14:07:44 +0000901
902 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000903 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000904 return;
905}
906
Reid Spencer5f016e22007-07-11 17:01:13 +0000907/// The declarators are chained together backwards, reverse the list.
908Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
909 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000910 Decl *GroupDecl = static_cast<Decl*>(group);
911 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000912 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000913
914 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
915 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000916 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000918 else { // reverse the list.
919 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000920 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000921 Group->setNextDeclarator(NewGroup);
922 NewGroup = Group;
923 Group = Next;
924 }
925 }
926 // Perform semantic analysis that depends on having fully processed both
927 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000928 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000929 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
930 if (!IDecl)
931 continue;
932 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
933 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
934 QualType T = IDecl->getType();
935
936 // C99 6.7.5.2p2: If an identifier is declared to be an object with
937 // static storage duration, it shall not have a variable length array.
938 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +0000939 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000940 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
941 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +0000942 }
943 }
944 // Block scope. C99 6.7p7: If an identifier for an object is declared with
945 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
946 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
947 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000948 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
949 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000950 IDecl->setInvalidDecl();
951 }
952 }
953 // File scope. C99 6.9.2p2: A declaration of an identifier for and
954 // object that has file scope without an initializer, and without a
955 // storage-class specifier or with the storage-class specifier "static",
956 // constitutes a tentative definition. Note: A tentative definition with
957 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000958 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
959 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +0000960 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000961 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
962 // array to be completed. Don't issue a diagnostic.
963 } else if (T->isIncompleteType()) {
964 // C99 6.9.2p3: If the declaration of an identifier for an object is
965 // a tentative definition and has internal linkage (C99 6.2.2p3), the
966 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000967 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
968 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000969 IDecl->setInvalidDecl();
970 }
971 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 }
973 return NewGroup;
974}
Steve Naroffe1223f72007-08-28 03:03:08 +0000975
976// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000977ParmVarDecl *
Nate Begeman6d20d032008-02-17 21:02:04 +0000978Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
979 Scope *FnScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000980 IdentifierInfo *II = PI.Ident;
981 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
982 // Can this happen for params? We already checked that they don't conflict
983 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000984 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 PI.IdentLoc, FnScope)) {
986
987 }
988
989 // FIXME: Handle storage class (auto, register). No declarator?
990 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000991
992 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
993 // Doing the promotion here has a win and a loss. The win is the type for
994 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
995 // code generator). The loss is the orginal type isn't preserved. For example:
996 //
997 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
998 // int blockvardecl[5];
999 // sizeof(parmvardecl); // size == 4
1000 // sizeof(blockvardecl); // size == 20
1001 // }
1002 //
1003 // For expressions, all implicit conversions are captured using the
1004 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1005 //
1006 // FIXME: If a source translation tool needs to see the original type, then
1007 // we need to consider storing both types (in ParmVarDecl)...
1008 //
1009 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +00001010 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
1011 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001012 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +00001013 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
1014 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001015 parmDeclType = Context.getPointerType(parmDeclType);
1016
1017 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Anders Carlssonf78915f2008-02-15 07:04:12 +00001018 VarDecl::None, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001019
Steve Naroff53a32342007-08-28 18:45:29 +00001020 if (PI.InvalidType)
1021 New->setInvalidDecl();
1022
Reid Spencer5f016e22007-07-11 17:01:13 +00001023 // If this has an identifier, add it to the scope stack.
1024 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001025 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001026 II->setFETokenInfo(New);
1027 FnScope->AddDecl(New);
1028 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001029
1030 HandleDeclAttributes(New, PI.AttrList, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 return New;
1032}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001033
Chris Lattnerb652cea2007-10-09 17:14:05 +00001034Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001035 assert(CurFunctionDecl == 0 && "Function parsing confused");
1036 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1037 "Not a function declarator!");
1038 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1039
1040 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1041 // for a K&R function.
1042 if (!FTI.hasPrototype) {
1043 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1044 if (FTI.ArgInfo[i].TypeInfo == 0) {
1045 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1046 FTI.ArgInfo[i].Ident->getName());
1047 // Implicitly declare the argument as type 'int' for lack of a better
1048 // type.
1049 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1050 }
1051 }
Chris Lattner52804082008-02-17 19:31:09 +00001052
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 // Since this is a function definition, act as though we have information
1054 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001055 if (FTI.NumArgs)
1056 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001057 } else {
1058 // FIXME: Diagnose arguments without names in C.
1059
1060 }
1061
1062 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001063
1064 // See if this is a redefinition.
1065 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1066 D.getIdentifierLoc(), GlobalScope);
1067 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1068 if (FD->getBody()) {
1069 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1070 D.getIdentifier()->getName());
1071 Diag(FD->getLocation(), diag::err_previous_definition);
1072 }
1073 }
Steve Narofffabbc342008-02-12 01:09:36 +00001074 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001075 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 CurFunctionDecl = FD;
1077
1078 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1079 llvm::SmallVector<ParmVarDecl*, 16> Params;
1080
1081 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1082 // no arguments, not a function that takes a single void argument.
1083 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerf46699c2008-02-20 20:55:12 +00001084 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001085 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // empty arg list, don't push any params.
1087 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001088 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begemanbff5f5c2007-11-13 21:49:48 +00001089 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff66499922007-11-12 03:44:46 +00001090 FnBodyScope));
1091 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 }
1093
1094 FD->setParams(&Params[0], Params.size());
1095
1096 return FD;
1097}
1098
Steve Naroffd6d054d2007-11-11 23:20:51 +00001099Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1100 Decl *dcl = static_cast<Decl *>(D);
1101 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1102 FD->setBody((Stmt*)Body);
1103 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001104 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001105 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001106 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001107 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001108 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001109 // Verify and clean out per-function state.
1110
1111 // Check goto/label use.
1112 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1113 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1114 // Verify that we have no forward references left. If so, there was a goto
1115 // or address of a label taken, but no definition of it. Label fwd
1116 // definitions are indicated with a null substmt.
1117 if (I->second->getSubStmt() == 0) {
1118 LabelStmt *L = I->second;
1119 // Emit error.
1120 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1121
1122 // At this point, we have gotos that use the bogus label. Stitch it into
1123 // the function body so that they aren't leaked and that the AST is well
1124 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001125 if (Body) {
1126 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1127 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1128 } else {
1129 // The whole function wasn't parsed correctly, just delete this.
1130 delete L;
1131 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
1133 }
1134 LabelMap.clear();
1135
Steve Naroffd6d054d2007-11-11 23:20:51 +00001136 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001137}
1138
Reid Spencer5f016e22007-07-11 17:01:13 +00001139/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1140/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001141ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1142 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001143 if (getLangOptions().C99) // Extension in C99.
1144 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1145 else // Legal in C90, but warn about it.
1146 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1147
1148 // FIXME: handle stuff like:
1149 // void foo() { extern float X(); }
1150 // void bar() { X(); } <-- implicit decl for X in another scope.
1151
1152 // Set a Declarator for the implicit definition: int foo();
1153 const char *Dummy;
1154 DeclSpec DS;
1155 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1156 Error = Error; // Silence warning.
1157 assert(!Error && "Error setting up implicit decl!");
1158 Declarator D(DS, Declarator::BlockContext);
1159 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1160 D.SetIdentifier(&II, Loc);
1161
1162 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001163 if (Scope *FnS = S->getFnParent())
1164 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 while (S->getParent())
1166 S = S->getParent();
1167
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001168 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001169}
1170
1171
Chris Lattner41af0932007-11-14 06:34:38 +00001172TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001173 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001175 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001176
1177 // Scope manipulation handled by caller.
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001178 TypedefDecl *NewTD = TypedefDecl::Create(D.getIdentifierLoc(),
1179 D.getIdentifier(),
1180 T, LastDeclarator, Context);
Steve Naroff5912a352007-08-28 20:14:24 +00001181 if (D.getInvalidType())
1182 NewTD->setInvalidDecl();
1183 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001184}
1185
Steve Naroff08d92e42007-09-15 18:49:24 +00001186/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001187/// former case, Name will be non-null. In the later case, Name will be null.
1188/// TagType indicates what kind of tag this is. TK indicates whether this is a
1189/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001190Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 SourceLocation KWLoc, IdentifierInfo *Name,
1192 SourceLocation NameLoc, AttributeList *Attr) {
1193 // If this is a use of an existing tag, it must have a name.
1194 assert((Name != 0 || TK == TK_Definition) &&
1195 "Nameless record must be a definition!");
1196
1197 Decl::Kind Kind;
1198 switch (TagType) {
1199 default: assert(0 && "Unknown tag type!");
1200 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1201 case DeclSpec::TST_union: Kind = Decl::Union; break;
1202//case DeclSpec::TST_class: Kind = Decl::Class; break;
1203 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1204 }
1205
1206 // If this is a named struct, check to see if there was a previous forward
1207 // declaration or definition.
1208 if (TagDecl *PrevDecl =
1209 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1210 NameLoc, S))) {
1211
1212 // If this is a use of a previous tag, or if the tag is already declared in
1213 // the same scope (so that the definition/declaration completes or
1214 // rementions the tag), reuse the decl.
1215 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1216 // Make sure that this wasn't declared as an enum and now used as a struct
1217 // or something similar.
1218 if (PrevDecl->getKind() != Kind) {
1219 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1220 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1221 }
1222
1223 // If this is a use or a forward declaration, we're good.
1224 if (TK != TK_Definition)
1225 return PrevDecl;
1226
1227 // Diagnose attempts to redefine a tag.
1228 if (PrevDecl->isDefinition()) {
1229 Diag(NameLoc, diag::err_redefinition, Name->getName());
1230 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1231 // If this is a redefinition, recover by making this struct be
1232 // anonymous, which will make any later references get the previous
1233 // definition.
1234 Name = 0;
1235 } else {
1236 // Okay, this is definition of a previously declared or referenced tag.
1237 // Move the location of the decl to be the definition site.
1238 PrevDecl->setLocation(NameLoc);
1239 return PrevDecl;
1240 }
1241 }
1242 // If we get here, this is a definition of a new struct type in a nested
1243 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1244 // type.
1245 }
1246
1247 // If there is an identifier, use the location of the identifier as the
1248 // location of the decl, otherwise use the location of the struct/union
1249 // keyword.
1250 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1251
1252 // Otherwise, if this is the first time we've seen this tag, create the decl.
1253 TagDecl *New;
1254 switch (Kind) {
1255 default: assert(0 && "Unknown tag kind!");
1256 case Decl::Enum:
1257 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1258 // enum X { A, B, C } D; D should chain to X.
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001259 New = EnumDecl::Create(Loc, Name, 0, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 // If this is an undefined enum, warn.
1261 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1262 break;
1263 case Decl::Union:
1264 case Decl::Struct:
1265 case Decl::Class:
1266 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1267 // struct X { int A; } D; D should chain to X.
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001268 New = RecordDecl::Create(Kind, Loc, Name, 0, Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 break;
1270 }
1271
1272 // If this has an identifier, add it to the scope stack.
1273 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001274 // The scope passed in may not be a decl scope. Zip up the scope tree until
1275 // we find one that is.
1276 while ((S->getFlags() & Scope::DeclScope) == 0)
1277 S = S->getParent();
1278
1279 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001280 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 Name->setFETokenInfo(New);
1282 S->AddDecl(New);
1283 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001284
Anders Carlssonad148062008-02-16 00:29:18 +00001285 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 return New;
1287}
1288
Steve Naroff08d92e42007-09-15 18:49:24 +00001289/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001290/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001291Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001292 SourceLocation DeclStart,
1293 Declarator &D, ExprTy *BitfieldWidth) {
1294 IdentifierInfo *II = D.getIdentifier();
1295 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 SourceLocation Loc = DeclStart;
1297 if (II) Loc = D.getIdentifierLoc();
1298
1299 // FIXME: Unnamed fields can be handled in various different ways, for
1300 // example, unnamed unions inject all members into the struct namespace!
1301
1302
1303 if (BitWidth) {
1304 // TODO: Validate.
1305 //printf("WARNING: BITFIELDS IGNORED!\n");
1306
1307 // 6.7.2.1p3
1308 // 6.7.2.1p4
1309
1310 } else {
1311 // Not a bitfield.
1312
1313 // validate II.
1314
1315 }
1316
1317 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001318 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1319 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001320
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1322 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001323 if (T->isVariablyModifiedType()) {
1324 // FIXME: This diagnostic needs work
1325 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001326 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001328 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001329 FieldDecl *NewFD;
1330
1331 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patel54e62352007-11-01 16:29:56 +00001332 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001333 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1334 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1335 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001336 // FIXME: ivars are currently used to model properties, and
1337 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001338 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1339 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1340 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001341 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001342 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001343
Anders Carlssonad148062008-02-16 00:29:18 +00001344 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1345 D.getAttributes());
1346
Steve Naroff5912a352007-08-28 20:14:24 +00001347 if (D.getInvalidType() || InvalidDecl)
1348 NewFD->setInvalidDecl();
1349 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001350}
1351
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001352/// TranslateIvarVisibility - Translate visibility from a token ID to an
1353/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001354static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001355TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001356 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001357 case tok::objc_private: return ObjCIvarDecl::Private;
1358 case tok::objc_public: return ObjCIvarDecl::Public;
1359 case tok::objc_protected: return ObjCIvarDecl::Protected;
1360 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001361 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001362 }
1363}
1364
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001365void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001366 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001367 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001368 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001369 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001370 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1371 assert(EnclosingDecl && "missing record or interface decl");
1372 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1373
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001374 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 // Diagnose code like:
1376 // struct S { struct S {} X; };
1377 // We discover this when we complete the outer S. Reject and ignore the
1378 // outer S.
1379 Diag(Record->getLocation(), diag::err_nested_redefinition,
1380 Record->getKindName());
1381 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001382 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 return;
1384 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 // Verify that all the fields are okay.
1386 unsigned NumNamedMembers = 0;
1387 llvm::SmallVector<FieldDecl*, 32> RecFields;
1388 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001389
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001391
Steve Naroff74216642007-09-14 22:20:54 +00001392 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1393 assert(FD && "missing field decl");
1394
1395 // Remember all fields.
1396 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001397
1398 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001399 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001400
Steve Narofff13271f2007-09-14 23:09:53 +00001401 // If we have visibility info, make sure the AST is set accordingly.
1402 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001403 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001404 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001405
Reid Spencer5f016e22007-07-11 17:01:13 +00001406 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001407 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001408 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001410 FD->setInvalidDecl();
1411 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001412 continue;
1413 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1415 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001416 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001417 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001418 FD->setInvalidDecl();
1419 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001420 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001421 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001422 if (i != NumFields-1 || // ... that the last member ...
1423 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001424 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001426 FD->setInvalidDecl();
1427 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 continue;
1429 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001430 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1432 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001433 FD->setInvalidDecl();
1434 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 continue;
1436 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001437 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001438 if (Record)
1439 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1442 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001443 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1445 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001446 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 Record->setHasFlexibleArrayMember(true);
1448 } else {
1449 // If this is a struct/class and this is not the last element, reject
1450 // it. Note that GCC supports variable sized arrays in the middle of
1451 // structures.
1452 if (i != NumFields-1) {
1453 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1454 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001455 FD->setInvalidDecl();
1456 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 continue;
1458 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 // We support flexible arrays at the end of structs in other structs
1460 // as an extension.
1461 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1462 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001463 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001464 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465 }
1466 }
1467 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001468 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001469 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001470 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1471 FD->getName());
1472 FD->setInvalidDecl();
1473 EnclosingDecl->setInvalidDecl();
1474 continue;
1475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // Keep track of the number of named members.
1477 if (IdentifierInfo *II = FD->getIdentifier()) {
1478 // Detect duplicate member names.
1479 if (!FieldIDs.insert(II)) {
1480 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1481 // Find the previous decl.
1482 SourceLocation PrevLoc;
1483 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1484 assert(i != e && "Didn't find previous def!");
1485 if (RecFields[i]->getIdentifier() == II) {
1486 PrevLoc = RecFields[i]->getLocation();
1487 break;
1488 }
1489 }
1490 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001491 FD->setInvalidDecl();
1492 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001493 continue;
1494 }
1495 ++NumNamedMembers;
1496 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 }
1498
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001500 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001501 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001502 Consumer.HandleTagDeclDefinition(Record);
1503 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001504 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1505 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1506 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1507 else if (ObjCImplementationDecl *IMPDecl =
1508 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001509 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1510 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001511 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001512 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001513 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001514}
1515
Steve Naroff08d92e42007-09-15 18:49:24 +00001516Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 DeclTy *lastEnumConst,
1518 SourceLocation IdLoc, IdentifierInfo *Id,
1519 SourceLocation EqualLoc, ExprTy *val) {
1520 theEnumDecl = theEnumDecl; // silence unused warning.
1521 EnumConstantDecl *LastEnumConst =
1522 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1523 Expr *Val = static_cast<Expr*>(val);
1524
Chris Lattner31e05722007-08-26 06:24:45 +00001525 // The scope passed in may not be a decl scope. Zip up the scope tree until
1526 // we find one that is.
1527 while ((S->getFlags() & Scope::DeclScope) == 0)
1528 S = S->getParent();
1529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 // Verify that there isn't already something declared with this name in this
1531 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001532 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1533 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 if (S->isDeclScope(PrevDecl)) {
1535 if (isa<EnumConstantDecl>(PrevDecl))
1536 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1537 else
1538 Diag(IdLoc, diag::err_redefinition, Id->getName());
1539 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001540 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 return 0;
1542 }
1543 }
1544
1545 llvm::APSInt EnumVal(32);
1546 QualType EltTy;
1547 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001548 // Make sure to promote the operand type to int.
1549 UsualUnaryConversions(Val);
1550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1552 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001553 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1555 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001556 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001557 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001558 } else {
1559 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001561 }
1562
1563 if (!Val) {
1564 if (LastEnumConst) {
1565 // Assign the last value + 1.
1566 EnumVal = LastEnumConst->getInitVal();
1567 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001568
1569 // Check for overflow on increment.
1570 if (EnumVal < LastEnumConst->getInitVal())
1571 Diag(IdLoc, diag::warn_enum_value_overflow);
1572
Chris Lattnerb7416f92007-08-27 17:37:24 +00001573 EltTy = LastEnumConst->getType();
1574 } else {
1575 // First value, set to zero.
1576 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001577 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001578 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 }
1580
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001581 EnumConstantDecl *New =
1582 EnumConstantDecl::Create(IdLoc, Id, EltTy, Val, EnumVal, LastEnumConst,
1583 Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00001584
1585 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001586 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 Id->setFETokenInfo(New);
1588 S->AddDecl(New);
1589 return New;
1590}
1591
Steve Naroff08d92e42007-09-15 18:49:24 +00001592void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001593 DeclTy **Elements, unsigned NumElements) {
1594 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1595 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1596
Chris Lattnere37f0be2007-08-28 05:10:31 +00001597 // TODO: If the result value doesn't fit in an int, it must be a long or long
1598 // long value. ISO C does not support this, but GCC does as an extension,
1599 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001600 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001601
Chris Lattnerac609682007-08-28 06:15:15 +00001602 // Verify that all the values are okay, compute the size of the values, and
1603 // reverse the list.
1604 unsigned NumNegativeBits = 0;
1605 unsigned NumPositiveBits = 0;
1606
1607 // Keep track of whether all elements have type int.
1608 bool AllElementsInt = true;
1609
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 EnumConstantDecl *EltList = 0;
1611 for (unsigned i = 0; i != NumElements; ++i) {
1612 EnumConstantDecl *ECD =
1613 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1614 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001615
1616 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001617 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001618 assert(InitVal.getBitWidth() >= IntWidth &&
1619 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001620 if (InitVal.getBitWidth() > IntWidth) {
1621 llvm::APSInt V(InitVal);
1622 V.trunc(IntWidth);
1623 V.extend(InitVal.getBitWidth());
1624 if (V != InitVal)
1625 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1626 InitVal.toString());
1627 }
Chris Lattnerac609682007-08-28 06:15:15 +00001628
1629 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001630 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001631 NumPositiveBits = std::max(NumPositiveBits,
1632 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001633 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001634 NumNegativeBits = std::max(NumNegativeBits,
1635 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001636
Chris Lattnerac609682007-08-28 06:15:15 +00001637 // Keep track of whether every enum element has type int (very commmon).
1638 if (AllElementsInt)
1639 AllElementsInt = ECD->getType() == Context.IntTy;
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 ECD->setNextDeclarator(EltList);
1642 EltList = ECD;
1643 }
1644
Chris Lattnerac609682007-08-28 06:15:15 +00001645 // Figure out the type that should be used for this enum.
1646 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1647 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001648 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001649
1650 if (NumNegativeBits) {
1651 // If there is a negative value, figure out the smallest integer type (of
1652 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001653 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001654 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001655 BestWidth = IntWidth;
1656 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001657 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001658
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001659 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001660 BestType = Context.LongTy;
1661 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001662 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001663
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 <=
Chris Lattner98be4942008-03-05 18:54:05 +00001676 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001677 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001678 } else {
1679 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001680 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001681 "How could an initializer get larger than ULL?");
1682 BestType = Context.UnsignedLongLongTy;
1683 }
1684 }
1685
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001686 // Loop over all of the enumerator constants, changing their types to match
1687 // the type of the enum if needed.
1688 for (unsigned i = 0; i != NumElements; ++i) {
1689 EnumConstantDecl *ECD =
1690 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1691 if (!ECD) continue; // Already issued a diagnostic.
1692
1693 // Standard C says the enumerators have int type, but we allow, as an
1694 // extension, the enumerators to be larger than int size. If each
1695 // enumerator value fits in an int, type it as an int, otherwise type it the
1696 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1697 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001698 if (ECD->getType() == Context.IntTy) {
1699 // Make sure the init value is signed.
1700 llvm::APSInt IV = ECD->getInitVal();
1701 IV.setIsSigned(true);
1702 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001703 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001704 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001705
1706 // Determine whether the value fits into an int.
1707 llvm::APSInt InitVal = ECD->getInitVal();
1708 bool FitsInInt;
1709 if (InitVal.isUnsigned() || !InitVal.isNegative())
1710 FitsInInt = InitVal.getActiveBits() < IntWidth;
1711 else
1712 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1713
1714 // If it fits into an integer type, force it. Otherwise force it to match
1715 // the enum decl type.
1716 QualType NewTy;
1717 unsigned NewWidth;
1718 bool NewSign;
1719 if (FitsInInt) {
1720 NewTy = Context.IntTy;
1721 NewWidth = IntWidth;
1722 NewSign = true;
1723 } else if (ECD->getType() == BestType) {
1724 // Already the right type!
1725 continue;
1726 } else {
1727 NewTy = BestType;
1728 NewWidth = BestWidth;
1729 NewSign = BestType->isSignedIntegerType();
1730 }
1731
1732 // Adjust the APSInt value.
1733 InitVal.extOrTrunc(NewWidth);
1734 InitVal.setIsSigned(NewSign);
1735 ECD->setInitVal(InitVal);
1736
1737 // Adjust the Expr initializer and type.
1738 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1739 ECD->setType(NewTy);
1740 }
Chris Lattnerac609682007-08-28 06:15:15 +00001741
Chris Lattnere00b18c2007-08-28 18:24:31 +00001742 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001743 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001744}
1745
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001746Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1747 ExprTy *expr) {
1748 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1749
1750 return new FileScopeAsmDecl(Loc, AsmString);
1751}
1752
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001753Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001754 SourceLocation LBrace,
1755 SourceLocation RBrace,
1756 const char *Lang,
1757 unsigned StrSize,
1758 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001759 LinkageSpecDecl::LanguageIDs Language;
1760 Decl *dcl = static_cast<Decl *>(D);
1761 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1762 Language = LinkageSpecDecl::lang_c;
1763 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1764 Language = LinkageSpecDecl::lang_cxx;
1765 else {
1766 Diag(Loc, diag::err_bad_language);
1767 return 0;
1768 }
1769
1770 // FIXME: Add all the various semantics of linkage specifications
1771 return new LinkageSpecDecl(Loc, Language, dcl);
1772}
1773
Chris Lattner74788ba2008-02-21 00:48:22 +00001774void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001775
Chris Lattner74788ba2008-02-21 00:48:22 +00001776 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001777 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001779 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 if (!newType.isNull()) // install the new vector type into the decl
1781 vDecl->setType(newType);
1782 }
1783 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1784 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001785 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 if (!newType.isNull()) // install the new vector type into the decl
1787 tDecl->setUnderlyingType(newType);
1788 }
Chris Lattner212839c2008-02-20 23:17:35 +00001789 break;
1790 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001791 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001792 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001793 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001794 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001795 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001796 break;
1797 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001798 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1799 QualType newType = HandleAddressSpaceTypeAttribute(
1800 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001801 Attr);
1802 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001803 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1804 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001805 Attr);
1806 // install the new addr spaced type into the decl
1807 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001808 }
Chris Lattner212839c2008-02-20 23:17:35 +00001809 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001810 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001811 HandleDeprecatedAttribute(New, Attr);
1812 break;
1813 case AttributeList::AT_visibility:
1814 HandleVisibilityAttribute(New, Attr);
1815 break;
1816 case AttributeList::AT_weak:
1817 HandleWeakAttribute(New, Attr);
1818 break;
1819 case AttributeList::AT_dllimport:
1820 HandleDLLImportAttribute(New, Attr);
1821 break;
1822 case AttributeList::AT_dllexport:
1823 HandleDLLExportAttribute(New, Attr);
1824 break;
1825 case AttributeList::AT_nothrow:
1826 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001827 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001828 case AttributeList::AT_stdcall:
1829 HandleStdCallAttribute(New, Attr);
1830 break;
1831 case AttributeList::AT_fastcall:
1832 HandleFastCallAttribute(New, Attr);
1833 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001834 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001835 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001836 break;
1837 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001838 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001839 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001840 case AttributeList::AT_annotate:
1841 HandleAnnotateAttribute(New, Attr);
1842 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001843 case AttributeList::AT_noreturn:
1844 HandleNoReturnAttribute(New, Attr);
1845 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001846 case AttributeList::AT_format:
1847 HandleFormatAttribute(New, Attr);
1848 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001849 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001850#if 0
1851 // TODO: when we have the full set of attributes, warn about unknown ones.
1852 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1853 Attr->getName()->getName());
1854#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001855 break;
1856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001857}
1858
1859void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1860 AttributeList *declarator_postfix) {
1861 while (declspec_prefix) {
1862 HandleDeclAttribute(New, declspec_prefix);
1863 declspec_prefix = declspec_prefix->getNext();
1864 }
1865 while (declarator_postfix) {
1866 HandleDeclAttribute(New, declarator_postfix);
1867 declarator_postfix = declarator_postfix->getNext();
1868 }
1869}
1870
Steve Naroffbea0b342007-07-29 16:33:31 +00001871void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1872 AttributeList *rawAttr) {
1873 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001874 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001875 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001876 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00001877 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001878 return;
Steve Naroff73322922007-07-18 18:00:27 +00001879 }
1880 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1881 llvm::APSInt vecSize(32);
1882 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001883 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001884 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001885 return;
Steve Naroff73322922007-07-18 18:00:27 +00001886 }
1887 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1888 // in conjunction with complex types (pointers, arrays, functions, etc.).
1889 Type *canonType = curType.getCanonicalType().getTypePtr();
1890 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001891 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00001892 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001893 return;
Steve Naroff73322922007-07-18 18:00:27 +00001894 }
1895 // unlike gcc's vector_size attribute, the size is specified as the
1896 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001897 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001898
1899 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001900 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00001901 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001902 return;
Steve Naroff73322922007-07-18 18:00:27 +00001903 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001904 // Instantiate/Install the vector type, the number of elements is > 0.
1905 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1906 // Remember this typedef decl, we will need it later for diagnostics.
1907 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001908}
1909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001911 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 // check the attribute arugments.
1913 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001914 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 std::string("1"));
1916 return QualType();
1917 }
1918 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1919 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001920 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001921 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001922 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 return QualType();
1924 }
1925 // navigate to the base type - we need to provide for vector pointers,
1926 // vector arrays, and functions returning vectors.
1927 Type *canonType = curType.getCanonicalType().getTypePtr();
1928
Steve Naroff73322922007-07-18 18:00:27 +00001929 if (canonType->isPointerType() || canonType->isArrayType() ||
1930 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001931 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001932 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1933 do {
1934 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1935 canonType = PT->getPointeeType().getTypePtr();
1936 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1937 canonType = AT->getElementType().getTypePtr();
1938 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1939 canonType = FT->getResultType().getTypePtr();
1940 } while (canonType->isPointerType() || canonType->isArrayType() ||
1941 canonType->isFunctionType());
1942 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001943 }
1944 // the base type must be integer or float.
1945 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001946 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00001947 curType.getCanonicalType().getAsString());
1948 return QualType();
1949 }
Chris Lattner98be4942008-03-05 18:54:05 +00001950 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00001951 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001952 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001953
1954 // the vector size needs to be an integral multiple of the type size.
1955 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00001956 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 sizeExpr->getSourceRange());
1958 return QualType();
1959 }
1960 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001961 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 sizeExpr->getSourceRange());
1963 return QualType();
1964 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00001965 // Instantiate the vector type, the number of elements is > 0, and not
1966 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00001967 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001968}
1969
Chris Lattner2070d802008-02-20 23:25:22 +00001970void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00001971 // check the attribute arguments.
1972 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001973 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00001974 std::string("0"));
1975 return;
1976 }
1977
1978 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1979 TD->addAttr(new PackedAttr);
1980 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1981 // If the alignment is less than or equal to 8 bits, the packed attribute
1982 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00001983 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00001984 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00001985 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00001986 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00001987 else
Anders Carlsson425a6092008-02-16 00:39:40 +00001988 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00001989 } else
Chris Lattner2070d802008-02-20 23:25:22 +00001990 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
1991 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00001992}
Nate Begemanc398f0b2008-02-21 19:30:49 +00001993
Ted Kremenekaecb3832008-02-27 20:43:06 +00001994void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
1995 // check the attribute arguments.
1996 if (rawAttr->getNumArgs() != 0) {
1997 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
1998 std::string("0"));
1999 return;
2000 }
2001
Ted Kremenek3465fb32008-03-03 16:52:27 +00002002 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2003
2004 if (!Fn) {
2005 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2006 "noreturn", "function");
2007 return;
2008 }
2009
Ted Kremenekaecb3832008-02-27 20:43:06 +00002010 d->addAttr(new NoReturnAttr());
2011}
2012
Chris Lattnerddee4232008-03-03 03:28:21 +00002013void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2014 // check the attribute arguments.
2015 if (rawAttr->getNumArgs() != 0) {
2016 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2017 std::string("0"));
2018 return;
2019 }
2020
2021 d->addAttr(new DeprecatedAttr());
2022}
2023
2024void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2025 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002026 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002027 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2028 std::string("1"));
2029 return;
2030 }
2031
Chris Lattner7b937ae2008-03-04 18:08:48 +00002032 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2033 Arg = Arg->IgnoreParenCasts();
2034 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2035
2036 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002037 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002038 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002039 return;
2040 }
2041
Chris Lattner7b937ae2008-03-04 18:08:48 +00002042 const char *TypeStr = Str->getStrData();
2043 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002044 llvm::GlobalValue::VisibilityTypes type;
2045
Chris Lattner7b937ae2008-03-04 18:08:48 +00002046 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002047 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002048 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002049 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002050 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002051 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002052 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002053 type = llvm::GlobalValue::ProtectedVisibility;
2054 else {
2055 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002056 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002057 return;
2058 }
2059
2060 d->addAttr(new VisibilityAttr(type));
2061}
2062
2063void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2064 // check the attribute arguments.
2065 if (rawAttr->getNumArgs() != 0) {
2066 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2067 std::string("0"));
2068 return;
2069 }
2070
2071 d->addAttr(new WeakAttr());
2072}
2073
2074void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2075 // check the attribute arguments.
2076 if (rawAttr->getNumArgs() != 0) {
2077 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2078 std::string("0"));
2079 return;
2080 }
2081
2082 d->addAttr(new DLLImportAttr());
2083}
2084
2085void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2086 // check the attribute arguments.
2087 if (rawAttr->getNumArgs() != 0) {
2088 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2089 std::string("0"));
2090 return;
2091 }
2092
2093 d->addAttr(new DLLExportAttr());
2094}
2095
Nate Begeman440b4562008-03-07 20:04:22 +00002096void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2097 // check the attribute arguments.
2098 if (rawAttr->getNumArgs() != 0) {
2099 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2100 std::string("0"));
2101 return;
2102 }
2103
2104 d->addAttr(new StdCallAttr());
2105}
2106
2107void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2108 // check the attribute arguments.
2109 if (rawAttr->getNumArgs() != 0) {
2110 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2111 std::string("0"));
2112 return;
2113 }
2114
2115 d->addAttr(new FastCallAttr());
2116}
2117
Chris Lattnerddee4232008-03-03 03:28:21 +00002118void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2119 // check the attribute arguments.
2120 if (rawAttr->getNumArgs() != 0) {
2121 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2122 std::string("0"));
2123 return;
2124 }
2125
2126 d->addAttr(new NoThrowAttr());
2127}
2128
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002129/// Handle __attribute__((format(type,idx,firstarg))) attributes
2130/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002131void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2132
2133 if (!rawAttr->getParameterName()) {
2134 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2135 "format", std::string("1"));
2136 return;
2137 }
2138
2139 if (rawAttr->getNumArgs() != 2) {
2140 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2141 std::string("3"));
2142 return;
2143 }
2144
2145 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2146 if (!Fn) {
2147 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2148 "format", "function");
2149 return;
2150 }
2151
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002152 const FunctionTypeProto *proto =
2153 dyn_cast<FunctionTypeProto>(Fn->getType()->getAsFunctionType());
2154 if (!proto)
2155 return;
2156
Chris Lattnerddee4232008-03-03 03:28:21 +00002157 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002158 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002159 // the index must start in 1 and the limit is numargs+1
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002160 unsigned NumArgs = Fn->getNumParams();
2161 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002162
2163 const char *Format = rawAttr->getParameterName()->getName();
2164 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2165
2166 // Normalize the argument, __foo__ becomes foo.
2167 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2168 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2169 Format += 2;
2170 FormatLen -= 4;
2171 }
2172
2173 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2174 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2175 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2176 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2177 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2178 "format", rawAttr->getParameterName()->getName());
2179 return;
2180 }
2181
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002182 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002183 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002184 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002185 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2186 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2187 "format", std::string("2"), IdxExpr->getSourceRange());
2188 return;
2189 }
2190
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002191 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002192 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2193 "format", std::string("2"), IdxExpr->getSourceRange());
2194 return;
2195 }
2196
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002197 // make sure the format string is really a string
2198 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2199 if (!Ty->isPointerType() ||
2200 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2201 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2202 IdxExpr->getSourceRange());
2203 return;
2204 }
2205
2206
2207 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002208 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002209 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002210 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2211 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2212 "format", std::string("3"), FirstArgExpr->getSourceRange());
2213 return;
2214 }
2215
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002216 // check if the function is variadic if the 3rd argument non-zero
2217 if (FirstArg != 0) {
2218 if (proto->isVariadic()) {
2219 ++NumArgs; // +1 for ...
2220 } else {
2221 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2222 return;
2223 }
2224 }
2225
2226 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2227 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002228 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002229 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002230 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2231 FirstArgExpr->getSourceRange());
2232 return;
2233 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002234 // if 0 it disables parameter checking (to use with e.g. va_list)
2235 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002236 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2237 "format", std::string("3"), FirstArgExpr->getSourceRange());
2238 return;
2239 }
2240
2241 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2242 Idx.getZExtValue(), FirstArg.getZExtValue()));
2243}
2244
Nate Begemanc398f0b2008-02-21 19:30:49 +00002245void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2246 // check the attribute arguments.
2247 if (rawAttr->getNumArgs() != 1) {
2248 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2249 std::string("1"));
2250 return;
2251 }
2252 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2253 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002254
Nate Begemanc398f0b2008-02-21 19:30:49 +00002255 // Make sure that there is a string literal as the annotation's single
2256 // argument.
2257 if (!SE) {
2258 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2259 return;
2260 }
2261 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2262 SE->getByteLength())));
2263}
2264
Anders Carlsson78aaae92007-12-19 07:19:40 +00002265void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2266{
2267 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002268 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002269 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002270 std::string("1"));
2271 return;
2272 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002273
Anders Carlsson042c4e72008-02-16 19:51:27 +00002274 unsigned Align = 0;
2275
2276 if (rawAttr->getNumArgs() == 0) {
2277 // FIXME: This should be the target specific maximum alignment.
2278 // (For now we just use 128 bits which is the maximum on X86.
2279 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002280 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002281 } else {
2282 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2283 llvm::APSInt alignment(32);
2284 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002285 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002286 "aligned", alignmentExpr->getSourceRange());
2287 return;
2288 }
2289
2290 Align = alignment.getZExtValue() * 8;
2291 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002292
Anders Carlsson042c4e72008-02-16 19:51:27 +00002293 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002294}