blob: c5901f0b91391222b84e6b2b48ec87148b1b2e4e [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Chris Lattner622c1932008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson1a841062008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000018#include "clang/AST/Builtins.h"
Chris Lattnere168f762006-11-10 05:29:30 +000019#include "clang/AST/Decl.h"
Chris Lattner1300fb92007-01-23 23:42:53 +000020#include "clang/AST/Expr.h"
Chris Lattnerf84a79c2006-11-11 22:59:23 +000021#include "clang/AST/Type.h"
Chris Lattner591a6752006-11-19 23:16:18 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattnere168f762006-11-10 05:29:30 +000023#include "clang/Parse/Scope.h"
Chris Lattnerac18be92006-11-20 06:49:47 +000024#include "clang/Basic/LangOptions.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000025#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-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 Lattner622c1932008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffe101f952008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffd54978b2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner38047f92007-01-27 06:24:01 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian458f7112007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner697e5d62006-11-09 06:32:27 +000033using namespace clang;
34
Steve Naroff2fc93f52008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahaniand52cd412007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff09bf8152007-09-06 21:24:23 +000040 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000041}
42
Steve Naroffc62adb62007-10-09 22:01:59 +000043void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +000044 if (S->decl_empty()) return;
45 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
46
Chris Lattner302b4be2006-11-19 02:31:38 +000047 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
48 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +000049 Decl *TmpD = static_cast<Decl*>(*I);
50 assert(TmpD && "This decl didn't get pushed??");
51 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
52 assert(D && "This decl isn't a ScopedDecl?");
53
Chris Lattnerff65b6b2007-01-23 01:33:16 +000054 IdentifierInfo *II = D->getIdentifier();
55 if (!II) continue;
Chris Lattner302b4be2006-11-19 02:31:38 +000056
Chris Lattnerff65b6b2007-01-23 01:33:16 +000057 // Unlink this decl from the identifier. Because the scope contains decls
58 // in an unordered collection, and because we have multiple identifier
59 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
60 if (II->getFETokenInfo<Decl>() == D) {
61 // Normal case, no multiple decls in different namespaces.
62 II->setFETokenInfo(D->getNext());
63 } else {
64 // Scan ahead. There are only three namespaces in C, so this loop can
65 // never execute more than 3 times.
Steve Naroff9324db12007-09-13 18:10:37 +000066 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattnerff65b6b2007-01-23 01:33:16 +000067 while (SomeDecl->getNext() != D) {
68 SomeDecl = SomeDecl->getNext();
69 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
70 }
71 SomeDecl->setNext(D->getNext());
72 }
Chris Lattner302b4be2006-11-19 02:31:38 +000073
Chris Lattner740b2f32006-11-21 01:32:20 +000074 // This will have to be revisited for C++: there we want to nest stuff in
75 // namespace decls etc. Even for C, we might want a top-level translation
76 // unit decl or something.
77 if (!CurFunctionDecl)
78 continue;
79
80 // Chain this decl to the containing function, it now owns the memory for
81 // the decl.
82 D->setNext(CurFunctionDecl->getDeclChain());
83 CurFunctionDecl->setDeclChain(D);
Chris Lattner302b4be2006-11-19 02:31:38 +000084 }
85}
86
Steve Naroff257520b2008-04-01 23:04:06 +000087/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
88/// return 0 if one not found.
89/// FIXME: removed this when ObjCInterfaceDecl's aren't ScopedDecl's.
90ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000091 ScopedDecl *IDecl;
92 // Scan up the scope chain looking for a decl that matches this identifier
93 // that is in the appropriate namespace.
Steve Naroff257520b2008-04-01 23:04:06 +000094 for (IDecl = Id->getFETokenInfo<ScopedDecl>(); IDecl;
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +000095 IDecl = IDecl->getNext())
96 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
97 break;
98
Ted Kremenek1b0ea822008-01-07 19:49:32 +000099 if (ObjCCompatibleAliasDecl *ADecl =
100 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000101 return ADecl->getClassInterface();
Steve Naroff2fc93f52008-04-02 14:35:35 +0000102 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000103}
104
Steve Naroff257520b2008-04-01 23:04:06 +0000105/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner18b19622007-01-22 07:39:13 +0000106/// namespace.
Steve Naroff2fc93f52008-04-02 14:35:35 +0000107Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
108 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner18b19622007-01-22 07:39:13 +0000109 if (II == 0) return 0;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000110 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner18b19622007-01-22 07:39:13 +0000111
112 // Scan up the scope chain looking for a decl that matches this identifier
113 // that is in the appropriate namespace. This search should not take long, as
114 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroff9324db12007-09-13 18:10:37 +0000115 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner18b19622007-01-22 07:39:13 +0000116 if (D->getIdentifierNamespace() == NS)
117 return D;
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000118
Chris Lattner9561a0b2007-01-28 08:20:04 +0000119 // If we didn't find a use of this identifier, and if the identifier
120 // corresponds to a compiler builtin, create the decl object for the builtin
121 // now, injecting it into translation unit scope, and return it.
122 if (NS == Decl::IDNS_Ordinary) {
Steve Naroff2fc93f52008-04-02 14:35:35 +0000123 if (enableLazyBuiltinCreation) {
124 // If this is a builtin on this (or all) targets, create the decl.
125 if (unsigned BuiltinID = II->getBuiltinID())
126 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
127 }
Steve Naroff257520b2008-04-01 23:04:06 +0000128 if (getLangOptions().ObjC1) {
129 // @interface and @compatibility_alias introduce typedef-like names.
130 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff9b94b172008-04-02 00:39:51 +0000131 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroff257520b2008-04-01 23:04:06 +0000132 // other names in IDNS_Ordinary.
133 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
134 if (I != ObjCAliasDecls.end())
135 return I->second->getClassInterface();
136 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000137 }
Chris Lattner18b19622007-01-22 07:39:13 +0000138 return 0;
139}
140
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000141void Sema::InitBuiltinVaListType()
142{
143 if (!Context.getBuiltinVaListType().isNull())
144 return;
145
146 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff2fc93f52008-04-02 14:35:35 +0000147 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000148 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000149 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
150}
151
Chris Lattner9561a0b2007-01-28 08:20:04 +0000152/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
153/// lazily create a decl for it.
Chris Lattner9c7a0362007-10-10 23:42:28 +0000154ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
155 Scope *S) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000156 Builtin::ID BID = (Builtin::ID)bid;
157
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000158 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson24ebce62007-10-12 23:56:29 +0000159 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000160 BID == Builtin::BI__builtin_va_end)
161 InitBuiltinVaListType();
162
Anders Carlsson87c149b2007-10-11 01:00:40 +0000163 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner5072bae2008-03-15 21:24:04 +0000164 FunctionDecl *New = FunctionDecl::Create(Context, SourceLocation(), II, R,
165 FunctionDecl::Extern, false, 0);
Chris Lattner9561a0b2007-01-28 08:20:04 +0000166
167 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000168 if (Scope *FnS = S->getFnParent())
169 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner9561a0b2007-01-28 08:20:04 +0000170 while (S->getParent())
171 S = S->getParent();
172 S->AddDecl(New);
173
174 // Add this decl to the end of the identifier info.
Steve Naroff9324db12007-09-13 18:10:37 +0000175 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000176 // Scan until we find the last (outermost) decl in the id chain.
177 while (LastDecl->getNext())
178 LastDecl = LastDecl->getNext();
179 // Insert before (outside) it.
180 LastDecl->setNext(New);
181 } else {
182 II->setFETokenInfo(New);
183 }
Chris Lattner9561a0b2007-01-28 08:20:04 +0000184 return New;
185}
186
Chris Lattner01564d92007-01-27 19:27:06 +0000187/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
188/// and scope as a previous declaration 'Old'. Figure out how to resolve this
189/// situation, merging decls or emitting diagnostics as appropriate.
190///
Steve Naroff257520b2008-04-01 23:04:06 +0000191TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000192 // Verify the old decl was also a typedef.
193 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
194 if (!Old) {
195 Diag(New->getLocation(), diag::err_redefinition_different_kind,
196 New->getName());
197 Diag(OldD->getLocation(), diag::err_previous_definition);
198 return New;
199 }
200
Steve Naroff6d40db02007-10-31 18:42:27 +0000201 // Allow multiple definitions for ObjC built-in typedefs.
202 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000203 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff6d40db02007-10-31 18:42:27 +0000204 return Old;
Steve Naroffe101f952008-01-30 23:46:05 +0000205
206 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
207 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
208 // *either* declaration is in a system header. The code below implements
209 // this adhoc compatibility rule. FIXME: The following code will not
210 // work properly when compiling ".i" files (containing preprocessed output).
211 SourceManager &SrcMgr = Context.getSourceManager();
212 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
213 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
214 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
215 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
216 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
217
Steve Naroffc06ee802008-03-26 21:27:00 +0000218 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
219 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
220 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffb2c80c72008-02-07 03:50:06 +0000221 getLangOptions().Microsoft)
Steve Naroffe101f952008-01-30 23:46:05 +0000222 return New;
Steve Naroffc06ee802008-03-26 21:27:00 +0000223
Chris Lattner01564d92007-01-27 19:27:06 +0000224 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
225 // TODO: This is totally simplistic. It should handle merging functions
226 // together etc, merging extern int X; int X; ...
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230}
231
Chris Lattner84966392008-03-03 03:28:21 +0000232/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
233static bool DeclHasAttr(const Decl *decl, const Attr *target) {
234 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
235 if (attr->getKind() == target->getKind())
236 return true;
237
238 return false;
239}
240
241/// MergeAttributes - append attributes from the Old decl to the New one.
242static void MergeAttributes(Decl *New, Decl *Old) {
243 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
244
245// FIXME: fix this code to cleanup the Old attrs correctly
246 while (attr) {
247 tmp = attr;
248 attr = attr->getNext();
249
250 if (!DeclHasAttr(New, tmp)) {
251 New->addAttr(tmp);
252 } else {
253 tmp->setNext(0);
254 delete(tmp);
255 }
256 }
257}
258
Chris Lattner01564d92007-01-27 19:27:06 +0000259/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
260/// and scope as a previous declaration 'Old'. Figure out how to resolve this
261/// situation, merging decls or emitting diagnostics as appropriate.
262///
Steve Naroff257520b2008-04-01 23:04:06 +0000263FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000264 // Verify the old decl was also a function.
265 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
266 if (!Old) {
267 Diag(New->getLocation(), diag::err_redefinition_different_kind,
268 New->getName());
269 Diag(OldD->getLocation(), diag::err_previous_definition);
270 return New;
271 }
Chris Lattner8a8558b2008-02-29 16:48:43 +0000272
Chris Lattner84966392008-03-03 03:28:21 +0000273 MergeAttributes(New, Old);
274
Chris Lattnerc511efb2007-01-27 19:32:14 +0000275
Chris Lattner5c3f1542007-11-20 19:04:50 +0000276 QualType OldQType = Old->getCanonicalType();
277 QualType NewQType = New->getCanonicalType();
278
Steve Naroff012484d2008-01-14 20:51:29 +0000279 // Function types need to be compatible, not identical. This handles
280 // duplicate function decls like "void f(int); void f(enum X);" properly.
281 if (Context.functionTypesAreCompatible(OldQType, NewQType))
282 return New;
Chris Lattner45d561a2007-11-06 06:07:26 +0000283
Steve Naroff17832a42008-01-16 15:01:34 +0000284 // A function that has already been declared has been redeclared or defined
285 // with a different type- show appropriate diagnostic
286 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
287 diag::err_previous_declaration;
288
Chris Lattner01564d92007-01-27 19:27:06 +0000289 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
290 // TODO: This is totally simplistic. It should handle merging functions
291 // together etc, merging extern int X; int X; ...
Steve Naroff17832a42008-01-16 15:01:34 +0000292 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
293 Diag(Old->getLocation(), PrevDiag);
Chris Lattner01564d92007-01-27 19:27:06 +0000294 return New;
295}
296
Chris Lattner32097252007-11-06 04:28:31 +0000297/// equivalentArrayTypes - Used to determine whether two array types are
298/// equivalent.
299/// We need to check this explicitly as an incomplete array definition is
300/// considered a VariableArrayType, so will not match a complete array
301/// definition that would be otherwise equivalent.
302static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
303 const ArrayType *NewAT = NewQType->getAsArrayType();
304 const ArrayType *OldAT = OldQType->getAsArrayType();
305
306 if (!NewAT || !OldAT)
307 return false;
308
309 // If either (or both) array types in incomplete we need to strip off the
310 // outer VariableArrayType. Once the outer VAT is removed the remaining
311 // types must be identical if the array types are to be considered
312 // equivalent.
313 // eg. int[][1] and int[1][1] become
314 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
315 // removing the outermost VAT gives
316 // CAT(1, int) and CAT(1, int)
317 // which are equal, therefore the array types are equivalent.
Eli Friedman9e805b22008-02-15 12:53:51 +0000318 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattner32097252007-11-06 04:28:31 +0000319 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
320 return false;
Eli Friedman361de612008-01-29 07:51:12 +0000321 NewQType = NewAT->getElementType().getCanonicalType();
322 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattner32097252007-11-06 04:28:31 +0000323 }
324
325 return NewQType == OldQType;
326}
327
Chris Lattner01564d92007-01-27 19:27:06 +0000328/// MergeVarDecl - We just parsed a variable 'New' which has the same name
329/// and scope as a previous declaration 'Old'. Figure out how to resolve this
330/// situation, merging decls or emitting diagnostics as appropriate.
331///
Steve Narofffc49d672007-04-01 21:27:45 +0000332/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
333/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
334///
Steve Naroff257520b2008-04-01 23:04:06 +0000335VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000336 // Verify the old decl was also a variable.
337 VarDecl *Old = dyn_cast<VarDecl>(OldD);
338 if (!Old) {
339 Diag(New->getLocation(), diag::err_redefinition_different_kind,
340 New->getName());
341 Diag(OldD->getLocation(), diag::err_previous_definition);
342 return New;
343 }
Chris Lattner84966392008-03-03 03:28:21 +0000344
345 MergeAttributes(New, Old);
346
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000347 // Verify the types match.
Chris Lattner32097252007-11-06 04:28:31 +0000348 if (Old->getCanonicalType() != New->getCanonicalType() &&
349 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000350 Diag(New->getLocation(), diag::err_redefinition, New->getName());
351 Diag(Old->getLocation(), diag::err_previous_definition);
352 return New;
353 }
Steve Naroff1e787362008-01-30 00:44:01 +0000354 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
355 if (New->getStorageClass() == VarDecl::Static &&
356 (Old->getStorageClass() == VarDecl::None ||
357 Old->getStorageClass() == VarDecl::Extern)) {
358 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
359 Diag(Old->getLocation(), diag::err_previous_definition);
360 return New;
361 }
362 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
363 if (New->getStorageClass() != VarDecl::Static &&
364 Old->getStorageClass() == VarDecl::Static) {
365 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
366 Diag(Old->getLocation(), diag::err_previous_definition);
367 return New;
368 }
369 // We've verified the types match, now handle "tentative" definitions.
370 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
371 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
372
373 if (OldFSDecl && NewFSDecl) {
374 // Handle C "tentative" external object definitions (C99 6.9.2).
375 bool OldIsTentative = false;
376 bool NewIsTentative = false;
377
378 if (!OldFSDecl->getInit() &&
379 (OldFSDecl->getStorageClass() == VarDecl::None ||
380 OldFSDecl->getStorageClass() == VarDecl::Static))
381 OldIsTentative = true;
382
383 // FIXME: this check doesn't work (since the initializer hasn't been
384 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
385 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
386 // thrown out the old decl.
387 if (!NewFSDecl->getInit() &&
388 (NewFSDecl->getStorageClass() == VarDecl::None ||
389 NewFSDecl->getStorageClass() == VarDecl::Static))
390 ; // change to NewIsTentative = true; once the code is moved.
391
392 if (NewIsTentative || OldIsTentative)
393 return New;
394 }
395 if (Old->getStorageClass() != VarDecl::Extern &&
396 New->getStorageClass() != VarDecl::Extern) {
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000397 Diag(New->getLocation(), diag::err_redefinition, New->getName());
398 Diag(Old->getLocation(), diag::err_previous_definition);
399 }
Chris Lattner01564d92007-01-27 19:27:06 +0000400 return New;
401}
402
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000403/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
404/// no declarator (e.g. "struct foo;") is parsed.
405Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
406 // TODO: emit error on 'int;' or 'const enum foo;'.
407 // TODO: emit error on 'typedef int;'
408 // if (!DS.isMissingDeclaratorOk()) Diag(...);
409
Steve Naroff14f5f792007-11-17 21:37:36 +0000410 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000411}
412
Steve Naroff98f72032008-01-10 22:15:12 +0000413bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroff2fea1392007-09-02 02:04:30 +0000414 // Get the type before calling CheckSingleAssignmentConstraints(), since
415 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +0000416 QualType InitType = Init->getType();
Steve Naroff2fea1392007-09-02 02:04:30 +0000417
Chris Lattner9bad62c2008-01-04 18:04:52 +0000418 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
419 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
420 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +0000421}
422
Steve Naroff77b97002007-09-04 14:36:54 +0000423bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroff98f72032008-01-10 22:15:12 +0000424 QualType ElementType) {
Chris Lattnerf6412552007-12-11 23:15:04 +0000425 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff98f72032008-01-10 22:15:12 +0000426 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerf6412552007-12-11 23:15:04 +0000427 return true; // types weren't compatible.
428
Steve Naroff77b97002007-09-04 14:36:54 +0000429 if (savExpr != expr) // The type was promoted, update initializer list.
430 IList->setInit(slot, expr);
Steve Naroffac074b42007-09-04 02:20:04 +0000431 return false;
432}
433
Steve Naroffaf2a0222008-01-22 00:55:40 +0000434bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanbd258282008-02-15 18:16:39 +0000435 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000436 // C99 6.7.8p14. We have an array of character type with unknown size
437 // being initialized to a string literal.
438 llvm::APSInt ConstVal(32);
439 ConstVal = strLiteral->getByteLength() + 1;
440 // Return a new array type (C99 6.7.8p22).
Eli Friedmanbd258282008-02-15 18:16:39 +0000441 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffaf2a0222008-01-22 00:55:40 +0000442 ArrayType::Normal, 0);
443 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
444 // C99 6.7.8p14. We have an array of character type with known size.
445 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
446 Diag(strLiteral->getSourceRange().getBegin(),
447 diag::warn_initializer_string_for_char_array_too_long,
448 strLiteral->getSourceRange());
449 } else {
450 assert(0 && "HandleStringLiteralInit(): Invalid array type");
451 }
452 // Set type from "char *" to "constant array of char".
453 strLiteral->setType(DeclT);
454 // For now, we always return false (meaning success).
455 return false;
456}
457
458StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000459 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000460 if (AT && AT->getElementType()->isCharType()) {
461 return dyn_cast<StringLiteral>(Init);
462 }
Steve Naroffaf2a0222008-01-22 00:55:40 +0000463 return 0;
464}
465
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000466// CheckInitializerListTypes - Checks the types of elements of an initializer
467// list. This function is recursive: it calls itself to initialize subelements
468// of aggregate types. Note that the topLevel parameter essentially refers to
469// whether this expression "owns" the initializer list passed in, or if this
470// initialization is taking elements out of a parent initializer. Each
471// call to this function adds zero or more to startIndex, reports any errors,
472// and returns true if it found any inconsistent types.
473bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
474 bool topLevel, unsigned& startIndex) {
Steve Naroff91f78082007-12-10 22:44:33 +0000475 bool hadError = false;
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000476
477 if (DeclType->isScalarType()) {
478 // The simplest case: initializing a single scalar
479 if (topLevel) {
480 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
481 IList->getSourceRange());
482 }
483 if (startIndex < IList->getNumInits()) {
484 Expr* expr = IList->getInit(startIndex);
485 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
486 // FIXME: Should an error be reported here instead?
487 unsigned newIndex = 0;
488 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
489 } else {
490 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
491 }
492 ++startIndex;
493 }
494 // FIXME: Should an error be reported for empty initializer list + scalar?
495 } else if (DeclType->isVectorType()) {
496 if (startIndex < IList->getNumInits()) {
497 const VectorType *VT = DeclType->getAsVectorType();
498 int maxElements = VT->getNumElements();
499 QualType elementType = VT->getElementType();
500
501 for (int i = 0; i < maxElements; ++i) {
502 // Don't attempt to go past the end of the init list
503 if (startIndex >= IList->getNumInits())
504 break;
505 Expr* expr = IList->getInit(startIndex);
506 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
507 unsigned newIndex = 0;
508 hadError |= CheckInitializerListTypes(SubInitList, elementType,
509 true, newIndex);
510 ++startIndex;
511 } else {
512 hadError |= CheckInitializerListTypes(IList, elementType,
513 false, startIndex);
514 }
515 }
516 }
517 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
518 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffaeb6b302008-01-28 02:00:41 +0000519 if (startIndex < IList->getNumInits() && !topLevel &&
520 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
521 DeclType)) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000522 // We found a compatible struct; per the standard, this initializes the
523 // struct. (The C standard technically says that this only applies for
524 // initializers for declarations with automatic scope; however, this
525 // construct is unambiguous anyway because a struct cannot contain
526 // a type compatible with itself. We'll output an error when we check
527 // if the initializer is constant.)
528 // FIXME: Is a call to CheckSingleInitializer required here?
529 ++startIndex;
530 } else {
531 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroff326389b2008-02-11 00:06:17 +0000532
Steve Naroffb5fc2552008-02-11 21:52:37 +0000533 // If the record is invalid, some of it's members are invalid. To avoid
534 // confusion, we forgo checking the intializer for the entire record.
Steve Naroff326389b2008-02-11 00:06:17 +0000535 if (structDecl->isInvalidDecl())
536 return true;
537
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000538 // If structDecl is a forward declaration, this loop won't do anything;
539 // That's okay, because an error should get printed out elsewhere. It
540 // might be worthwhile to skip over the rest of the initializer, though.
541 int numMembers = structDecl->getNumMembers() -
542 structDecl->hasFlexibleArrayMember();
543 for (int i = 0; i < numMembers; i++) {
544 // Don't attempt to go past the end of the init list
545 if (startIndex >= IList->getNumInits())
546 break;
547 FieldDecl * curField = structDecl->getMember(i);
548 if (!curField->getIdentifier()) {
549 // Don't initialize unnamed fields, e.g. "int : 20;"
550 continue;
551 }
552 QualType fieldType = curField->getType();
553 Expr* expr = IList->getInit(startIndex);
554 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
555 unsigned newStart = 0;
556 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
557 true, newStart);
558 ++startIndex;
559 } else {
560 hadError |= CheckInitializerListTypes(IList, fieldType,
561 false, startIndex);
562 }
563 if (DeclType->isUnionType())
564 break;
565 }
566 // FIXME: Implement flexible array initialization GCC extension (it's a
567 // really messy extension to implement, unfortunately...the necessary
568 // information isn't actually even here!)
569 }
570 } else if (DeclType->isArrayType()) {
571 // Check for the special-case of initializing an array with a string.
572 if (startIndex < IList->getNumInits()) {
573 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
574 DeclType)) {
575 CheckStringLiteralInit(lit, DeclType);
576 ++startIndex;
577 if (topLevel && startIndex < IList->getNumInits()) {
578 // We have leftover initializers; warn
579 Diag(IList->getInit(startIndex)->getLocStart(),
580 diag::err_excess_initializers_in_char_array_initializer,
581 IList->getInit(startIndex)->getSourceRange());
582 }
583 return false;
584 }
585 }
586 int maxElements;
Eli Friedmanbd258282008-02-15 18:16:39 +0000587 if (DeclType->isIncompleteArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000588 // FIXME: use a proper constant
589 maxElements = 0x7FFFFFFF;
Chris Lattnerf1791902008-02-20 23:17:35 +0000590 } else if (const VariableArrayType *VAT =
591 DeclType->getAsVariableArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000592 // Check for VLAs; in standard C it would be possible to check this
593 // earlier, but I don't know where clang accepts VLAs (gcc accepts
594 // them in all sorts of strange places).
Eli Friedmanbd258282008-02-15 18:16:39 +0000595 Diag(VAT->getSizeExpr()->getLocStart(),
596 diag::err_variable_object_no_init,
597 VAT->getSizeExpr()->getSourceRange());
598 hadError = true;
599 maxElements = 0x7FFFFFFF;
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000600 } else {
601 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
602 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
603 }
604 QualType elementType = DeclType->getAsArrayType()->getElementType();
605 int numElements = 0;
606 for (int i = 0; i < maxElements; ++i, ++numElements) {
607 // Don't attempt to go past the end of the init list
608 if (startIndex >= IList->getNumInits())
609 break;
610 Expr* expr = IList->getInit(startIndex);
611 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
612 unsigned newIndex = 0;
613 hadError |= CheckInitializerListTypes(SubInitList, elementType,
614 true, newIndex);
615 ++startIndex;
616 } else {
617 hadError |= CheckInitializerListTypes(IList, elementType,
618 false, startIndex);
619 }
620 }
Eli Friedman9e805b22008-02-15 12:53:51 +0000621 if (DeclType->isIncompleteArrayType()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000622 // If this is an incomplete array type, the actual type needs to
623 // be calculated here
624 if (numElements == 0) {
625 // Sizing an array implicitly to zero is not allowed
626 // (It could in theory be allowed, but it doesn't really matter.)
627 Diag(IList->getLocStart(),
628 diag::err_at_least_one_initializer_needed_to_size_array);
629 hadError = true;
630 } else {
631 llvm::APSInt ConstVal(32);
632 ConstVal = numElements;
633 DeclType = Context.getConstantArrayType(elementType, ConstVal,
634 ArrayType::Normal, 0);
635 }
636 }
637 } else {
638 assert(0 && "Aggregate that isn't a function or array?!");
639 }
640 } else {
641 // In C, all types are either scalars or aggregates, but
642 // additional handling is needed here for C++ (and possibly others?).
643 assert(0 && "Unsupported initializer type");
644 }
645
646 // If this init list is a base list, we set the type; an initializer doesn't
647 // fundamentally have a type, but this makes the ASTs a bit easier to read
648 if (topLevel)
649 IList->setType(DeclType);
650
651 if (topLevel && startIndex < IList->getNumInits()) {
652 // We have leftover initializers; warn
653 Diag(IList->getInit(startIndex)->getLocStart(),
654 diag::warn_excess_initializers,
655 IList->getInit(startIndex)->getSourceRange());
656 }
657 return hadError;
658}
659
660bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Narofff9eb5982008-01-21 23:53:58 +0000661 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
662 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanbd258282008-02-15 18:16:39 +0000663 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Narofff9eb5982008-01-21 23:53:58 +0000664 return Diag(VAT->getSizeExpr()->getLocStart(),
665 diag::err_variable_object_no_init,
666 VAT->getSizeExpr()->getSourceRange());
667
Steve Naroff91f78082007-12-10 22:44:33 +0000668 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
669 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +0000670 // FIXME: Handle wide strings
671 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
672 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman42978262008-02-08 00:48:24 +0000673
674 if (DeclType->isArrayType())
675 return Diag(Init->getLocStart(),
676 diag::err_array_init_list_required,
677 Init->getSourceRange());
678
Steve Naroff98f72032008-01-10 22:15:12 +0000679 return CheckSingleInitializer(Init, DeclType);
Steve Naroff91f78082007-12-10 22:44:33 +0000680 }
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000681 unsigned newIndex = 0;
682 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff2fea1392007-09-02 02:04:30 +0000683}
684
Fariborz Jahanian56ff1462007-11-08 23:49:49 +0000685Sema::DeclTy *
Steve Naroff30d242c2007-09-15 18:49:24 +0000686Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000687 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattnere168f762006-11-10 05:29:30 +0000688 IdentifierInfo *II = D.getIdentifier();
Chris Lattner302b4be2006-11-19 02:31:38 +0000689
Chris Lattner02c04392007-07-25 00:24:17 +0000690 // All of these full declarators require an identifier. If it doesn't have
691 // one, the ParsedFreeStandingDeclSpec action should be used.
692 if (II == 0) {
Chris Lattnera7c19fe2007-10-16 22:36:42 +0000693 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerc4f6d0c2007-08-28 06:17:15 +0000694 diag::err_declarator_need_ident,
Chris Lattner02c04392007-07-25 00:24:17 +0000695 D.getDeclSpec().getSourceRange(), D.getSourceRange());
696 return 0;
697 }
698
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000699 // The scope passed in may not be a decl scope. Zip up the scope tree until
700 // we find one that is.
701 while ((S->getFlags() & Scope::DeclScope) == 0)
702 S = S->getParent();
703
Chris Lattner01564d92007-01-27 19:27:06 +0000704 // See if this is a redefinition of a variable in the same scope.
Steve Naroff2fc93f52008-04-02 14:35:35 +0000705 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroff9324db12007-09-13 18:10:37 +0000706 ScopedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +0000707 bool InvalidDecl = false;
708
Chris Lattner07b201d2007-11-14 06:34:38 +0000709 QualType R = GetTypeForDeclarator(D, S);
710 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
711
Chris Lattner01a7c532007-01-25 23:09:03 +0000712 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner07b201d2007-11-14 06:34:38 +0000713 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner01564d92007-01-27 19:27:06 +0000714 if (!NewTD) return 0;
Steve Naroffa8fd9732007-06-11 00:35:03 +0000715
716 // Handle attributes prior to checking for duplicates in MergeVarDecl
717 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
718 D.getAttributes());
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000719 // Merge the decl with the existing one if appropriate. If the decl is
720 // in an outer scope, it isn't the same thing.
721 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000722 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
723 if (NewTD == 0) return 0;
724 }
725 New = NewTD;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000726 if (S->getParent() == 0) {
727 // C99 6.7.7p2: If a typedef name specifies a variably modified type
728 // then it shall have block scope.
Eli Friedman9e805b22008-02-15 12:53:51 +0000729 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
730 // FIXME: Diagnostic needs to be fixed.
731 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff096dd942007-08-31 17:20:07 +0000732 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +0000733 }
734 }
Chris Lattner07b201d2007-11-14 06:34:38 +0000735 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattnercc61bf52007-09-27 15:15:46 +0000736 FunctionDecl::StorageClass SC = FunctionDecl::None;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000737 switch (D.getDeclSpec().getStorageClassSpec()) {
738 default: assert(0 && "Unknown storage class!");
739 case DeclSpec::SCS_auto:
740 case DeclSpec::SCS_register:
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000741 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
742 R.getAsString());
Steve Narofff93b6722007-08-28 20:14:24 +0000743 InvalidDecl = true;
744 break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000745 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
746 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
747 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff1f7f6922008-01-28 21:57:15 +0000748 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000749 }
750
Chris Lattner5072bae2008-03-15 21:24:04 +0000751 bool isInline = D.getDeclSpec().isInlineSpecified();
752 FunctionDecl *NewFD = FunctionDecl::Create(Context, D.getIdentifierLoc(),
753 II, R, SC, isInline,
754 LastDeclarator);
Ted Kremenek49b61ab2008-02-27 22:18:07 +0000755 // Handle attributes.
Ted Kremenek49b61ab2008-02-27 22:18:07 +0000756 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
757 D.getAttributes());
Chris Lattner01564d92007-01-27 19:27:06 +0000758
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000759 // Merge the decl with the existing one if appropriate. Since C functions
760 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner01564d92007-01-27 19:27:06 +0000761 if (PrevDecl) {
762 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
763 if (NewFD == 0) return 0;
764 }
765 New = NewFD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000766 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000767 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +0000768 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
769 D.getIdentifier()->getName());
770 InvalidDecl = true;
771 }
Chris Lattner01564d92007-01-27 19:27:06 +0000772
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000773 VarDecl *NewVD;
774 VarDecl::StorageClass SC;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000775 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner4b08ca82008-03-15 21:10:16 +0000776 default: assert(0 && "Unknown storage class!");
777 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
778 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
779 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
780 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
781 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
782 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000783 }
Steve Narofffc49d672007-04-01 21:27:45 +0000784 if (S->getParent() == 0) {
Bill Wendlingd6de6572007-06-02 09:40:07 +0000785 // C99 6.9p2: The storage-class specifiers auto and register shall not
786 // appear in the declaration specifiers in an external declaration.
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000787 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerc04bd6a2007-05-16 18:09:54 +0000788 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
789 R.getAsString());
Steve Naroffcf871f52007-08-28 18:45:29 +0000790 InvalidDecl = true;
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000791 }
Chris Lattner96c460d2008-03-15 21:32:50 +0000792 NewVD = FileVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
793 LastDeclarator);
Steve Naroff2fea1392007-09-02 02:04:30 +0000794 } else {
Chris Lattner96c460d2008-03-15 21:32:50 +0000795 NewVD = BlockVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
796 LastDeclarator);
Steve Naroffcf871f52007-08-28 18:45:29 +0000797 }
Steve Naroffa8fd9732007-06-11 00:35:03 +0000798 // Handle attributes prior to checking for duplicates in MergeVarDecl
799 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
800 D.getAttributes());
Nate Begemanb561de72008-03-14 18:07:10 +0000801
802 // Emit an error if an address space was applied to decl with local storage.
803 // This includes arrays of objects with address space qualifiers, but not
804 // automatic variables that point to other address spaces.
805 // ISO/IEC TR 18037 S5.1.2
Nate Begemanc506c782008-03-25 18:36:32 +0000806 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
807 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
808 InvalidDecl = true;
Nate Begeman144625e2008-03-14 00:22:18 +0000809 }
Steve Naroffe6b0ec82008-01-09 23:34:55 +0000810 // Merge the decl with the existing one if appropriate. If the decl is
811 // in an outer scope, it isn't the same thing.
812 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner01564d92007-01-27 19:27:06 +0000813 NewVD = MergeVarDecl(NewVD, PrevDecl);
814 if (NewVD == 0) return 0;
815 }
816 New = NewVD;
Chris Lattner01a7c532007-01-25 23:09:03 +0000817 }
Chris Lattner302b4be2006-11-19 02:31:38 +0000818
Chris Lattnere168f762006-11-10 05:29:30 +0000819 // If this has an identifier, add it to the scope stack.
820 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +0000821 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnere168f762006-11-10 05:29:30 +0000822 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +0000823 S->AddDecl(New);
Chris Lattnere168f762006-11-10 05:29:30 +0000824 }
Steve Narofff93b6722007-08-28 20:14:24 +0000825 // If any semantic error occurred, mark the decl as invalid.
826 if (D.getInvalidType() || InvalidDecl)
827 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +0000828
829 return New;
830}
831
Steve Naroff98f72032008-01-10 22:15:12 +0000832bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
833 SourceLocation loc;
834 // FIXME: Remove the isReference check and handle assignment to a reference.
835 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
836 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
837 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
838 return true;
839 }
840 return false;
841}
842
Steve Naroff61091402007-09-12 14:07:44 +0000843void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000844 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff61091402007-09-12 14:07:44 +0000845 Expr *Init = static_cast<Expr *>(init);
Chris Lattner8beb9de2007-10-19 20:10:30 +0000846 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +0000847
Chris Lattner8beb9de2007-10-19 20:10:30 +0000848 // If there is no declaration, there was an error parsing it. Just ignore
849 // the initializer.
850 if (RealDecl == 0) {
851 delete Init;
852 return;
853 }
Steve Naroff61091402007-09-12 14:07:44 +0000854
Steve Naroff437b4d82007-09-12 20:13:48 +0000855 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
856 if (!VDecl) {
Steve Naroff9def2b12007-09-13 21:41:19 +0000857 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
858 diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +0000859 RealDecl->setInvalidDecl();
860 return;
861 }
Steve Naroff61091402007-09-12 14:07:44 +0000862 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +0000863 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +0000864 QualType DclT = VDecl->getType(), SavT = DclT;
865 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000866 VarDecl::StorageClass SC = BVD->getStorageClass();
867 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +0000868 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff61091402007-09-12 14:07:44 +0000869 BVD->setInvalidDecl();
870 } else if (!BVD->isInvalidDecl()) {
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000871 if (CheckInitializerTypes(Init, DclT))
872 BVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000873 if (SC == VarDecl::Static) // C99 6.7.8p4.
874 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000875 }
Steve Naroff437b4d82007-09-12 20:13:48 +0000876 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff61091402007-09-12 14:07:44 +0000877 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +0000878 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff61091402007-09-12 14:07:44 +0000879 if (!FVD->isInvalidDecl())
Steve Naroff78c6cdf2008-01-25 00:51:06 +0000880 if (CheckInitializerTypes(Init, DclT))
881 FVD->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +0000882
883 // C99 6.7.8p4. All file scoped initializers need to be constant.
884 CheckForConstantInitializer(Init, DclT);
Steve Naroff61091402007-09-12 14:07:44 +0000885 }
886 // If the type changed, it means we had an incomplete type that was
887 // completed by the initializer. For example:
888 // int ary[] = { 1, 3, 5 };
889 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000890 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +0000891 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +0000892 Init->setType(DclT);
893 }
Steve Naroff61091402007-09-12 14:07:44 +0000894
895 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +0000896 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +0000897 return;
898}
899
Chris Lattner776fac82007-06-09 00:53:06 +0000900/// The declarators are chained together backwards, reverse the list.
901Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
902 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +0000903 Decl *GroupDecl = static_cast<Decl*>(group);
904 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +0000905 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +0000906
907 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
908 ScopedDecl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +0000909 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +0000910 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +0000911 else { // reverse the list.
912 while (Group) {
Steve Naroffa23cc792007-09-13 23:52:58 +0000913 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +0000914 Group->setNextDeclarator(NewGroup);
915 NewGroup = Group;
916 Group = Next;
917 }
918 }
919 // Perform semantic analysis that depends on having fully processed both
920 // the declarator and initializer.
Steve Naroffa23cc792007-09-13 23:52:58 +0000921 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +0000922 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
923 if (!IDecl)
924 continue;
925 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
926 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
927 QualType T = IDecl->getType();
928
929 // C99 6.7.5.2p2: If an identifier is declared to be an object with
930 // static storage duration, it shall not have a variable length array.
931 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman5c949092008-02-15 19:53:52 +0000932 if (T->getAsVariableArrayType()) {
Eli Friedmanbd258282008-02-15 18:16:39 +0000933 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
934 IDecl->setInvalidDecl();
Steve Naroff61091402007-09-12 14:07:44 +0000935 }
936 }
937 // Block scope. C99 6.7p7: If an identifier for an object is declared with
938 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
939 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner81cb9e82008-04-02 01:05:10 +0000940 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner310369f2007-12-02 07:50:03 +0000941 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
942 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000943 IDecl->setInvalidDecl();
944 }
945 }
946 // File scope. C99 6.9.2p2: A declaration of an identifier for and
947 // object that has file scope without an initializer, and without a
948 // storage-class specifier or with the storage-class specifier "static",
949 // constitutes a tentative definition. Note: A tentative definition with
950 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb716fba2008-01-18 00:39:39 +0000951 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
952 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9e805b22008-02-15 12:53:51 +0000953 if (T->isIncompleteArrayType()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +0000954 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
955 // array to be completed. Don't issue a diagnostic.
Chris Lattner81cb9e82008-04-02 01:05:10 +0000956 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +0000957 // C99 6.9.2p3: If the declaration of an identifier for an object is
958 // a tentative definition and has internal linkage (C99 6.2.2p3), the
959 // declared type shall not be an incomplete type.
Chris Lattner310369f2007-12-02 07:50:03 +0000960 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
961 T.getAsString());
Steve Naroff61091402007-09-12 14:07:44 +0000962 IDecl->setInvalidDecl();
963 }
964 }
Chris Lattner776fac82007-06-09 00:53:06 +0000965 }
966 return NewGroup;
967}
Steve Naroff7e6f7c22007-08-28 03:03:08 +0000968
969// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner53621a52007-06-13 20:44:40 +0000970ParmVarDecl *
Nate Begemanf0e4a522008-02-17 21:02:04 +0000971Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
972 Scope *FnScope) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000973 IdentifierInfo *II = PI.Ident;
Chris Lattnerc284e9b2007-01-23 05:14:32 +0000974 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
975 // Can this happen for params? We already checked that they don't conflict
976 // among each other. Here they can only shadow globals, which is ok.
Steve Naroff2fc93f52008-04-02 14:35:35 +0000977 if (/*Decl *PrevDecl = */LookupDecl(II, Decl::IDNS_Ordinary, FnScope)) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000978
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +0000979 }
980
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000981 // FIXME: Handle storage class (auto, register). No declarator?
Chris Lattner776fac82007-06-09 00:53:06 +0000982 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff773df5c2007-08-07 22:44:21 +0000983
984 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
985 // Doing the promotion here has a win and a loss. The win is the type for
986 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
987 // code generator). The loss is the orginal type isn't preserved. For example:
988 //
989 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
990 // int blockvardecl[5];
991 // sizeof(parmvardecl); // size == 4
992 // sizeof(blockvardecl); // size == 20
993 // }
994 //
995 // For expressions, all implicit conversions are captured using the
996 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
997 //
998 // FIXME: If a source translation tool needs to see the original type, then
999 // we need to consider storing both types (in ParmVarDecl)...
1000 //
1001 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnera21ad802008-04-02 05:18:44 +00001002 if (parmDeclType->isArrayType()) {
Chris Lattner4f203512008-01-02 22:50:48 +00001003 // int x[restrict 4] -> int *restrict
Chris Lattnera21ad802008-04-02 05:18:44 +00001004 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner4f203512008-01-02 22:50:48 +00001005 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +00001006 parmDeclType = Context.getPointerType(parmDeclType);
1007
Chris Lattner96c460d2008-03-15 21:32:50 +00001008 ParmVarDecl *New = ParmVarDecl::Create(Context, PI.IdentLoc, II, parmDeclType,
1009 VarDecl::None, 0);
Anders Carlsson1a841062008-02-15 07:04:12 +00001010
Steve Naroffcf871f52007-08-28 18:45:29 +00001011 if (PI.InvalidType)
1012 New->setInvalidDecl();
1013
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001014 // If this has an identifier, add it to the scope stack.
1015 if (II) {
Steve Naroff9324db12007-09-13 18:10:37 +00001016 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001017 II->setFETokenInfo(New);
Chris Lattner99d31772007-01-21 22:37:37 +00001018 FnScope->AddDecl(New);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001019 }
Nate Begemand8c41562008-02-17 21:20:31 +00001020
1021 HandleDeclAttributes(New, PI.AttrList, 0);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001022 return New;
1023}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00001024
Chris Lattnera55a2cc2007-10-09 17:14:05 +00001025Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner229ce602006-11-21 01:21:07 +00001026 assert(CurFunctionDecl == 0 && "Function parsing confused");
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001027 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1028 "Not a function declarator!");
1029 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1030
1031 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1032 // for a K&R function.
1033 if (!FTI.hasPrototype) {
1034 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1035 if (FTI.ArgInfo[i].TypeInfo == 0) {
Chris Lattner843c5922007-06-10 23:40:34 +00001036 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001037 FTI.ArgInfo[i].Ident->getName());
1038 // Implicitly declare the argument as type 'int' for lack of a better
1039 // type.
1040 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1041 }
1042 }
Chris Lattnerb080ed52008-02-17 19:31:09 +00001043
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001044 // Since this is a function definition, act as though we have information
1045 // about the arguments.
Chris Lattnerb080ed52008-02-17 19:31:09 +00001046 if (FTI.NumArgs)
1047 FTI.hasPrototype = true;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001048 } else {
1049 // FIXME: Diagnose arguments without names in C.
1050
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00001051 }
1052
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001053 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00001054
1055 // See if this is a redefinition.
Steve Naroff257520b2008-04-01 23:04:06 +00001056 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff2fc93f52008-04-02 14:35:35 +00001057 GlobalScope);
Steve Naroff012484d2008-01-14 20:51:29 +00001058 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1059 if (FD->getBody()) {
1060 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1061 D.getIdentifier()->getName());
1062 Diag(FD->getLocation(), diag::err_previous_definition);
1063 }
1064 }
Steve Naroffc1e22c72008-02-12 01:09:36 +00001065 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner27055192008-02-16 01:20:36 +00001066 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner229ce602006-11-21 01:21:07 +00001067 CurFunctionDecl = FD;
Chris Lattner2114d5e2006-12-04 07:40:24 +00001068
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001069 // Create Decl objects for each parameter, adding them to the FunctionDecl.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001070 llvm::SmallVector<ParmVarDecl*, 16> Params;
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001071
1072 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1073 // no arguments, not a function that takes a single void argument.
1074 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner445fcab2008-02-20 20:55:12 +00001075 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerdb2a6ef2007-11-28 18:51:29 +00001076 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner99d31772007-01-21 22:37:37 +00001077 // empty arg list, don't push any params.
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001078 } else {
Steve Naroffd0bf5162007-11-12 03:44:46 +00001079 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Steve Naroffc5f81202008-03-19 23:07:49 +00001080 ParmVarDecl *parmDecl;
1081
1082 parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1083 FnBodyScope);
1084 // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1085 // declarator that is part of a function definition of that function
1086 // shall not have incomplete type.
Chris Lattner81cb9e82008-04-02 01:05:10 +00001087 if (parmDecl->getType()->isIncompleteType() &&
1088 !parmDecl->isInvalidDecl()) {
Steve Naroffc5f81202008-03-19 23:07:49 +00001089 Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1090 parmDecl->getType().getAsString());
1091 parmDecl->setInvalidDecl();
1092 }
1093 Params.push_back(parmDecl);
Steve Naroffd0bf5162007-11-12 03:44:46 +00001094 }
Chris Lattnerf61c8a82007-01-21 19:04:43 +00001095 }
Chris Lattner2114d5e2006-12-04 07:40:24 +00001096
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001097 FD->setParams(&Params[0], Params.size());
Chris Lattner2114d5e2006-12-04 07:40:24 +00001098
Chris Lattnere168f762006-11-10 05:29:30 +00001099 return FD;
1100}
1101
Steve Naroffb313fc32007-11-11 23:20:51 +00001102Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1103 Decl *dcl = static_cast<Decl *>(D);
1104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1105 FD->setBody((Stmt*)Body);
1106 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroffd78c81b2007-12-13 18:18:56 +00001107 CurFunctionDecl = 0;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001108 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00001109 MD->setBody((Stmt*)Body);
Steve Naroffe3d1ab22007-11-12 13:56:41 +00001110 CurMethodDecl = 0;
Steve Naroffd78c81b2007-12-13 18:18:56 +00001111 }
Chris Lattnere2473062007-05-28 06:28:18 +00001112 // Verify and clean out per-function state.
1113
1114 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001115 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1116 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00001117 // Verify that we have no forward references left. If so, there was a goto
1118 // or address of a label taken, but no definition of it. Label fwd
1119 // definitions are indicated with a null substmt.
1120 if (I->second->getSubStmt() == 0) {
1121 LabelStmt *L = I->second;
1122 // Emit error.
Chris Lattnereefa10e2007-05-28 06:56:27 +00001123 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
Chris Lattnere2473062007-05-28 06:28:18 +00001124
1125 // At this point, we have gotos that use the bogus label. Stitch it into
1126 // the function body so that they aren't leaked and that the AST is well
1127 // formed.
Chris Lattner3efff542008-01-25 00:01:10 +00001128 if (Body) {
1129 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1130 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1131 } else {
1132 // The whole function wasn't parsed correctly, just delete this.
1133 delete L;
1134 }
Chris Lattnere2473062007-05-28 06:28:18 +00001135 }
1136 }
1137 LabelMap.clear();
1138
Steve Naroffb313fc32007-11-11 23:20:51 +00001139 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00001140}
1141
Chris Lattnerac18be92006-11-20 06:49:47 +00001142/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1143/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff2f742082007-09-16 16:16:00 +00001144ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1145 IdentifierInfo &II, Scope *S) {
Chris Lattnerac18be92006-11-20 06:49:47 +00001146 if (getLangOptions().C99) // Extension in C99.
1147 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1148 else // Legal in C90, but warn about it.
1149 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1150
1151 // FIXME: handle stuff like:
1152 // void foo() { extern float X(); }
1153 // void bar() { X(); } <-- implicit decl for X in another scope.
1154
1155 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00001156 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00001157 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00001158 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00001159 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00001160 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00001161 Declarator D(DS, Declarator::BlockContext);
Chris Lattnercbc426d2006-12-02 06:43:02 +00001162 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
Chris Lattnerac18be92006-11-20 06:49:47 +00001163 D.SetIdentifier(&II, Loc);
1164
Chris Lattner62d2e662007-01-28 00:21:37 +00001165 // Find translation-unit scope to insert this function into.
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001166 if (Scope *FnS = S->getFnParent())
1167 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner62d2e662007-01-28 00:21:37 +00001168 while (S->getParent())
1169 S = S->getParent();
Chris Lattnerac18be92006-11-20 06:49:47 +00001170
Steve Naroff2f742082007-09-16 16:16:00 +00001171 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattnerac18be92006-11-20 06:49:47 +00001172}
1173
Chris Lattner302b4be2006-11-19 02:31:38 +00001174
Chris Lattner07b201d2007-11-14 06:34:38 +00001175TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroffa23cc792007-09-13 23:52:58 +00001176 ScopedDecl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00001177 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00001178 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001179
Chris Lattner18b19622007-01-22 07:39:13 +00001180 // Scope manipulation handled by caller.
Chris Lattner96c460d2008-03-15 21:32:50 +00001181 TypedefDecl *NewTD = TypedefDecl::Create(Context, D.getIdentifierLoc(),
Chris Lattnera7b32872008-03-15 06:12:44 +00001182 D.getIdentifier(),
Chris Lattner96c460d2008-03-15 21:32:50 +00001183 T, LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +00001184 if (D.getInvalidType())
1185 NewTD->setInvalidDecl();
1186 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00001187}
1188
Steve Naroff30d242c2007-09-15 18:49:24 +00001189/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00001190/// former case, Name will be non-null. In the later case, Name will be null.
1191/// TagType indicates what kind of tag this is. TK indicates whether this is a
1192/// reference/declaration/definition of a tag.
Steve Naroff30d242c2007-09-15 18:49:24 +00001193Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001194 SourceLocation KWLoc, IdentifierInfo *Name,
Steve Naroffb3096442007-06-09 03:47:53 +00001195 SourceLocation NameLoc, AttributeList *Attr) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001196 // If this is a use of an existing tag, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001197 assert((Name != 0 || TK == TK_Definition) &&
1198 "Nameless record must be a definition!");
Chris Lattner8799cf22007-01-23 01:57:16 +00001199
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001200 Decl::Kind Kind;
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001201 switch (TagType) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001202 default: assert(0 && "Unknown tag type!");
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001203 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1204 case DeclSpec::TST_union: Kind = Decl::Union; break;
1205//case DeclSpec::TST_class: Kind = Decl::Class; break;
1206 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001207 }
Chris Lattner7e783a12007-01-23 02:05:42 +00001208
Chris Lattner18b19622007-01-22 07:39:13 +00001209 // If this is a named struct, check to see if there was a previous forward
1210 // declaration or definition.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001211 if (TagDecl *PrevDecl =
Steve Naroff2fc93f52008-04-02 14:35:35 +00001212 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner8799cf22007-01-23 01:57:16 +00001213
1214 // If this is a use of a previous tag, or if the tag is already declared in
1215 // the same scope (so that the definition/declaration completes or
1216 // rementions the tag), reuse the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001217 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
Chris Lattner7e783a12007-01-23 02:05:42 +00001218 // Make sure that this wasn't declared as an enum and now used as a struct
1219 // or something similar.
1220 if (PrevDecl->getKind() != Kind) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001221 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Chris Lattner7e783a12007-01-23 02:05:42 +00001222 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1223 }
Chris Lattner7b9ace62007-01-23 20:11:08 +00001224
1225 // If this is a use or a forward declaration, we're good.
1226 if (TK != TK_Definition)
1227 return PrevDecl;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001228
Chris Lattner7b9ace62007-01-23 20:11:08 +00001229 // Diagnose attempts to redefine a tag.
1230 if (PrevDecl->isDefinition()) {
1231 Diag(NameLoc, diag::err_redefinition, Name->getName());
1232 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1233 // If this is a redefinition, recover by making this struct be
1234 // anonymous, which will make any later references get the previous
1235 // definition.
1236 Name = 0;
1237 } else {
1238 // Okay, this is definition of a previously declared or referenced tag.
1239 // Move the location of the decl to be the definition site.
1240 PrevDecl->setLocation(NameLoc);
Chris Lattner7b9ace62007-01-23 20:11:08 +00001241 return PrevDecl;
1242 }
Chris Lattner8799cf22007-01-23 01:57:16 +00001243 }
Chris Lattnerf34c4da2007-01-23 04:08:05 +00001244 // If we get here, this is a definition of a new struct type in a nested
1245 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1246 // type.
Chris Lattner18b19622007-01-22 07:39:13 +00001247 }
1248
Chris Lattnerbf0b7982007-01-23 04:27:41 +00001249 // If there is an identifier, use the location of the identifier as the
1250 // location of the decl, otherwise use the location of the struct/union
1251 // keyword.
1252 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1253
Chris Lattner18b19622007-01-22 07:39:13 +00001254 // Otherwise, if this is the first time we've seen this tag, create the decl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00001255 TagDecl *New;
Chris Lattner720a0542007-01-25 00:44:24 +00001256 switch (Kind) {
1257 default: assert(0 && "Unknown tag kind!");
Chris Lattner5f521502007-01-25 06:27:24 +00001258 case Decl::Enum:
Chris Lattner776fac82007-06-09 00:53:06 +00001259 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1260 // enum X { A, B, C } D; D should chain to X.
Chris Lattner96c460d2008-03-15 21:32:50 +00001261 New = EnumDecl::Create(Context, Loc, Name, 0);
Chris Lattner5f521502007-01-25 06:27:24 +00001262 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00001263 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Chris Lattner5f521502007-01-25 06:27:24 +00001264 break;
Chris Lattner720a0542007-01-25 00:44:24 +00001265 case Decl::Union:
1266 case Decl::Struct:
1267 case Decl::Class:
Chris Lattner776fac82007-06-09 00:53:06 +00001268 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1269 // struct X { int A; } D; D should chain to X.
Chris Lattner96c460d2008-03-15 21:32:50 +00001270 New = RecordDecl::Create(Context, Kind, Loc, Name, 0);
Chris Lattner720a0542007-01-25 00:44:24 +00001271 break;
1272 }
Chris Lattner18b19622007-01-22 07:39:13 +00001273
1274 // If this has an identifier, add it to the scope stack.
1275 if (Name) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001276 // The scope passed in may not be a decl scope. Zip up the scope tree until
1277 // we find one that is.
1278 while ((S->getFlags() & Scope::DeclScope) == 0)
1279 S = S->getParent();
1280
1281 // Add it to the decl chain.
Steve Naroff9324db12007-09-13 18:10:37 +00001282 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner18b19622007-01-22 07:39:13 +00001283 Name->setFETokenInfo(New);
1284 S->AddDecl(New);
1285 }
Chris Lattner622c1932008-02-06 00:51:33 +00001286
Anders Carlsson28e71082008-02-16 00:29:18 +00001287 HandleDeclAttributes(New, Attr, 0);
Chris Lattner18b19622007-01-22 07:39:13 +00001288 return New;
1289}
Chris Lattner1300fb92007-01-23 23:42:53 +00001290
Steve Naroff30d242c2007-09-15 18:49:24 +00001291/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00001292/// to create a FieldDecl object for it.
Chris Lattner2a520832008-03-16 01:16:52 +00001293Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
Chris Lattner1300fb92007-01-23 23:42:53 +00001294 SourceLocation DeclStart,
1295 Declarator &D, ExprTy *BitfieldWidth) {
1296 IdentifierInfo *II = D.getIdentifier();
1297 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner2a520832008-03-16 01:16:52 +00001298 Decl *TagDecl = static_cast<Decl *>(tagDecl);
Chris Lattner1300fb92007-01-23 23:42:53 +00001299 SourceLocation Loc = DeclStart;
1300 if (II) Loc = D.getIdentifierLoc();
1301
Chris Lattner62d2e662007-01-28 00:21:37 +00001302 // FIXME: Unnamed fields can be handled in various different ways, for
1303 // example, unnamed unions inject all members into the struct namespace!
1304
1305
Chris Lattner1300fb92007-01-23 23:42:53 +00001306 if (BitWidth) {
1307 // TODO: Validate.
Steve Narofff84d11f2007-05-23 21:48:04 +00001308 //printf("WARNING: BITFIELDS IGNORED!\n");
Chris Lattner1300fb92007-01-23 23:42:53 +00001309
1310 // 6.7.2.1p3
1311 // 6.7.2.1p4
1312
1313 } else {
1314 // Not a bitfield.
1315
1316 // validate II.
1317
1318 }
1319
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001320 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001321 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1322 bool InvalidDecl = false;
Steve Naroff096dd942007-08-31 17:20:07 +00001323
Steve Naroff8eeeb132007-05-08 21:09:37 +00001324 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1325 // than a variably modified type.
Eli Friedman9e805b22008-02-15 12:53:51 +00001326 if (T->isVariablyModifiedType()) {
1327 // FIXME: This diagnostic needs work
1328 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff096dd942007-08-31 17:20:07 +00001329 InvalidDecl = true;
Steve Naroff8eeeb132007-05-08 21:09:37 +00001330 }
Chris Lattner776fac82007-06-09 00:53:06 +00001331 // FIXME: Chain fielddecls together.
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001332 FieldDecl *NewFD;
1333
Chris Lattner2a520832008-03-16 01:16:52 +00001334 if (isa<RecordDecl>(TagDecl))
Chris Lattneree1284a2008-03-16 00:16:02 +00001335 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Chris Lattner2a520832008-03-16 01:16:52 +00001336 else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1337 isa<ObjCImplementationDecl>(TagDecl) ||
1338 isa<ObjCCategoryDecl>(TagDecl) ||
Steve Naroff9e0887cf2007-11-14 14:15:31 +00001339 // FIXME: ivars are currently used to model properties, and
1340 // properties can appear within a protocol.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001341 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
Chris Lattner2a520832008-03-16 01:16:52 +00001342 isa<ObjCProtocolDecl>(TagDecl))
Chris Lattner96c501e2008-03-16 01:15:50 +00001343 NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001344 else
Steve Naroff30d242c2007-09-15 18:49:24 +00001345 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Narofff2fb4ad2007-09-11 21:17:26 +00001346
Anders Carlsson28e71082008-02-16 00:29:18 +00001347 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1348 D.getAttributes());
1349
Steve Narofff93b6722007-08-28 20:14:24 +00001350 if (D.getInvalidType() || InvalidDecl)
1351 NewFD->setInvalidDecl();
1352 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00001353}
1354
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001355/// TranslateIvarVisibility - Translate visibility from a token ID to an
1356/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001357static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001358TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00001359 switch (ivarVisibility) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001360 case tok::objc_private: return ObjCIvarDecl::Private;
1361 case tok::objc_public: return ObjCIvarDecl::Public;
1362 case tok::objc_protected: return ObjCIvarDecl::Protected;
1363 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001364 default: assert(false && "Unknown visitibility kind");
Steve Naroff2e688fd2007-09-14 23:09:53 +00001365 }
1366}
1367
Fariborz Jahanian343f7092007-09-29 00:54:24 +00001368void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00001369 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00001370 DeclTy **Fields, unsigned NumFields,
Steve Naroff33a1e802007-10-29 21:38:07 +00001371 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff30d242c2007-09-15 18:49:24 +00001372 tok::ObjCKeywordKind *visibility) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001373 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1374 assert(EnclosingDecl && "missing record or interface decl");
1375 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1376
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001377 if (Record && Record->isDefinition()) {
Chris Lattner1300fb92007-01-23 23:42:53 +00001378 // Diagnose code like:
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001379 // struct S { struct S {} X; };
Chris Lattner1300fb92007-01-23 23:42:53 +00001380 // We discover this when we complete the outer S. Reject and ignore the
1381 // outer S.
1382 Diag(Record->getLocation(), diag::err_nested_redefinition,
1383 Record->getKindName());
1384 Diag(RecLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001385 Record->setInvalidDecl();
Chris Lattner1300fb92007-01-23 23:42:53 +00001386 return;
1387 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001388 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00001389 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00001390 llvm::SmallVector<FieldDecl*, 32> RecFields;
1391 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroffdb47ee22007-09-14 22:20:54 +00001392
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001393 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001394
Steve Naroffdb47ee22007-09-14 22:20:54 +00001395 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1396 assert(FD && "missing field decl");
1397
1398 // Remember all fields.
1399 RecFields.push_back(FD);
Chris Lattner720a0542007-01-25 00:44:24 +00001400
1401 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001402 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner720a0542007-01-25 00:44:24 +00001403
Steve Naroff2e688fd2007-09-14 23:09:53 +00001404 // If we have visibility info, make sure the AST is set accordingly.
1405 if (visibility)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001406 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00001407 TranslateIvarVisibility(visibility[i]));
Steve Naroff2e688fd2007-09-14 23:09:53 +00001408
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001409 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001410 if (FDTy->isFunctionType()) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00001411 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001412 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001413 FD->setInvalidDecl();
1414 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001415 continue;
1416 }
Chris Lattner82625602007-01-24 02:26:21 +00001417 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00001418 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001419 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian67341402007-10-04 00:45:27 +00001420 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001421 FD->setInvalidDecl();
1422 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00001423 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001424 }
Chris Lattner82625602007-01-24 02:26:21 +00001425 if (i != NumFields-1 || // ... that the last member ...
1426 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00001427 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner82625602007-01-24 02:26:21 +00001428 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001429 FD->setInvalidDecl();
1430 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001431 continue;
1432 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001433 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner82625602007-01-24 02:26:21 +00001434 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1435 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001436 FD->setInvalidDecl();
1437 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00001438 continue;
1439 }
Chris Lattner720a0542007-01-25 00:44:24 +00001440 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001441 if (Record)
1442 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001443 }
Chris Lattner720a0542007-01-25 00:44:24 +00001444 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1445 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00001446 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00001447 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1448 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001449 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner41943152007-01-25 04:52:46 +00001450 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001451 } else {
1452 // If this is a struct/class and this is not the last element, reject
1453 // it. Note that GCC supports variable sized arrays in the middle of
1454 // structures.
1455 if (i != NumFields-1) {
1456 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1457 FD->getName());
Steve Naroffdb47ee22007-09-14 22:20:54 +00001458 FD->setInvalidDecl();
1459 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00001460 continue;
1461 }
Chris Lattner720a0542007-01-25 00:44:24 +00001462 // We support flexible arrays at the end of structs in other structs
1463 // as an extension.
1464 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1465 FD->getName());
Fariborz Jahanian67341402007-10-04 00:45:27 +00001466 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001467 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00001468 }
1469 }
1470 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001471 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001472 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00001473 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1474 FD->getName());
1475 FD->setInvalidDecl();
1476 EnclosingDecl->setInvalidDecl();
1477 continue;
1478 }
Chris Lattner82625602007-01-24 02:26:21 +00001479 // Keep track of the number of named members.
Chris Lattnere5a66562007-01-25 22:48:42 +00001480 if (IdentifierInfo *II = FD->getIdentifier()) {
1481 // Detect duplicate member names.
Chris Lattnerbaf33662007-01-27 02:14:08 +00001482 if (!FieldIDs.insert(II)) {
Chris Lattnere5a66562007-01-25 22:48:42 +00001483 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1484 // Find the previous decl.
1485 SourceLocation PrevLoc;
1486 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1487 assert(i != e && "Didn't find previous def!");
1488 if (RecFields[i]->getIdentifier() == II) {
1489 PrevLoc = RecFields[i]->getLocation();
1490 break;
1491 }
1492 }
1493 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroffdb47ee22007-09-14 22:20:54 +00001494 FD->setInvalidDecl();
1495 EnclosingDecl->setInvalidDecl();
Chris Lattnere5a66562007-01-25 22:48:42 +00001496 continue;
1497 }
Chris Lattner82625602007-01-24 02:26:21 +00001498 ++NumNamedMembers;
Chris Lattnere5a66562007-01-25 22:48:42 +00001499 }
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00001500 }
Chris Lattner82625602007-01-24 02:26:21 +00001501
Chris Lattner82625602007-01-24 02:26:21 +00001502 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00001503 if (Record) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00001504 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner622c1932008-02-06 00:51:33 +00001505 Consumer.HandleTagDeclDefinition(Record);
1506 } else {
Chris Lattner9413a012008-02-05 22:40:55 +00001507 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1508 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1509 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1510 else if (ObjCImplementationDecl *IMPDecl =
1511 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001512 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1513 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00001514 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00001515 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00001516 }
Chris Lattner1300fb92007-01-23 23:42:53 +00001517}
1518
Steve Naroff30d242c2007-09-15 18:49:24 +00001519Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00001520 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001521 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00001522 SourceLocation EqualLoc, ExprTy *val) {
1523 theEnumDecl = theEnumDecl; // silence unused warning.
1524 EnumConstantDecl *LastEnumConst =
1525 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1526 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001527
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001528 // The scope passed in may not be a decl scope. Zip up the scope tree until
1529 // we find one that is.
1530 while ((S->getFlags() & Scope::DeclScope) == 0)
1531 S = S->getParent();
1532
Chris Lattner8116d1b2007-01-25 22:38:29 +00001533 // Verify that there isn't already something declared with this name in this
1534 // scope.
Steve Naroff2fc93f52008-04-02 14:35:35 +00001535 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00001536 if (S->isDeclScope(PrevDecl)) {
1537 if (isa<EnumConstantDecl>(PrevDecl))
1538 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1539 else
1540 Diag(IdLoc, diag::err_redefinition, Id->getName());
1541 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner77683132008-02-26 00:33:57 +00001542 delete Val;
Chris Lattner8116d1b2007-01-25 22:38:29 +00001543 return 0;
1544 }
1545 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001546
Chris Lattner23b7eb62007-06-15 23:05:46 +00001547 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00001548 QualType EltTy;
1549 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00001550 // Make sure to promote the operand type to int.
1551 UsualUnaryConversions(Val);
1552
Chris Lattner4ef40012007-06-11 01:28:17 +00001553 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1554 SourceLocation ExpLoc;
Chris Lattner0e9d6222007-07-15 23:26:56 +00001555 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner4ef40012007-06-11 01:28:17 +00001556 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1557 Id->getName());
Chris Lattner77683132008-02-26 00:33:57 +00001558 delete Val;
Chris Lattnerf283a372007-08-27 17:37:24 +00001559 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00001560 } else {
1561 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00001562 }
Chris Lattnerf283a372007-08-27 17:37:24 +00001563 }
1564
1565 if (!Val) {
1566 if (LastEnumConst) {
1567 // Assign the last value + 1.
1568 EnumVal = LastEnumConst->getInitVal();
1569 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00001570
1571 // Check for overflow on increment.
1572 if (EnumVal < LastEnumConst->getInitVal())
1573 Diag(IdLoc, diag::warn_enum_value_overflow);
1574
Chris Lattnerf283a372007-08-27 17:37:24 +00001575 EltTy = LastEnumConst->getType();
1576 } else {
1577 // First value, set to zero.
1578 EltTy = Context.IntTy;
Chris Lattner37e05872008-03-05 18:54:05 +00001579 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerf283a372007-08-27 17:37:24 +00001580 }
Steve Naroff63969212007-05-07 21:22:42 +00001581 }
Chris Lattner4ef40012007-06-11 01:28:17 +00001582
Chris Lattnera7b32872008-03-15 06:12:44 +00001583 EnumConstantDecl *New =
Chris Lattner96c460d2008-03-15 21:32:50 +00001584 EnumConstantDecl::Create(Context, IdLoc, Id, EltTy, Val, EnumVal,
1585 LastEnumConst);
Chris Lattner8116d1b2007-01-25 22:38:29 +00001586
1587 // Register this decl in the current scope stack.
Steve Naroff9324db12007-09-13 18:10:37 +00001588 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner8116d1b2007-01-25 22:38:29 +00001589 Id->setFETokenInfo(New);
1590 S->AddDecl(New);
1591 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001592}
1593
Steve Naroff30d242c2007-09-15 18:49:24 +00001594void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00001595 DeclTy **Elements, unsigned NumElements) {
1596 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1597 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1598
Chris Lattner67933c02007-08-28 05:10:31 +00001599 // TODO: If the result value doesn't fit in an int, it must be a long or long
1600 // long value. ISO C does not support this, but GCC does as an extension,
1601 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00001602 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner67933c02007-08-28 05:10:31 +00001603
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001604 // Verify that all the values are okay, compute the size of the values, and
1605 // reverse the list.
1606 unsigned NumNegativeBits = 0;
1607 unsigned NumPositiveBits = 0;
1608
1609 // Keep track of whether all elements have type int.
1610 bool AllElementsInt = true;
1611
Chris Lattner4ef40012007-06-11 01:28:17 +00001612 EnumConstantDecl *EltList = 0;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001613 for (unsigned i = 0; i != NumElements; ++i) {
1614 EnumConstantDecl *ECD =
1615 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1616 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001617
1618 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001619 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner77683132008-02-26 00:33:57 +00001620 assert(InitVal.getBitWidth() >= IntWidth &&
1621 "Should have promoted value to int");
Chris Lattnerbf478cb2007-08-28 05:27:00 +00001622 if (InitVal.getBitWidth() > IntWidth) {
1623 llvm::APSInt V(InitVal);
1624 V.trunc(IntWidth);
1625 V.extend(InitVal.getBitWidth());
1626 if (V != InitVal)
1627 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1628 InitVal.toString());
1629 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001630
1631 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00001632 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00001633 NumPositiveBits = std::max(NumPositiveBits,
1634 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001635 else
Chris Lattner49f980c2008-01-14 21:47:29 +00001636 NumNegativeBits = std::max(NumNegativeBits,
1637 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00001638
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001639 // Keep track of whether every enum element has type int (very commmon).
1640 if (AllElementsInt)
1641 AllElementsInt = ECD->getType() == Context.IntTy;
1642
Chris Lattner4ef40012007-06-11 01:28:17 +00001643 ECD->setNextDeclarator(EltList);
1644 EltList = ECD;
Chris Lattnerc1915e22007-01-25 07:29:02 +00001645 }
1646
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001647 // Figure out the type that should be used for this enum.
1648 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1649 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001650 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001651
1652 if (NumNegativeBits) {
1653 // If there is a negative value, figure out the smallest integer type (of
1654 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001655 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001656 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001657 BestWidth = IntWidth;
1658 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00001659 BestWidth = Context.Target.getLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001660
Chris Lattner3a370bf2007-08-29 17:31:48 +00001661 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001662 BestType = Context.LongTy;
1663 else {
Chris Lattner37e05872008-03-05 18:54:05 +00001664 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00001665
Chris Lattner3a370bf2007-08-29 17:31:48 +00001666 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001667 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1668 BestType = Context.LongLongTy;
1669 }
1670 }
1671 } else {
1672 // If there is no negative value, figure out which of uint, ulong, ulonglong
1673 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00001674 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001675 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00001676 BestWidth = IntWidth;
1677 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00001678 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001679 BestType = Context.UnsignedLongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00001680 } else {
1681 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00001682 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001683 "How could an initializer get larger than ULL?");
1684 BestType = Context.UnsignedLongLongTy;
1685 }
1686 }
1687
Chris Lattner3a370bf2007-08-29 17:31:48 +00001688 // Loop over all of the enumerator constants, changing their types to match
1689 // the type of the enum if needed.
1690 for (unsigned i = 0; i != NumElements; ++i) {
1691 EnumConstantDecl *ECD =
1692 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1693 if (!ECD) continue; // Already issued a diagnostic.
1694
1695 // Standard C says the enumerators have int type, but we allow, as an
1696 // extension, the enumerators to be larger than int size. If each
1697 // enumerator value fits in an int, type it as an int, otherwise type it the
1698 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1699 // that X has type 'int', not 'unsigned'.
Chris Lattner77683132008-02-26 00:33:57 +00001700 if (ECD->getType() == Context.IntTy) {
1701 // Make sure the init value is signed.
1702 llvm::APSInt IV = ECD->getInitVal();
1703 IV.setIsSigned(true);
1704 ECD->setInitVal(IV);
Chris Lattner3a370bf2007-08-29 17:31:48 +00001705 continue; // Already int type.
Chris Lattner77683132008-02-26 00:33:57 +00001706 }
Chris Lattner3a370bf2007-08-29 17:31:48 +00001707
1708 // Determine whether the value fits into an int.
1709 llvm::APSInt InitVal = ECD->getInitVal();
1710 bool FitsInInt;
1711 if (InitVal.isUnsigned() || !InitVal.isNegative())
1712 FitsInInt = InitVal.getActiveBits() < IntWidth;
1713 else
1714 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1715
1716 // If it fits into an integer type, force it. Otherwise force it to match
1717 // the enum decl type.
1718 QualType NewTy;
1719 unsigned NewWidth;
1720 bool NewSign;
1721 if (FitsInInt) {
1722 NewTy = Context.IntTy;
1723 NewWidth = IntWidth;
1724 NewSign = true;
1725 } else if (ECD->getType() == BestType) {
1726 // Already the right type!
1727 continue;
1728 } else {
1729 NewTy = BestType;
1730 NewWidth = BestWidth;
1731 NewSign = BestType->isSignedIntegerType();
1732 }
1733
1734 // Adjust the APSInt value.
1735 InitVal.extOrTrunc(NewWidth);
1736 InitVal.setIsSigned(NewSign);
1737 ECD->setInitVal(InitVal);
1738
1739 // Adjust the Expr initializer and type.
1740 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1741 ECD->setType(NewTy);
1742 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00001743
Chris Lattner1c1f9322007-08-28 18:24:31 +00001744 Enum->defineElements(EltList, BestType);
Chris Lattner622c1932008-02-06 00:51:33 +00001745 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +00001746}
Chris Lattner1300fb92007-01-23 23:42:53 +00001747
Anders Carlsson5c6c0592008-02-08 00:33:21 +00001748Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1749 ExprTy *expr) {
1750 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1751
Chris Lattneree1284a2008-03-16 00:16:02 +00001752 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson5c6c0592008-02-08 00:33:21 +00001753}
1754
Chris Lattner38376f12008-01-12 07:05:38 +00001755Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnereb85ab42008-02-25 21:04:36 +00001756 SourceLocation LBrace,
1757 SourceLocation RBrace,
1758 const char *Lang,
1759 unsigned StrSize,
1760 DeclTy *D) {
Chris Lattner38376f12008-01-12 07:05:38 +00001761 LinkageSpecDecl::LanguageIDs Language;
1762 Decl *dcl = static_cast<Decl *>(D);
1763 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1764 Language = LinkageSpecDecl::lang_c;
1765 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1766 Language = LinkageSpecDecl::lang_cxx;
1767 else {
1768 Diag(Loc, diag::err_bad_language);
1769 return 0;
1770 }
1771
1772 // FIXME: Add all the various semantics of linkage specifications
Chris Lattneree1284a2008-03-16 00:16:02 +00001773 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner38376f12008-01-12 07:05:38 +00001774}
1775
Chris Lattneree0d2712008-02-21 00:48:22 +00001776void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson081f1b42007-12-19 06:16:30 +00001777
Chris Lattneree0d2712008-02-21 00:48:22 +00001778 switch (Attr->getKind()) {
Chris Lattnerf1791902008-02-20 23:17:35 +00001779 case AttributeList::AT_vector_size:
Steve Naroffa8fd9732007-06-11 00:35:03 +00001780 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattneree0d2712008-02-21 00:48:22 +00001781 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001782 if (!newType.isNull()) // install the new vector type into the decl
1783 vDecl->setType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001784 }
1785 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001786 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001787 Attr);
Steve Naroff4dddb612007-07-09 18:55:26 +00001788 if (!newType.isNull()) // install the new vector type into the decl
1789 tDecl->setUnderlyingType(newType);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001790 }
Chris Lattnerf1791902008-02-20 23:17:35 +00001791 break;
1792 case AttributeList::AT_ocu_vector_type:
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001793 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattneree0d2712008-02-21 00:48:22 +00001794 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001795 else
Chris Lattneree0d2712008-02-21 00:48:22 +00001796 Diag(Attr->getLoc(),
Steve Naroff91fcddb2007-07-18 18:00:27 +00001797 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattnerf1791902008-02-20 23:17:35 +00001798 break;
1799 case AttributeList::AT_address_space:
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001800 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1801 QualType newType = HandleAddressSpaceTypeAttribute(
1802 tDecl->getUnderlyingType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001803 Attr);
1804 tDecl->setUnderlyingType(newType);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001805 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1806 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattneree0d2712008-02-21 00:48:22 +00001807 Attr);
1808 // install the new addr spaced type into the decl
1809 vDecl->setType(newType);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001810 }
Chris Lattnerf1791902008-02-20 23:17:35 +00001811 break;
Chris Lattner8a8558b2008-02-29 16:48:43 +00001812 case AttributeList::AT_deprecated:
Chris Lattner84966392008-03-03 03:28:21 +00001813 HandleDeprecatedAttribute(New, Attr);
1814 break;
1815 case AttributeList::AT_visibility:
1816 HandleVisibilityAttribute(New, Attr);
1817 break;
1818 case AttributeList::AT_weak:
1819 HandleWeakAttribute(New, Attr);
1820 break;
1821 case AttributeList::AT_dllimport:
1822 HandleDLLImportAttribute(New, Attr);
1823 break;
1824 case AttributeList::AT_dllexport:
1825 HandleDLLExportAttribute(New, Attr);
1826 break;
1827 case AttributeList::AT_nothrow:
1828 HandleNothrowAttribute(New, Attr);
Chris Lattner8a8558b2008-02-29 16:48:43 +00001829 break;
Nate Begeman0a6192c2008-03-07 20:04:22 +00001830 case AttributeList::AT_stdcall:
1831 HandleStdCallAttribute(New, Attr);
1832 break;
1833 case AttributeList::AT_fastcall:
1834 HandleFastCallAttribute(New, Attr);
1835 break;
Chris Lattnerf1791902008-02-20 23:17:35 +00001836 case AttributeList::AT_aligned:
Chris Lattneree0d2712008-02-21 00:48:22 +00001837 HandleAlignedAttribute(New, Attr);
Chris Lattnerf1791902008-02-20 23:17:35 +00001838 break;
1839 case AttributeList::AT_packed:
Chris Lattneree0d2712008-02-21 00:48:22 +00001840 HandlePackedAttribute(New, Attr);
Chris Lattnerf1791902008-02-20 23:17:35 +00001841 break;
Nate Begemand45d38d2008-02-21 19:30:49 +00001842 case AttributeList::AT_annotate:
1843 HandleAnnotateAttribute(New, Attr);
1844 break;
Ted Kremenekf7146ca2008-02-27 20:43:06 +00001845 case AttributeList::AT_noreturn:
1846 HandleNoReturnAttribute(New, Attr);
1847 break;
Chris Lattner84966392008-03-03 03:28:21 +00001848 case AttributeList::AT_format:
1849 HandleFormatAttribute(New, Attr);
1850 break;
Chris Lattnerf1791902008-02-20 23:17:35 +00001851 default:
Chris Lattner8a8558b2008-02-29 16:48:43 +00001852#if 0
1853 // TODO: when we have the full set of attributes, warn about unknown ones.
1854 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1855 Attr->getName()->getName());
1856#endif
Chris Lattnerf1791902008-02-20 23:17:35 +00001857 break;
1858 }
Steve Naroffa8fd9732007-06-11 00:35:03 +00001859}
1860
1861void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1862 AttributeList *declarator_postfix) {
1863 while (declspec_prefix) {
1864 HandleDeclAttribute(New, declspec_prefix);
1865 declspec_prefix = declspec_prefix->getNext();
1866 }
1867 while (declarator_postfix) {
1868 HandleDeclAttribute(New, declarator_postfix);
1869 declarator_postfix = declarator_postfix->getNext();
1870 }
1871}
1872
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001873void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1874 AttributeList *rawAttr) {
1875 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson721f6012007-12-19 07:19:40 +00001876 // check the attribute arguments.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001877 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001878 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001879 std::string("1"));
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001880 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001881 }
1882 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1883 llvm::APSInt vecSize(32);
1884 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001885 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001886 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001887 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001888 }
1889 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1890 // in conjunction with complex types (pointers, arrays, functions, etc.).
1891 Type *canonType = curType.getCanonicalType().getTypePtr();
1892 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001893 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001894 curType.getCanonicalType().getAsString());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001895 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001896 }
1897 // unlike gcc's vector_size attribute, the size is specified as the
1898 // number of elements, not the number of bytes.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001899 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff91fcddb2007-07-18 18:00:27 +00001900
1901 if (vectorSize == 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001902 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff91fcddb2007-07-18 18:00:27 +00001903 sizeExpr->getSourceRange());
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001904 return;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001905 }
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001906 // Instantiate/Install the vector type, the number of elements is > 0.
1907 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1908 // Remember this typedef decl, we will need it later for diagnostics.
1909 OCUVectorDecls.push_back(tDecl);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001910}
1911
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001912QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattner983a8bb2007-07-13 22:13:22 +00001913 AttributeList *rawAttr) {
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001914 // check the attribute arugments.
Steve Naroffa8fd9732007-06-11 00:35:03 +00001915 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001916 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroffa8fd9732007-06-11 00:35:03 +00001917 std::string("1"));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001918 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001919 }
1920 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
Chris Lattner23b7eb62007-06-15 23:05:46 +00001921 llvm::APSInt vecSize(32);
Chris Lattner0e9d6222007-07-15 23:26:56 +00001922 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001923 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00001924 "vector_size", sizeExpr->getSourceRange());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001925 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001926 }
1927 // navigate to the base type - we need to provide for vector pointers,
1928 // vector arrays, and functions returning vectors.
1929 Type *canonType = curType.getCanonicalType().getTypePtr();
1930
Steve Naroff91fcddb2007-07-18 18:00:27 +00001931 if (canonType->isPointerType() || canonType->isArrayType() ||
1932 canonType->isFunctionType()) {
Chris Lattner0f8a39c2007-12-19 05:38:06 +00001933 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff91fcddb2007-07-18 18:00:27 +00001934 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1935 do {
1936 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1937 canonType = PT->getPointeeType().getTypePtr();
1938 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1939 canonType = AT->getElementType().getTypePtr();
1940 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1941 canonType = FT->getResultType().getTypePtr();
1942 } while (canonType->isPointerType() || canonType->isArrayType() ||
1943 canonType->isFunctionType());
1944 */
Steve Naroffa8fd9732007-06-11 00:35:03 +00001945 }
1946 // the base type must be integer or float.
1947 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001948 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroffa8fd9732007-06-11 00:35:03 +00001949 curType.getCanonicalType().getAsString());
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001950 return QualType();
Steve Naroffa8fd9732007-06-11 00:35:03 +00001951 }
Chris Lattner37e05872008-03-05 18:54:05 +00001952 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001953 // vecSize is specified in bytes - convert to bits.
Chris Lattner9cf21c52007-09-04 02:45:27 +00001954 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001955
1956 // the vector size needs to be an integral multiple of the type size.
1957 if (vectorSize % typeSize) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001958 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001959 sizeExpr->getSourceRange());
1960 return QualType();
1961 }
1962 if (vectorSize == 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001963 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001964 sizeExpr->getSourceRange());
1965 return QualType();
1966 }
Nate Begemand45d38d2008-02-21 19:30:49 +00001967 // Instantiate the vector type, the number of elements is > 0, and not
1968 // required to be a power of 2, unlike GCC.
Steve Naroff91fcddb2007-07-18 18:00:27 +00001969 return Context.getVectorType(curType, vectorSize/typeSize);
Steve Naroffa8fd9732007-06-11 00:35:03 +00001970}
1971
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001972void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson28e71082008-02-16 00:29:18 +00001973 // check the attribute arguments.
1974 if (rawAttr->getNumArgs() > 0) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001975 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson28e71082008-02-16 00:29:18 +00001976 std::string("0"));
1977 return;
1978 }
1979
1980 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1981 TD->addAttr(new PackedAttr);
1982 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1983 // If the alignment is less than or equal to 8 bits, the packed attribute
1984 // has no effect.
Chris Lattner37e05872008-03-05 18:54:05 +00001985 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001986 Diag(rawAttr->getLoc(),
Anders Carlsson28e71082008-02-16 00:29:18 +00001987 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001988 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson28e71082008-02-16 00:29:18 +00001989 else
Anders Carlsson4b939792008-02-16 00:39:40 +00001990 FD->addAttr(new PackedAttr);
Anders Carlsson28e71082008-02-16 00:29:18 +00001991 } else
Chris Lattnerdcee3a92008-02-20 23:25:22 +00001992 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
1993 rawAttr->getName()->getName());
Anders Carlsson28e71082008-02-16 00:29:18 +00001994}
Nate Begemand45d38d2008-02-21 19:30:49 +00001995
Ted Kremenekf7146ca2008-02-27 20:43:06 +00001996void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
1997 // check the attribute arguments.
1998 if (rawAttr->getNumArgs() != 0) {
1999 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2000 std::string("0"));
2001 return;
2002 }
2003
Ted Kremenek98c56672008-03-03 16:52:27 +00002004 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2005
2006 if (!Fn) {
2007 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2008 "noreturn", "function");
2009 return;
2010 }
2011
Ted Kremenekf7146ca2008-02-27 20:43:06 +00002012 d->addAttr(new NoReturnAttr());
2013}
2014
Chris Lattner84966392008-03-03 03:28:21 +00002015void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2016 // check the attribute arguments.
2017 if (rawAttr->getNumArgs() != 0) {
2018 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2019 std::string("0"));
2020 return;
2021 }
2022
2023 d->addAttr(new DeprecatedAttr());
2024}
2025
2026void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2027 // check the attribute arguments.
Chris Lattner0fdc3792008-03-04 18:08:48 +00002028 if (rawAttr->getNumArgs() != 1) {
Chris Lattner84966392008-03-03 03:28:21 +00002029 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2030 std::string("1"));
2031 return;
2032 }
2033
Chris Lattner0fdc3792008-03-04 18:08:48 +00002034 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2035 Arg = Arg->IgnoreParenCasts();
2036 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2037
2038 if (Str == 0 || Str->isWide()) {
Chris Lattner84966392008-03-03 03:28:21 +00002039 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner0fdc3792008-03-04 18:08:48 +00002040 "visibility", std::string("1"));
Chris Lattner84966392008-03-03 03:28:21 +00002041 return;
2042 }
2043
Chris Lattner0fdc3792008-03-04 18:08:48 +00002044 const char *TypeStr = Str->getStrData();
2045 unsigned TypeLen = Str->getByteLength();
Chris Lattner84966392008-03-03 03:28:21 +00002046 llvm::GlobalValue::VisibilityTypes type;
2047
Chris Lattner0fdc3792008-03-04 18:08:48 +00002048 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattner84966392008-03-03 03:28:21 +00002049 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner0fdc3792008-03-04 18:08:48 +00002050 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattner84966392008-03-03 03:28:21 +00002051 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner0fdc3792008-03-04 18:08:48 +00002052 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattner84966392008-03-03 03:28:21 +00002053 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner0fdc3792008-03-04 18:08:48 +00002054 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattner84966392008-03-03 03:28:21 +00002055 type = llvm::GlobalValue::ProtectedVisibility;
2056 else {
2057 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner0fdc3792008-03-04 18:08:48 +00002058 "visibility", TypeStr);
Chris Lattner84966392008-03-03 03:28:21 +00002059 return;
2060 }
2061
2062 d->addAttr(new VisibilityAttr(type));
2063}
2064
2065void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2066 // check the attribute arguments.
2067 if (rawAttr->getNumArgs() != 0) {
2068 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2069 std::string("0"));
2070 return;
2071 }
2072
2073 d->addAttr(new WeakAttr());
2074}
2075
2076void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2077 // check the attribute arguments.
2078 if (rawAttr->getNumArgs() != 0) {
2079 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2080 std::string("0"));
2081 return;
2082 }
2083
2084 d->addAttr(new DLLImportAttr());
2085}
2086
2087void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2088 // check the attribute arguments.
2089 if (rawAttr->getNumArgs() != 0) {
2090 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2091 std::string("0"));
2092 return;
2093 }
2094
2095 d->addAttr(new DLLExportAttr());
2096}
2097
Nate Begeman0a6192c2008-03-07 20:04:22 +00002098void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2099 // check the attribute arguments.
2100 if (rawAttr->getNumArgs() != 0) {
2101 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2102 std::string("0"));
2103 return;
2104 }
2105
2106 d->addAttr(new StdCallAttr());
2107}
2108
2109void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2110 // check the attribute arguments.
2111 if (rawAttr->getNumArgs() != 0) {
2112 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2113 std::string("0"));
2114 return;
2115 }
2116
2117 d->addAttr(new FastCallAttr());
2118}
2119
Chris Lattner84966392008-03-03 03:28:21 +00002120void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2121 // check the attribute arguments.
2122 if (rawAttr->getNumArgs() != 0) {
2123 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2124 std::string("0"));
2125 return;
2126 }
2127
2128 d->addAttr(new NoThrowAttr());
2129}
2130
Nuno Lopes623207d2008-03-25 23:01:48 +00002131static const FunctionTypeProto *getFunctionProto(Decl *d) {
2132 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2133 if (!decl) return 0;
2134
2135 QualType Ty = decl->getType();
2136
2137 if (Ty->isFunctionPointerType()) {
2138 const PointerType *PtrTy = Ty->getAsPointerType();
2139 Ty = PtrTy->getPointeeType();
2140 }
2141
2142 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2143 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2144
2145 return 0;
2146}
2147
2148
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002149/// Handle __attribute__((format(type,idx,firstarg))) attributes
2150/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner84966392008-03-03 03:28:21 +00002151void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2152
2153 if (!rawAttr->getParameterName()) {
2154 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2155 "format", std::string("1"));
2156 return;
2157 }
2158
2159 if (rawAttr->getNumArgs() != 2) {
2160 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2161 std::string("3"));
2162 return;
2163 }
2164
Nuno Lopes623207d2008-03-25 23:01:48 +00002165 // GCC ignores the format attribute on K&R style function
2166 // prototypes, so we ignore it as well
2167 const FunctionTypeProto *proto = getFunctionProto(d);
2168
2169 if (!proto) {
Chris Lattner84966392008-03-03 03:28:21 +00002170 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2171 "format", "function");
2172 return;
2173 }
2174
2175 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002176 // this is needed in order to be compatible with GCC
Chris Lattner84966392008-03-03 03:28:21 +00002177 // the index must start in 1 and the limit is numargs+1
Nuno Lopes623207d2008-03-25 23:01:48 +00002178 unsigned NumArgs = proto->getNumArgs();
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002179 unsigned FirstIdx = 1;
Chris Lattner84966392008-03-03 03:28:21 +00002180
2181 const char *Format = rawAttr->getParameterName()->getName();
2182 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2183
2184 // Normalize the argument, __foo__ becomes foo.
2185 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2186 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2187 Format += 2;
2188 FormatLen -= 4;
2189 }
2190
2191 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2192 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2193 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2194 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2195 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2196 "format", rawAttr->getParameterName()->getName());
2197 return;
2198 }
2199
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002200 // checks for the 2nd argument
Chris Lattner84966392008-03-03 03:28:21 +00002201 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002202 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner84966392008-03-03 03:28:21 +00002203 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2204 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2205 "format", std::string("2"), IdxExpr->getSourceRange());
2206 return;
2207 }
2208
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002209 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner84966392008-03-03 03:28:21 +00002210 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2211 "format", std::string("2"), IdxExpr->getSourceRange());
2212 return;
2213 }
2214
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002215 // make sure the format string is really a string
2216 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2217 if (!Ty->isPointerType() ||
2218 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2219 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2220 IdxExpr->getSourceRange());
2221 return;
2222 }
2223
2224
2225 // check the 3rd argument
Chris Lattner84966392008-03-03 03:28:21 +00002226 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002227 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner84966392008-03-03 03:28:21 +00002228 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2229 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2230 "format", std::string("3"), FirstArgExpr->getSourceRange());
2231 return;
2232 }
2233
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002234 // check if the function is variadic if the 3rd argument non-zero
2235 if (FirstArg != 0) {
2236 if (proto->isVariadic()) {
2237 ++NumArgs; // +1 for ...
2238 } else {
2239 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2240 return;
2241 }
2242 }
2243
2244 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2245 // the input is just the current time + the format string
Chris Lattner84966392008-03-03 03:28:21 +00002246 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002247 if (FirstArg != 0) {
Chris Lattner84966392008-03-03 03:28:21 +00002248 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2249 FirstArgExpr->getSourceRange());
2250 return;
2251 }
Ted Kremenek7bdd6302008-03-07 18:43:49 +00002252 // if 0 it disables parameter checking (to use with e.g. va_list)
2253 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner84966392008-03-03 03:28:21 +00002254 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2255 "format", std::string("3"), FirstArgExpr->getSourceRange());
2256 return;
2257 }
2258
2259 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2260 Idx.getZExtValue(), FirstArg.getZExtValue()));
2261}
2262
Nate Begemand45d38d2008-02-21 19:30:49 +00002263void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2264 // check the attribute arguments.
2265 if (rawAttr->getNumArgs() != 1) {
2266 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2267 std::string("1"));
2268 return;
2269 }
2270 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2271 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson28e71082008-02-16 00:29:18 +00002272
Nate Begemand45d38d2008-02-21 19:30:49 +00002273 // Make sure that there is a string literal as the annotation's single
2274 // argument.
2275 if (!SE) {
2276 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2277 return;
2278 }
2279 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2280 SE->getByteLength())));
2281}
2282
Anders Carlsson721f6012007-12-19 07:19:40 +00002283void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2284{
2285 // check the attribute arguments.
Eli Friedman3780d352008-01-30 17:38:42 +00002286 if (rawAttr->getNumArgs() > 1) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00002287 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson721f6012007-12-19 07:19:40 +00002288 std::string("1"));
2289 return;
2290 }
Eli Friedman3780d352008-01-30 17:38:42 +00002291
Anders Carlsson6e3ace52008-02-16 19:51:27 +00002292 unsigned Align = 0;
2293
2294 if (rawAttr->getNumArgs() == 0) {
2295 // FIXME: This should be the target specific maximum alignment.
2296 // (For now we just use 128 bits which is the maximum on X86.
2297 Align = 128;
Eli Friedman3780d352008-01-30 17:38:42 +00002298 return;
Anders Carlsson6e3ace52008-02-16 19:51:27 +00002299 } else {
2300 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2301 llvm::APSInt alignment(32);
2302 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattnerdcee3a92008-02-20 23:25:22 +00002303 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson6e3ace52008-02-16 19:51:27 +00002304 "aligned", alignmentExpr->getSourceRange());
2305 return;
2306 }
2307
2308 Align = alignment.getZExtValue() * 8;
2309 }
Eli Friedman3780d352008-01-30 17:38:42 +00002310
Anders Carlsson6e3ace52008-02-16 19:51:27 +00002311 d->addAttr(new AlignedAttr(Align));
Anders Carlsson721f6012007-12-19 07:19:40 +00002312}