blob: 2624f5019db1630e2f897fb9114b1f37e6a44977 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-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
Douglas Gregor2ce52f32008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000042 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Chris Lattner9fdf9c62008-04-22 18:39:57 +000045void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000046 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000047 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000048 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000049 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000050}
51
Chris Lattnerb048c982008-04-06 04:47:34 +000052void Sema::PopDeclContext() {
53 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000054 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000055 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000056 ? Context.getTranslationUnitDecl()
57 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000058}
59
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000060/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
62 IdResolver.AddDecl(D, S);
63 S->AddDecl(D);
64}
65
Steve Naroffb216c882007-10-09 22:01:59 +000066void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000067 if (S->decl_empty()) return;
68 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
69
Reid Spencer5f016e22007-07-11 17:01:13 +000070 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
71 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000072 Decl *TmpD = static_cast<Decl*>(*I);
73 assert(TmpD && "This decl didn't get pushed??");
74 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
75 assert(D && "This decl isn't a ScopedDecl?");
76
Reid Spencer5f016e22007-07-11 17:01:13 +000077 IdentifierInfo *II = D->getIdentifier();
78 if (!II) continue;
79
Chris Lattner7f925cc2008-04-11 07:00:53 +000080 // Unlink this decl from the identifier.
81 IdResolver.RemoveDecl(D);
82
Reid Spencer5f016e22007-07-11 17:01:13 +000083 // This will have to be revisited for C++: there we want to nest stuff in
84 // namespace decls etc. Even for C, we might want a top-level translation
85 // unit decl or something.
86 if (!CurFunctionDecl)
87 continue;
88
89 // Chain this decl to the containing function, it now owns the memory for
90 // the decl.
91 D->setNext(CurFunctionDecl->getDeclChain());
92 CurFunctionDecl->setDeclChain(D);
93 }
94}
95
Steve Naroffe8043c32008-04-01 23:04:06 +000096/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
97/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000098ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000099 // The third "scope" argument is 0 since we aren't enabling lazy built-in
100 // creation from this context.
101 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000102
Steve Naroffb327ce02008-04-02 14:35:35 +0000103 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104}
105
Steve Naroffe8043c32008-04-01 23:04:06 +0000106/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000107/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000108Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
109 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000111 unsigned NS = NSI;
112 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
113 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000118 NamedDecl *ND = IdResolver.Lookup(II, NS);
119 if (ND) return ND;
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 // If we didn't find a use of this identifier, and if the identifier
122 // corresponds to a compiler builtin, create the decl object for the builtin
123 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000124 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000125 if (enableLazyBuiltinCreation) {
126 // If this is a builtin on this (or all) targets, create the decl.
127 if (unsigned BuiltinID = II->getBuiltinID())
128 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
129 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000130 if (getLangOptions().ObjC1) {
131 // @interface and @compatibility_alias introduce typedef-like names.
132 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000133 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000134 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000135 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
136 if (IDI != ObjCInterfaceDecls.end())
137 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000138 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
139 if (I != ObjCAliasDecls.end())
140 return I->second->getClassInterface();
141 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 }
143 return 0;
144}
145
Chris Lattner95e2c712008-05-05 22:18:14 +0000146void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000147 if (!Context.getBuiltinVaListType().isNull())
148 return;
149
150 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000151 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000152 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000153 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
154}
155
Reid Spencer5f016e22007-07-11 17:01:13 +0000156/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
157/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000158ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
159 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 Builtin::ID BID = (Builtin::ID)bid;
161
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000162 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000163 BID == Builtin::BI__builtin_va_copy ||
164 BID == Builtin::BI__builtin_va_end)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000165 InitBuiltinVaListType();
166
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000167 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000168 FunctionDecl *New = FunctionDecl::Create(Context,
169 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000170 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000171 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000172
Chris Lattner95e2c712008-05-05 22:18:14 +0000173 // Create Decl objects for each parameter, adding them to the
174 // FunctionDecl.
175 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
176 llvm::SmallVector<ParmVarDecl*, 16> Params;
177 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
178 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
179 FT->getArgType(i), VarDecl::None, 0,
180 0));
181 New->setParams(&Params[0], Params.size());
182 }
183
184
185
Chris Lattner7f925cc2008-04-11 07:00:53 +0000186 // TUScope is the translation-unit scope to insert this function into.
187 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000188
189 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000190 IdResolver.AddGlobalDecl(New);
191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 return New;
193}
194
195/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
196/// and scope as a previous declaration 'Old'. Figure out how to resolve this
197/// situation, merging decls or emitting diagnostics as appropriate.
198///
Steve Naroffe8043c32008-04-01 23:04:06 +0000199TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 // Verify the old decl was also a typedef.
201 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
202 if (!Old) {
203 Diag(New->getLocation(), diag::err_redefinition_different_kind,
204 New->getName());
205 Diag(OldD->getLocation(), diag::err_previous_definition);
206 return New;
207 }
208
Steve Naroff8ee529b2007-10-31 18:42:27 +0000209 // Allow multiple definitions for ObjC built-in typedefs.
210 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000212 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000213
214 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
215 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
216 // *either* declaration is in a system header. The code below implements
217 // this adhoc compatibility rule. FIXME: The following code will not
218 // work properly when compiling ".i" files (containing preprocessed output).
219 SourceManager &SrcMgr = Context.getSourceManager();
220 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
221 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
222 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
223 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
224 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
225
Steve Naroffc5e2f342008-03-26 21:27:00 +0000226 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
227 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
228 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000229 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000230 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000231
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
233 // TODO: This is totally simplistic. It should handle merging functions
234 // together etc, merging extern int X; int X; ...
235 Diag(New->getLocation(), diag::err_redefinition, New->getName());
236 Diag(Old->getLocation(), diag::err_previous_definition);
237 return New;
238}
239
Chris Lattnerddee4232008-03-03 03:28:21 +0000240/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
241static bool DeclHasAttr(const Decl *decl, const Attr *target) {
242 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
243 if (attr->getKind() == target->getKind())
244 return true;
245
246 return false;
247}
248
249/// MergeAttributes - append attributes from the Old decl to the New one.
250static void MergeAttributes(Decl *New, Decl *Old) {
251 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
252
253// FIXME: fix this code to cleanup the Old attrs correctly
254 while (attr) {
255 tmp = attr;
256 attr = attr->getNext();
257
258 if (!DeclHasAttr(New, tmp)) {
259 New->addAttr(tmp);
260 } else {
261 tmp->setNext(0);
262 delete(tmp);
263 }
264 }
265}
266
Chris Lattner04421082008-04-08 04:40:51 +0000267/// MergeFunctionDecl - We just parsed a function 'New' from
268/// declarator D which has the same name and scope as a previous
269/// declaration 'Old'. Figure out how to resolve this situation,
270/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000271/// Redeclaration will be set true if thisNew is a redeclaration OldD.
272FunctionDecl *
273Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
274 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 // Verify the old decl was also a function.
276 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
277 if (!Old) {
278 Diag(New->getLocation(), diag::err_redefinition_different_kind,
279 New->getName());
280 Diag(OldD->getLocation(), diag::err_previous_definition);
281 return New;
282 }
Chris Lattner04421082008-04-08 04:40:51 +0000283
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000284 QualType OldQType = Context.getCanonicalType(Old->getType());
285 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000286
Chris Lattner04421082008-04-08 04:40:51 +0000287 // C++ [dcl.fct]p3:
288 // All declarations for a function shall agree exactly in both the
289 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000290 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
291 MergeAttributes(New, Old);
292 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000293 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000294 }
Chris Lattner04421082008-04-08 04:40:51 +0000295
296 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000297 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000298 if (!getLangOptions().CPlusPlus &&
299 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000300 MergeAttributes(New, Old);
301 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000302 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000303 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000304
Steve Naroff837618c2008-01-16 15:01:34 +0000305 // A function that has already been declared has been redeclared or defined
306 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000307 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000308 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000309 PrevDiag = diag::err_previous_definition;
310 else if (Old->isImplicit())
311 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000312 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000313 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000314
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
316 // TODO: This is totally simplistic. It should handle merging functions
317 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000318 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
319 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000320 return New;
321}
322
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000323/// equivalentArrayTypes - Used to determine whether two array types are
324/// equivalent.
325/// We need to check this explicitly as an incomplete array definition is
326/// considered a VariableArrayType, so will not match a complete array
327/// definition that would be otherwise equivalent.
328static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
329 const ArrayType *NewAT = NewQType->getAsArrayType();
330 const ArrayType *OldAT = OldQType->getAsArrayType();
331
332 if (!NewAT || !OldAT)
333 return false;
334
335 // If either (or both) array types in incomplete we need to strip off the
336 // outer VariableArrayType. Once the outer VAT is removed the remaining
337 // types must be identical if the array types are to be considered
338 // equivalent.
339 // eg. int[][1] and int[1][1] become
340 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
341 // removing the outermost VAT gives
342 // CAT(1, int) and CAT(1, int)
343 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000344 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000345 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
346 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000347 NewQType = NewAT->getElementType().getCanonicalType();
348 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000349 }
350
351 return NewQType == OldQType;
352}
353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354/// MergeVarDecl - We just parsed a variable 'New' which has the same name
355/// and scope as a previous declaration 'Old'. Figure out how to resolve this
356/// situation, merging decls or emitting diagnostics as appropriate.
357///
358/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
359/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
360///
Steve Naroffe8043c32008-04-01 23:04:06 +0000361VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // Verify the old decl was also a variable.
363 VarDecl *Old = dyn_cast<VarDecl>(OldD);
364 if (!Old) {
365 Diag(New->getLocation(), diag::err_redefinition_different_kind,
366 New->getName());
367 Diag(OldD->getLocation(), diag::err_previous_definition);
368 return New;
369 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000370
371 MergeAttributes(New, Old);
372
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000374 QualType OldCType = Context.getCanonicalType(Old->getType());
375 QualType NewCType = Context.getCanonicalType(New->getType());
376 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 Diag(New->getLocation(), diag::err_redefinition, New->getName());
378 Diag(Old->getLocation(), diag::err_previous_definition);
379 return New;
380 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000381 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
382 if (New->getStorageClass() == VarDecl::Static &&
383 (Old->getStorageClass() == VarDecl::None ||
384 Old->getStorageClass() == VarDecl::Extern)) {
385 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
386 Diag(Old->getLocation(), diag::err_previous_definition);
387 return New;
388 }
389 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
390 if (New->getStorageClass() != VarDecl::Static &&
391 Old->getStorageClass() == VarDecl::Static) {
392 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
393 Diag(Old->getLocation(), diag::err_previous_definition);
394 return New;
395 }
396 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000397 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000398 // Handle C "tentative" external object definitions (C99 6.9.2).
399 bool OldIsTentative = false;
400 bool NewIsTentative = false;
401
Steve Naroff248a7532008-04-15 22:42:06 +0000402 if (!Old->getInit() &&
403 (Old->getStorageClass() == VarDecl::None ||
404 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000405 OldIsTentative = true;
406
407 // FIXME: this check doesn't work (since the initializer hasn't been
408 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
409 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
410 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000411 if (!New->getInit() &&
412 (New->getStorageClass() == VarDecl::None ||
413 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000414 ; // change to NewIsTentative = true; once the code is moved.
415
416 if (NewIsTentative || OldIsTentative)
417 return New;
418 }
419 if (Old->getStorageClass() != VarDecl::Extern &&
420 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 Diag(New->getLocation(), diag::err_redefinition, New->getName());
422 Diag(Old->getLocation(), diag::err_previous_definition);
423 }
424 return New;
425}
426
Chris Lattner04421082008-04-08 04:40:51 +0000427/// CheckParmsForFunctionDef - Check that the parameters of the given
428/// function are appropriate for the definition of a function. This
429/// takes care of any checks that cannot be performed on the
430/// declaration itself, e.g., that the types of each of the function
431/// parameters are complete.
432bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
433 bool HasInvalidParm = false;
434 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
435 ParmVarDecl *Param = FD->getParamDecl(p);
436
437 // C99 6.7.5.3p4: the parameters in a parameter type list in a
438 // function declarator that is part of a function definition of
439 // that function shall not have incomplete type.
440 if (Param->getType()->isIncompleteType() &&
441 !Param->isInvalidDecl()) {
442 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
443 Param->getType().getAsString());
444 Param->setInvalidDecl();
445 HasInvalidParm = true;
446 }
447 }
448
449 return HasInvalidParm;
450}
451
452/// CreateImplicitParameter - Creates an implicit function parameter
453/// in the scope S and with the given type. This routine is used, for
454/// example, to create the implicit "self" parameter in an Objective-C
455/// method.
456ParmVarDecl *
457Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
458 SourceLocation IdLoc, QualType Type) {
459 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
460 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000461 if (Id)
462 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000463
464 return New;
465}
466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
468/// no declarator (e.g. "struct foo;") is parsed.
469Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
470 // TODO: emit error on 'int;' or 'const enum foo;'.
471 // TODO: emit error on 'typedef int;'
472 // if (!DS.isMissingDeclaratorOk()) Diag(...);
473
Steve Naroff92199282007-11-17 21:37:36 +0000474 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000475}
476
Steve Naroffd0091aa2008-01-10 22:15:12 +0000477bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000478 // Get the type before calling CheckSingleAssignmentConstraints(), since
479 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000480 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000481
Chris Lattner5cf216b2008-01-04 18:04:52 +0000482 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
483 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
484 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000485}
486
Steve Naroff9e8925e2007-09-04 14:36:54 +0000487bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000488 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000489 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000490 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000491 return true; // types weren't compatible.
492
Steve Naroff9e8925e2007-09-04 14:36:54 +0000493 if (savExpr != expr) // The type was promoted, update initializer list.
494 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000495 return false;
496}
497
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000498bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000499 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000500 // C99 6.7.8p14. We have an array of character type with unknown size
501 // being initialized to a string literal.
502 llvm::APSInt ConstVal(32);
503 ConstVal = strLiteral->getByteLength() + 1;
504 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000505 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000506 ArrayType::Normal, 0);
507 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
508 // C99 6.7.8p14. We have an array of character type with known size.
509 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
510 Diag(strLiteral->getSourceRange().getBegin(),
511 diag::warn_initializer_string_for_char_array_too_long,
512 strLiteral->getSourceRange());
513 } else {
514 assert(0 && "HandleStringLiteralInit(): Invalid array type");
515 }
516 // Set type from "char *" to "constant array of char".
517 strLiteral->setType(DeclT);
518 // For now, we always return false (meaning success).
519 return false;
520}
521
522StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000523 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000524 if (AT && AT->getElementType()->isCharType()) {
525 return dyn_cast<StringLiteral>(Init);
526 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000527 return 0;
528}
529
Steve Naroffa9960332008-01-25 00:51:06 +0000530// CheckInitializerListTypes - Checks the types of elements of an initializer
531// list. This function is recursive: it calls itself to initialize subelements
532// of aggregate types. Note that the topLevel parameter essentially refers to
533// whether this expression "owns" the initializer list passed in, or if this
534// initialization is taking elements out of a parent initializer. Each
535// call to this function adds zero or more to startIndex, reports any errors,
536// and returns true if it found any inconsistent types.
537bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
538 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000539 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000540
541 if (DeclType->isScalarType()) {
542 // The simplest case: initializing a single scalar
543 if (topLevel) {
544 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
545 IList->getSourceRange());
546 }
547 if (startIndex < IList->getNumInits()) {
548 Expr* expr = IList->getInit(startIndex);
549 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
550 // FIXME: Should an error be reported here instead?
551 unsigned newIndex = 0;
552 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
553 } else {
554 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
555 }
556 ++startIndex;
557 }
558 // FIXME: Should an error be reported for empty initializer list + scalar?
559 } else if (DeclType->isVectorType()) {
560 if (startIndex < IList->getNumInits()) {
561 const VectorType *VT = DeclType->getAsVectorType();
562 int maxElements = VT->getNumElements();
563 QualType elementType = VT->getElementType();
564
565 for (int i = 0; i < maxElements; ++i) {
566 // Don't attempt to go past the end of the init list
567 if (startIndex >= IList->getNumInits())
568 break;
569 Expr* expr = IList->getInit(startIndex);
570 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
571 unsigned newIndex = 0;
572 hadError |= CheckInitializerListTypes(SubInitList, elementType,
573 true, newIndex);
574 ++startIndex;
575 } else {
576 hadError |= CheckInitializerListTypes(IList, elementType,
577 false, startIndex);
578 }
579 }
580 }
581 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
582 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000583 if (startIndex < IList->getNumInits() && !topLevel &&
584 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
585 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000586 // We found a compatible struct; per the standard, this initializes the
587 // struct. (The C standard technically says that this only applies for
588 // initializers for declarations with automatic scope; however, this
589 // construct is unambiguous anyway because a struct cannot contain
590 // a type compatible with itself. We'll output an error when we check
591 // if the initializer is constant.)
592 // FIXME: Is a call to CheckSingleInitializer required here?
593 ++startIndex;
594 } else {
595 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000596
Steve Naroff406db932008-02-11 21:52:37 +0000597 // If the record is invalid, some of it's members are invalid. To avoid
598 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000599 if (structDecl->isInvalidDecl())
600 return true;
601
Steve Naroffa9960332008-01-25 00:51:06 +0000602 // If structDecl is a forward declaration, this loop won't do anything;
603 // That's okay, because an error should get printed out elsewhere. It
604 // might be worthwhile to skip over the rest of the initializer, though.
605 int numMembers = structDecl->getNumMembers() -
606 structDecl->hasFlexibleArrayMember();
607 for (int i = 0; i < numMembers; i++) {
608 // Don't attempt to go past the end of the init list
609 if (startIndex >= IList->getNumInits())
610 break;
611 FieldDecl * curField = structDecl->getMember(i);
612 if (!curField->getIdentifier()) {
613 // Don't initialize unnamed fields, e.g. "int : 20;"
614 continue;
615 }
616 QualType fieldType = curField->getType();
617 Expr* expr = IList->getInit(startIndex);
618 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
619 unsigned newStart = 0;
620 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
621 true, newStart);
622 ++startIndex;
623 } else {
624 hadError |= CheckInitializerListTypes(IList, fieldType,
625 false, startIndex);
626 }
627 if (DeclType->isUnionType())
628 break;
629 }
630 // FIXME: Implement flexible array initialization GCC extension (it's a
631 // really messy extension to implement, unfortunately...the necessary
632 // information isn't actually even here!)
633 }
634 } else if (DeclType->isArrayType()) {
635 // Check for the special-case of initializing an array with a string.
636 if (startIndex < IList->getNumInits()) {
637 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
638 DeclType)) {
639 CheckStringLiteralInit(lit, DeclType);
640 ++startIndex;
641 if (topLevel && startIndex < IList->getNumInits()) {
642 // We have leftover initializers; warn
643 Diag(IList->getInit(startIndex)->getLocStart(),
644 diag::err_excess_initializers_in_char_array_initializer,
645 IList->getInit(startIndex)->getSourceRange());
646 }
647 return false;
648 }
649 }
650 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000651 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000652 // FIXME: use a proper constant
653 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000654 } else if (const VariableArrayType *VAT =
655 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000656 // Check for VLAs; in standard C it would be possible to check this
657 // earlier, but I don't know where clang accepts VLAs (gcc accepts
658 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000659 Diag(VAT->getSizeExpr()->getLocStart(),
660 diag::err_variable_object_no_init,
661 VAT->getSizeExpr()->getSourceRange());
662 hadError = true;
663 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000664 } else {
665 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
666 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
667 }
668 QualType elementType = DeclType->getAsArrayType()->getElementType();
669 int numElements = 0;
670 for (int i = 0; i < maxElements; ++i, ++numElements) {
671 // Don't attempt to go past the end of the init list
672 if (startIndex >= IList->getNumInits())
673 break;
674 Expr* expr = IList->getInit(startIndex);
675 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
676 unsigned newIndex = 0;
677 hadError |= CheckInitializerListTypes(SubInitList, elementType,
678 true, newIndex);
679 ++startIndex;
680 } else {
681 hadError |= CheckInitializerListTypes(IList, elementType,
682 false, startIndex);
683 }
684 }
Eli Friedman9db13972008-02-15 12:53:51 +0000685 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000686 // If this is an incomplete array type, the actual type needs to
687 // be calculated here
688 if (numElements == 0) {
689 // Sizing an array implicitly to zero is not allowed
690 // (It could in theory be allowed, but it doesn't really matter.)
691 Diag(IList->getLocStart(),
692 diag::err_at_least_one_initializer_needed_to_size_array);
693 hadError = true;
694 } else {
695 llvm::APSInt ConstVal(32);
696 ConstVal = numElements;
697 DeclType = Context.getConstantArrayType(elementType, ConstVal,
698 ArrayType::Normal, 0);
699 }
700 }
701 } else {
702 assert(0 && "Aggregate that isn't a function or array?!");
703 }
704 } else {
705 // In C, all types are either scalars or aggregates, but
706 // additional handling is needed here for C++ (and possibly others?).
707 assert(0 && "Unsupported initializer type");
708 }
709
710 // If this init list is a base list, we set the type; an initializer doesn't
711 // fundamentally have a type, but this makes the ASTs a bit easier to read
712 if (topLevel)
713 IList->setType(DeclType);
714
715 if (topLevel && startIndex < IList->getNumInits()) {
716 // We have leftover initializers; warn
717 Diag(IList->getInit(startIndex)->getLocStart(),
718 diag::warn_excess_initializers,
719 IList->getInit(startIndex)->getSourceRange());
720 }
721 return hadError;
722}
723
724bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000725 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
726 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000727 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000728 return Diag(VAT->getSizeExpr()->getLocStart(),
729 diag::err_variable_object_no_init,
730 VAT->getSizeExpr()->getSourceRange());
731
Steve Naroff2fdc3742007-12-10 22:44:33 +0000732 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
733 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000734 // FIXME: Handle wide strings
735 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
736 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000737
738 if (DeclType->isArrayType())
739 return Diag(Init->getLocStart(),
740 diag::err_array_init_list_required,
741 Init->getSourceRange());
742
Steve Naroffd0091aa2008-01-10 22:15:12 +0000743 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000744 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000745#if 1
Steve Naroffa9960332008-01-25 00:51:06 +0000746 unsigned newIndex = 0;
747 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000748#else
749 InitListChecker CheckInitList(this, InitList, DeclType);
750 return CheckInitList.HadError();
751#endif
Steve Narofff0090632007-09-02 02:04:30 +0000752}
753
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000754Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000755Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000756 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000757 IdentifierInfo *II = D.getIdentifier();
758
Chris Lattnere80a59c2007-07-25 00:24:17 +0000759 // All of these full declarators require an identifier. If it doesn't have
760 // one, the ParsedFreeStandingDeclSpec action should be used.
761 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000762 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000763 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000764 D.getDeclSpec().getSourceRange(), D.getSourceRange());
765 return 0;
766 }
767
Chris Lattner31e05722007-08-26 06:24:45 +0000768 // The scope passed in may not be a decl scope. Zip up the scope tree until
769 // we find one that is.
770 while ((S->getFlags() & Scope::DeclScope) == 0)
771 S = S->getParent();
772
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000774 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000775 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000776 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000777
778 // In C++, the previous declaration we find might be a tag type
779 // (class or enum). In this case, the new declaration will hide the
780 // tag type.
781 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
782 PrevDecl = 0;
783
Chris Lattner41af0932007-11-14 06:34:38 +0000784 QualType R = GetTypeForDeclarator(D, S);
785 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000788 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 if (!NewTD) return 0;
790
791 // Handle attributes prior to checking for duplicates in MergeVarDecl
792 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
793 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000794 // Merge the decl with the existing one if appropriate. If the decl is
795 // in an outer scope, it isn't the same thing.
796 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
798 if (NewTD == 0) return 0;
799 }
800 New = NewTD;
801 if (S->getParent() == 0) {
802 // C99 6.7.7p2: If a typedef name specifies a variably modified type
803 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000804 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
805 // FIXME: Diagnostic needs to be fixed.
806 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000807 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 }
809 }
Chris Lattner41af0932007-11-14 06:34:38 +0000810 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000811 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 switch (D.getDeclSpec().getStorageClassSpec()) {
813 default: assert(0 && "Unknown storage class!");
814 case DeclSpec::SCS_auto:
815 case DeclSpec::SCS_register:
816 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
817 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000818 InvalidDecl = true;
819 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000820 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
821 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
822 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000823 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 }
825
Chris Lattnera98e58d2008-03-15 21:24:04 +0000826 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000827 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
828 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000829 II, R, SC, isInline,
830 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000831 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000832 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
833 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000834
835 // Copy the parameter declarations from the declarator D to
836 // the function declaration NewFD, if they are available.
837 if (D.getNumTypeObjects() > 0 &&
838 D.getTypeObject(0).Fun.hasPrototype) {
839 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
840
841 // Create Decl objects for each parameter, adding them to the
842 // FunctionDecl.
843 llvm::SmallVector<ParmVarDecl*, 16> Params;
844
845 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
846 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000847 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000848 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
849 FTI.ArgInfo[0].Param &&
850 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
851 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
852 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000853 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
854
Chris Lattnerdef026a2008-04-10 02:26:16 +0000855 // In C++, the empty parameter-type-list must be spelled "void"; a
856 // typedef of void is not permitted.
857 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000858 Param->getType() != Context.VoidTy) {
859 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
860 }
861
Chris Lattner04421082008-04-08 04:40:51 +0000862 } else {
863 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
864 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
865 }
866
867 NewFD->setParams(&Params[0], Params.size());
868 }
869
Steve Naroffffce4d52008-01-09 23:34:55 +0000870 // Merge the decl with the existing one if appropriate. Since C functions
871 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 if (PrevDecl) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000873 bool Redeclaration = false;
874 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000876 if (Redeclaration) {
877 // Note that the new declaration is a redeclaration of the
878 // older declaration. Then return the older declaration: the
879 // new one is only kept within the set of previous
880 // declarations for this function.
881 FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
882 OldFD->AddRedeclaration(NewFD);
883 return OldFD;
884 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 }
886 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000887
888 // In C++, check default arguments now that we have merged decls.
889 if (getLangOptions().CPlusPlus)
890 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000893 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
894 D.getIdentifier()->getName());
895 InvalidDecl = true;
896 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000897
898 VarDecl *NewVD;
899 VarDecl::StorageClass SC;
900 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000901 default: assert(0 && "Unknown storage class!");
902 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
903 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
904 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
905 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
906 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
907 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000908 }
909 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 // C99 6.9p2: The storage-class specifiers auto and register shall not
911 // appear in the declaration specifiers in an external declaration.
912 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
913 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
914 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000915 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000916 }
Steve Naroff248a7532008-04-15 22:42:06 +0000917 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
918 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000919 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000920 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
921 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000922 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 // Handle attributes prior to checking for duplicates in MergeVarDecl
924 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
925 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000926
927 // Emit an error if an address space was applied to decl with local storage.
928 // This includes arrays of objects with address space qualifiers, but not
929 // automatic variables that point to other address spaces.
930 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000931 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
932 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
933 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000934 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000935 // Merge the decl with the existing one if appropriate. If the decl is
936 // in an outer scope, it isn't the same thing.
937 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 NewVD = MergeVarDecl(NewVD, PrevDecl);
939 if (NewVD == 0) return 0;
940 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000941 New = NewVD;
942 }
943
944 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000945 if (II)
946 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000947 // If any semantic error occurred, mark the decl as invalid.
948 if (D.getInvalidType() || InvalidDecl)
949 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000950
951 return New;
952}
953
Steve Naroffd0091aa2008-01-10 22:15:12 +0000954bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
955 SourceLocation loc;
956 // FIXME: Remove the isReference check and handle assignment to a reference.
957 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
958 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
959 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
960 return true;
961 }
962 return false;
963}
964
Steve Naroffbb204692007-09-12 14:07:44 +0000965void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000966 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000967 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000968 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000969
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000970 // If there is no declaration, there was an error parsing it. Just ignore
971 // the initializer.
972 if (RealDecl == 0) {
973 delete Init;
974 return;
975 }
Steve Naroffbb204692007-09-12 14:07:44 +0000976
Steve Naroff410e3e22007-09-12 20:13:48 +0000977 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
978 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000979 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
980 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000981 RealDecl->setInvalidDecl();
982 return;
983 }
Steve Naroffbb204692007-09-12 14:07:44 +0000984 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000985 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000986 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +0000987 if (VDecl->isBlockVarDecl()) {
988 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +0000989 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000990 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +0000991 VDecl->setInvalidDecl();
992 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000993 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +0000994 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000995 if (SC == VarDecl::Static) // C99 6.7.8p4.
996 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000997 }
Steve Naroff248a7532008-04-15 22:42:06 +0000998 } else if (VDecl->isFileVarDecl()) {
999 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001000 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001001 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001002 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001003 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001004
1005 // C99 6.7.8p4. All file scoped initializers need to be constant.
1006 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +00001007 }
1008 // If the type changed, it means we had an incomplete type that was
1009 // completed by the initializer. For example:
1010 // int ary[] = { 1, 3, 5 };
1011 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001012 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001013 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001014 Init->setType(DclT);
1015 }
Steve Naroffbb204692007-09-12 14:07:44 +00001016
1017 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001018 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001019 return;
1020}
1021
Reid Spencer5f016e22007-07-11 17:01:13 +00001022/// The declarators are chained together backwards, reverse the list.
1023Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1024 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001025 Decl *GroupDecl = static_cast<Decl*>(group);
1026 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001027 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001028
1029 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1030 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001031 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001032 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001033 else { // reverse the list.
1034 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001035 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001036 Group->setNextDeclarator(NewGroup);
1037 NewGroup = Group;
1038 Group = Next;
1039 }
1040 }
1041 // Perform semantic analysis that depends on having fully processed both
1042 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001043 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001044 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1045 if (!IDecl)
1046 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001047 QualType T = IDecl->getType();
1048
1049 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1050 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001051 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1052 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001053 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001054 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1055 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001056 }
1057 }
1058 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1059 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001060 if (IDecl->isBlockVarDecl() &&
1061 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001062 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001063 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1064 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001065 IDecl->setInvalidDecl();
1066 }
1067 }
1068 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1069 // object that has file scope without an initializer, and without a
1070 // storage-class specifier or with the storage-class specifier "static",
1071 // constitutes a tentative definition. Note: A tentative definition with
1072 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001073 if (IDecl && !IDecl->getInit() &&
1074 (IDecl->getStorageClass() == VarDecl::Static ||
1075 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001076 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001077 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1078 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001079 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001080 // C99 6.9.2p3: If the declaration of an identifier for an object is
1081 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1082 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001083 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1084 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001085 IDecl->setInvalidDecl();
1086 }
1087 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 }
1089 return NewGroup;
1090}
Steve Naroffe1223f72007-08-28 03:03:08 +00001091
Chris Lattner04421082008-04-08 04:40:51 +00001092/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1093/// to introduce parameters into function prototype scope.
1094Sema::DeclTy *
1095Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1096 DeclSpec &DS = D.getDeclSpec();
1097
1098 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1099 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1100 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1101 Diag(DS.getStorageClassSpecLoc(),
1102 diag::err_invalid_storage_class_in_func_decl);
1103 DS.ClearStorageClassSpecs();
1104 }
1105 if (DS.isThreadSpecified()) {
1106 Diag(DS.getThreadSpecLoc(),
1107 diag::err_invalid_storage_class_in_func_decl);
1108 DS.ClearStorageClassSpecs();
1109 }
1110
1111
1112 // In this context, we *do not* check D.getInvalidType(). If the declarator
1113 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1114 // though it will not reflect the user specified type.
1115 QualType parmDeclType = GetTypeForDeclarator(D, S);
1116
1117 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1118
Reid Spencer5f016e22007-07-11 17:01:13 +00001119 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1120 // Can this happen for params? We already checked that they don't conflict
1121 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001122 IdentifierInfo *II = D.getIdentifier();
1123 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1124 if (S->isDeclScope(PrevDecl)) {
1125 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1126 dyn_cast<NamedDecl>(PrevDecl)->getName());
1127
1128 // Recover by removing the name
1129 II = 0;
1130 D.SetIdentifier(0, D.getIdentifierLoc());
1131 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001132 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001133
1134 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1135 // Doing the promotion here has a win and a loss. The win is the type for
1136 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1137 // code generator). The loss is the orginal type isn't preserved. For example:
1138 //
1139 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1140 // int blockvardecl[5];
1141 // sizeof(parmvardecl); // size == 4
1142 // sizeof(blockvardecl); // size == 20
1143 // }
1144 //
1145 // For expressions, all implicit conversions are captured using the
1146 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1147 //
1148 // FIXME: If a source translation tool needs to see the original type, then
1149 // we need to consider storing both types (in ParmVarDecl)...
1150 //
Chris Lattnere6327742008-04-02 05:18:44 +00001151 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001152 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001153 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001154 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001155 parmDeclType = Context.getPointerType(parmDeclType);
1156
Chris Lattner04421082008-04-08 04:40:51 +00001157 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1158 D.getIdentifierLoc(), II,
1159 parmDeclType, VarDecl::None,
1160 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001161
Chris Lattner04421082008-04-08 04:40:51 +00001162 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001163 New->setInvalidDecl();
1164
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001165 if (II)
1166 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001167
Chris Lattner04421082008-04-08 04:40:51 +00001168 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001170
Reid Spencer5f016e22007-07-11 17:01:13 +00001171}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001172
Chris Lattnerb652cea2007-10-09 17:14:05 +00001173Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 assert(CurFunctionDecl == 0 && "Function parsing confused");
1175 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1176 "Not a function declarator!");
1177 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001178
Reid Spencer5f016e22007-07-11 17:01:13 +00001179 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1180 // for a K&R function.
1181 if (!FTI.hasPrototype) {
1182 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001183 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001184 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1185 FTI.ArgInfo[i].Ident->getName());
1186 // Implicitly declare the argument as type 'int' for lack of a better
1187 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001188 DeclSpec DS;
1189 const char* PrevSpec; // unused
1190 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1191 PrevSpec);
1192 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1193 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1194 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 }
1196 }
Chris Lattner52804082008-02-17 19:31:09 +00001197
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 // Since this is a function definition, act as though we have information
1199 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001200 if (FTI.NumArgs)
1201 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001203 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
1205
1206 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001207
1208 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001209 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001210 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001211 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001212 const FunctionDecl *Definition;
1213 if (FD->getBody(Definition)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001214 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1215 D.getIdentifier()->getName());
Douglas Gregorf0097952008-04-21 02:02:58 +00001216 Diag(Definition->getLocation(), diag::err_previous_definition);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001217 }
1218 }
Steve Narofffabbc342008-02-12 01:09:36 +00001219 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001220 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001222 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001223
1224 // Check the validity of our function parameters
1225 CheckParmsForFunctionDef(FD);
1226
1227 // Introduce our parameters into the function scope
1228 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1229 ParmVarDecl *Param = FD->getParamDecl(p);
1230 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001231 if (Param->getIdentifier())
1232 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001233 }
Chris Lattner04421082008-04-08 04:40:51 +00001234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235 return FD;
1236}
1237
Steve Naroffd6d054d2007-11-11 23:20:51 +00001238Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1239 Decl *dcl = static_cast<Decl *>(D);
1240 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1241 FD->setBody((Stmt*)Body);
1242 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001243 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001244 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001245 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001246 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001247 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001248 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // Verify and clean out per-function state.
1250
1251 // Check goto/label use.
1252 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1253 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1254 // Verify that we have no forward references left. If so, there was a goto
1255 // or address of a label taken, but no definition of it. Label fwd
1256 // definitions are indicated with a null substmt.
1257 if (I->second->getSubStmt() == 0) {
1258 LabelStmt *L = I->second;
1259 // Emit error.
1260 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1261
1262 // At this point, we have gotos that use the bogus label. Stitch it into
1263 // the function body so that they aren't leaked and that the AST is well
1264 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001265 if (Body) {
1266 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1267 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1268 } else {
1269 // The whole function wasn't parsed correctly, just delete this.
1270 delete L;
1271 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 }
1273 }
1274 LabelMap.clear();
1275
Steve Naroffd6d054d2007-11-11 23:20:51 +00001276 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001277}
1278
Reid Spencer5f016e22007-07-11 17:01:13 +00001279/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1280/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001281ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1282 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001283 // Extension in C99. Legal in C90, but warn about it.
1284 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001286 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1288
1289 // FIXME: handle stuff like:
1290 // void foo() { extern float X(); }
1291 // void bar() { X(); } <-- implicit decl for X in another scope.
1292
1293 // Set a Declarator for the implicit definition: int foo();
1294 const char *Dummy;
1295 DeclSpec DS;
1296 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1297 Error = Error; // Silence warning.
1298 assert(!Error && "Error setting up implicit decl!");
1299 Declarator D(DS, Declarator::BlockContext);
1300 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1301 D.SetIdentifier(&II, Loc);
1302
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001303 // Insert this function into translation-unit scope.
1304
1305 DeclContext *PrevDC = CurContext;
1306 CurContext = Context.getTranslationUnitDecl();
1307
Steve Naroffe2ef8152008-04-04 14:32:09 +00001308 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001309 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001310 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001311
1312 CurContext = PrevDC;
1313
Steve Naroffe2ef8152008-04-04 14:32:09 +00001314 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001315}
1316
1317
Chris Lattner41af0932007-11-14 06:34:38 +00001318TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001319 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001320 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001321 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001322
1323 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001324 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1325 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001326 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001327 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001328 if (D.getInvalidType())
1329 NewTD->setInvalidDecl();
1330 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001331}
1332
Steve Naroff08d92e42007-09-15 18:49:24 +00001333/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001334/// former case, Name will be non-null. In the later case, Name will be null.
1335/// TagType indicates what kind of tag this is. TK indicates whether this is a
1336/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001337Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 SourceLocation KWLoc, IdentifierInfo *Name,
1339 SourceLocation NameLoc, AttributeList *Attr) {
1340 // If this is a use of an existing tag, it must have a name.
1341 assert((Name != 0 || TK == TK_Definition) &&
1342 "Nameless record must be a definition!");
1343
1344 Decl::Kind Kind;
1345 switch (TagType) {
1346 default: assert(0 && "Unknown tag type!");
1347 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1348 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001349 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1351 }
1352
1353 // If this is a named struct, check to see if there was a previous forward
1354 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001355 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1356 if (ScopedDecl *PrevDecl =
1357 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001358
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001359 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1360 "unexpected Decl type");
1361 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1362 // If this is a use of a previous tag, or if the tag is already declared in
1363 // the same scope (so that the definition/declaration completes or
1364 // rementions the tag), reuse the decl.
1365 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1366 // Make sure that this wasn't declared as an enum and now used as a struct
1367 // or something similar.
1368 if (PrevDecl->getKind() != Kind) {
1369 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1370 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1371 }
1372
1373 // If this is a use or a forward declaration, we're good.
1374 if (TK != TK_Definition)
1375 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001376
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001377 // Diagnose attempts to redefine a tag.
1378 if (PrevTagDecl->isDefinition()) {
1379 Diag(NameLoc, diag::err_redefinition, Name->getName());
1380 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1381 // If this is a redefinition, recover by making this struct be
1382 // anonymous, which will make any later references get the previous
1383 // definition.
1384 Name = 0;
1385 } else {
1386 // Okay, this is definition of a previously declared or referenced tag.
1387 // Move the location of the decl to be the definition site.
1388 PrevDecl->setLocation(NameLoc);
1389 return PrevDecl;
1390 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001392 // If we get here, this is a definition of a new struct type in a nested
1393 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1394 // type.
1395 } else {
1396 // The tag name clashes with a namespace name, issue an error and recover
1397 // by making this tag be anonymous.
1398 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1399 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1400 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 }
1403
1404 // If there is an identifier, use the location of the identifier as the
1405 // location of the decl, otherwise use the location of the struct/union
1406 // keyword.
1407 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1408
1409 // Otherwise, if this is the first time we've seen this tag, create the decl.
1410 TagDecl *New;
1411 switch (Kind) {
1412 default: assert(0 && "Unknown tag kind!");
1413 case Decl::Enum:
1414 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1415 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001416 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 // If this is an undefined enum, warn.
1418 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1419 break;
1420 case Decl::Union:
1421 case Decl::Struct:
1422 case Decl::Class:
1423 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1424 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001425 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 break;
1427 }
1428
1429 // If this has an identifier, add it to the scope stack.
1430 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001431 // The scope passed in may not be a decl scope. Zip up the scope tree until
1432 // we find one that is.
1433 while ((S->getFlags() & Scope::DeclScope) == 0)
1434 S = S->getParent();
1435
1436 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001437 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001439
Anders Carlssonad148062008-02-16 00:29:18 +00001440 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 return New;
1442}
1443
Steve Naroff08d92e42007-09-15 18:49:24 +00001444/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001445/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001446Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 SourceLocation DeclStart,
1448 Declarator &D, ExprTy *BitfieldWidth) {
1449 IdentifierInfo *II = D.getIdentifier();
1450 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 SourceLocation Loc = DeclStart;
1452 if (II) Loc = D.getIdentifierLoc();
1453
1454 // FIXME: Unnamed fields can be handled in various different ways, for
1455 // example, unnamed unions inject all members into the struct namespace!
1456
1457
1458 if (BitWidth) {
1459 // TODO: Validate.
1460 //printf("WARNING: BITFIELDS IGNORED!\n");
1461
1462 // 6.7.2.1p3
1463 // 6.7.2.1p4
1464
1465 } else {
1466 // Not a bitfield.
1467
1468 // validate II.
1469
1470 }
1471
1472 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001473 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1474 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001475
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1477 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001478 if (T->isVariablyModifiedType()) {
1479 // FIXME: This diagnostic needs work
1480 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001481 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001484 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001485
Anders Carlssonad148062008-02-16 00:29:18 +00001486 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1487 D.getAttributes());
1488
Steve Naroff5912a352007-08-28 20:14:24 +00001489 if (D.getInvalidType() || InvalidDecl)
1490 NewFD->setInvalidDecl();
1491 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001492}
1493
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001494/// TranslateIvarVisibility - Translate visibility from a token ID to an
1495/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001496static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001497TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001498 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001499 case tok::objc_private: return ObjCIvarDecl::Private;
1500 case tok::objc_public: return ObjCIvarDecl::Public;
1501 case tok::objc_protected: return ObjCIvarDecl::Protected;
1502 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001503 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001504 }
1505}
1506
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001507/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1508/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001509Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001510 SourceLocation DeclStart,
1511 Declarator &D, ExprTy *BitfieldWidth,
1512 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001513 IdentifierInfo *II = D.getIdentifier();
1514 Expr *BitWidth = (Expr*)BitfieldWidth;
1515 SourceLocation Loc = DeclStart;
1516 if (II) Loc = D.getIdentifierLoc();
1517
1518 // FIXME: Unnamed fields can be handled in various different ways, for
1519 // example, unnamed unions inject all members into the struct namespace!
1520
1521
1522 if (BitWidth) {
1523 // TODO: Validate.
1524 //printf("WARNING: BITFIELDS IGNORED!\n");
1525
1526 // 6.7.2.1p3
1527 // 6.7.2.1p4
1528
1529 } else {
1530 // Not a bitfield.
1531
1532 // validate II.
1533
1534 }
1535
1536 QualType T = GetTypeForDeclarator(D, S);
1537 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1538 bool InvalidDecl = false;
1539
1540 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1541 // than a variably modified type.
1542 if (T->isVariablyModifiedType()) {
1543 // FIXME: This diagnostic needs work
1544 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1545 InvalidDecl = true;
1546 }
1547
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001548 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001549
1550 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1551 D.getAttributes());
1552
1553 if (D.getInvalidType() || InvalidDecl)
1554 NewID->setInvalidDecl();
1555 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001556 if (Visibility != tok::objc_not_keyword)
1557 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001558 return NewID;
1559}
1560
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001561void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001562 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001563 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001564 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001565 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1566 assert(EnclosingDecl && "missing record or interface decl");
1567 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1568
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001569 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 // Diagnose code like:
1571 // struct S { struct S {} X; };
1572 // We discover this when we complete the outer S. Reject and ignore the
1573 // outer S.
1574 Diag(Record->getLocation(), diag::err_nested_redefinition,
1575 Record->getKindName());
1576 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001577 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 return;
1579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 // Verify that all the fields are okay.
1581 unsigned NumNamedMembers = 0;
1582 llvm::SmallVector<FieldDecl*, 32> RecFields;
1583 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001584
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001586
Steve Naroff74216642007-09-14 22:20:54 +00001587 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1588 assert(FD && "missing field decl");
1589
1590 // Remember all fields.
1591 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001592
1593 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001594 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001595
Reid Spencer5f016e22007-07-11 17:01:13 +00001596 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001597 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001598 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001600 FD->setInvalidDecl();
1601 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 continue;
1603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1605 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001606 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001607 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001608 FD->setInvalidDecl();
1609 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001610 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 if (i != NumFields-1 || // ... that the last member ...
1613 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001614 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001616 FD->setInvalidDecl();
1617 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 continue;
1619 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001620 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1622 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001623 FD->setInvalidDecl();
1624 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 continue;
1626 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001628 if (Record)
1629 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1632 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001633 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1635 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001636 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 Record->setHasFlexibleArrayMember(true);
1638 } else {
1639 // If this is a struct/class and this is not the last element, reject
1640 // it. Note that GCC supports variable sized arrays in the middle of
1641 // structures.
1642 if (i != NumFields-1) {
1643 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1644 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001645 FD->setInvalidDecl();
1646 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 continue;
1648 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 // We support flexible arrays at the end of structs in other structs
1650 // as an extension.
1651 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1652 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001653 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001654 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 }
1656 }
1657 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001658 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001659 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001660 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1661 FD->getName());
1662 FD->setInvalidDecl();
1663 EnclosingDecl->setInvalidDecl();
1664 continue;
1665 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // Keep track of the number of named members.
1667 if (IdentifierInfo *II = FD->getIdentifier()) {
1668 // Detect duplicate member names.
1669 if (!FieldIDs.insert(II)) {
1670 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1671 // Find the previous decl.
1672 SourceLocation PrevLoc;
1673 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1674 assert(i != e && "Didn't find previous def!");
1675 if (RecFields[i]->getIdentifier() == II) {
1676 PrevLoc = RecFields[i]->getLocation();
1677 break;
1678 }
1679 }
1680 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001681 FD->setInvalidDecl();
1682 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 continue;
1684 }
1685 ++NumNamedMembers;
1686 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 }
1688
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001690 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001691 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001692 Consumer.HandleTagDeclDefinition(Record);
1693 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001694 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1695 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1696 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1697 else if (ObjCImplementationDecl *IMPDecl =
1698 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001699 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1700 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001701 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001702 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001703 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001704}
1705
Steve Naroff08d92e42007-09-15 18:49:24 +00001706Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 DeclTy *lastEnumConst,
1708 SourceLocation IdLoc, IdentifierInfo *Id,
1709 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001710 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001711 EnumConstantDecl *LastEnumConst =
1712 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1713 Expr *Val = static_cast<Expr*>(val);
1714
Chris Lattner31e05722007-08-26 06:24:45 +00001715 // The scope passed in may not be a decl scope. Zip up the scope tree until
1716 // we find one that is.
1717 while ((S->getFlags() & Scope::DeclScope) == 0)
1718 S = S->getParent();
1719
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 // Verify that there isn't already something declared with this name in this
1721 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001722 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 if (S->isDeclScope(PrevDecl)) {
1724 if (isa<EnumConstantDecl>(PrevDecl))
1725 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1726 else
1727 Diag(IdLoc, diag::err_redefinition, Id->getName());
1728 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001729 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 return 0;
1731 }
1732 }
1733
1734 llvm::APSInt EnumVal(32);
1735 QualType EltTy;
1736 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001737 // Make sure to promote the operand type to int.
1738 UsualUnaryConversions(Val);
1739
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1741 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001742 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001743 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1744 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001745 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001746 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001747 } else {
1748 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001750 }
1751
1752 if (!Val) {
1753 if (LastEnumConst) {
1754 // Assign the last value + 1.
1755 EnumVal = LastEnumConst->getInitVal();
1756 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001757
1758 // Check for overflow on increment.
1759 if (EnumVal < LastEnumConst->getInitVal())
1760 Diag(IdLoc, diag::warn_enum_value_overflow);
1761
Chris Lattnerb7416f92007-08-27 17:37:24 +00001762 EltTy = LastEnumConst->getType();
1763 } else {
1764 // First value, set to zero.
1765 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001766 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001767 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 }
1769
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001770 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001771 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1772 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001773 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001774
1775 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001776 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 return New;
1778}
1779
Steve Naroff08d92e42007-09-15 18:49:24 +00001780void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 DeclTy **Elements, unsigned NumElements) {
1782 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1783 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1784
Chris Lattnere37f0be2007-08-28 05:10:31 +00001785 // TODO: If the result value doesn't fit in an int, it must be a long or long
1786 // long value. ISO C does not support this, but GCC does as an extension,
1787 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001788 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001789
Chris Lattnerac609682007-08-28 06:15:15 +00001790 // Verify that all the values are okay, compute the size of the values, and
1791 // reverse the list.
1792 unsigned NumNegativeBits = 0;
1793 unsigned NumPositiveBits = 0;
1794
1795 // Keep track of whether all elements have type int.
1796 bool AllElementsInt = true;
1797
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 EnumConstantDecl *EltList = 0;
1799 for (unsigned i = 0; i != NumElements; ++i) {
1800 EnumConstantDecl *ECD =
1801 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1802 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001803
1804 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001805 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001806 assert(InitVal.getBitWidth() >= IntWidth &&
1807 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001808 if (InitVal.getBitWidth() > IntWidth) {
1809 llvm::APSInt V(InitVal);
1810 V.trunc(IntWidth);
1811 V.extend(InitVal.getBitWidth());
1812 if (V != InitVal)
1813 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1814 InitVal.toString());
1815 }
Chris Lattnerac609682007-08-28 06:15:15 +00001816
1817 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001818 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001819 NumPositiveBits = std::max(NumPositiveBits,
1820 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001821 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001822 NumNegativeBits = std::max(NumNegativeBits,
1823 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001824
Chris Lattnerac609682007-08-28 06:15:15 +00001825 // Keep track of whether every enum element has type int (very commmon).
1826 if (AllElementsInt)
1827 AllElementsInt = ECD->getType() == Context.IntTy;
1828
Reid Spencer5f016e22007-07-11 17:01:13 +00001829 ECD->setNextDeclarator(EltList);
1830 EltList = ECD;
1831 }
1832
Chris Lattnerac609682007-08-28 06:15:15 +00001833 // Figure out the type that should be used for this enum.
1834 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1835 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001836 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001837
1838 if (NumNegativeBits) {
1839 // If there is a negative value, figure out the smallest integer type (of
1840 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001841 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001842 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001843 BestWidth = IntWidth;
1844 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001845 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001846
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001847 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001848 BestType = Context.LongTy;
1849 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001850 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001851
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001852 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001853 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1854 BestType = Context.LongLongTy;
1855 }
1856 }
1857 } else {
1858 // If there is no negative value, figure out which of uint, ulong, ulonglong
1859 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001860 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001861 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001862 BestWidth = IntWidth;
1863 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001864 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001865 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001866 } else {
1867 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001868 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001869 "How could an initializer get larger than ULL?");
1870 BestType = Context.UnsignedLongLongTy;
1871 }
1872 }
1873
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001874 // Loop over all of the enumerator constants, changing their types to match
1875 // the type of the enum if needed.
1876 for (unsigned i = 0; i != NumElements; ++i) {
1877 EnumConstantDecl *ECD =
1878 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1879 if (!ECD) continue; // Already issued a diagnostic.
1880
1881 // Standard C says the enumerators have int type, but we allow, as an
1882 // extension, the enumerators to be larger than int size. If each
1883 // enumerator value fits in an int, type it as an int, otherwise type it the
1884 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1885 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001886 if (ECD->getType() == Context.IntTy) {
1887 // Make sure the init value is signed.
1888 llvm::APSInt IV = ECD->getInitVal();
1889 IV.setIsSigned(true);
1890 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001891 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001892 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001893
1894 // Determine whether the value fits into an int.
1895 llvm::APSInt InitVal = ECD->getInitVal();
1896 bool FitsInInt;
1897 if (InitVal.isUnsigned() || !InitVal.isNegative())
1898 FitsInInt = InitVal.getActiveBits() < IntWidth;
1899 else
1900 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1901
1902 // If it fits into an integer type, force it. Otherwise force it to match
1903 // the enum decl type.
1904 QualType NewTy;
1905 unsigned NewWidth;
1906 bool NewSign;
1907 if (FitsInInt) {
1908 NewTy = Context.IntTy;
1909 NewWidth = IntWidth;
1910 NewSign = true;
1911 } else if (ECD->getType() == BestType) {
1912 // Already the right type!
1913 continue;
1914 } else {
1915 NewTy = BestType;
1916 NewWidth = BestWidth;
1917 NewSign = BestType->isSignedIntegerType();
1918 }
1919
1920 // Adjust the APSInt value.
1921 InitVal.extOrTrunc(NewWidth);
1922 InitVal.setIsSigned(NewSign);
1923 ECD->setInitVal(InitVal);
1924
1925 // Adjust the Expr initializer and type.
1926 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1927 ECD->setType(NewTy);
1928 }
Chris Lattnerac609682007-08-28 06:15:15 +00001929
Chris Lattnere00b18c2007-08-28 18:24:31 +00001930 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001931 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001932}
1933
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001934Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1935 ExprTy *expr) {
1936 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1937
Chris Lattner8e25d862008-03-16 00:16:02 +00001938 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001939}
1940
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001941Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001942 SourceLocation LBrace,
1943 SourceLocation RBrace,
1944 const char *Lang,
1945 unsigned StrSize,
1946 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001947 LinkageSpecDecl::LanguageIDs Language;
1948 Decl *dcl = static_cast<Decl *>(D);
1949 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1950 Language = LinkageSpecDecl::lang_c;
1951 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1952 Language = LinkageSpecDecl::lang_cxx;
1953 else {
1954 Diag(Loc, diag::err_bad_language);
1955 return 0;
1956 }
1957
1958 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001959 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001960}
1961
Chris Lattner74788ba2008-02-21 00:48:22 +00001962void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001963
Chris Lattner74788ba2008-02-21 00:48:22 +00001964 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001965 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001967 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 if (!newType.isNull()) // install the new vector type into the decl
1969 vDecl->setType(newType);
1970 }
1971 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1972 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001973 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 if (!newType.isNull()) // install the new vector type into the decl
1975 tDecl->setUnderlyingType(newType);
1976 }
Chris Lattner212839c2008-02-20 23:17:35 +00001977 break;
Nate Begeman213541a2008-04-18 23:10:10 +00001978 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001979 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00001980 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001981 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001982 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00001983 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001984 break;
1985 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001986 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1987 QualType newType = HandleAddressSpaceTypeAttribute(
1988 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001989 Attr);
1990 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001991 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1992 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001993 Attr);
1994 // install the new addr spaced type into the decl
1995 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001996 }
Chris Lattner212839c2008-02-20 23:17:35 +00001997 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001998 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001999 HandleDeprecatedAttribute(New, Attr);
2000 break;
2001 case AttributeList::AT_visibility:
2002 HandleVisibilityAttribute(New, Attr);
2003 break;
2004 case AttributeList::AT_weak:
2005 HandleWeakAttribute(New, Attr);
2006 break;
2007 case AttributeList::AT_dllimport:
2008 HandleDLLImportAttribute(New, Attr);
2009 break;
2010 case AttributeList::AT_dllexport:
2011 HandleDLLExportAttribute(New, Attr);
2012 break;
2013 case AttributeList::AT_nothrow:
2014 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002015 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002016 case AttributeList::AT_stdcall:
2017 HandleStdCallAttribute(New, Attr);
2018 break;
2019 case AttributeList::AT_fastcall:
2020 HandleFastCallAttribute(New, Attr);
2021 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002022 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002023 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002024 break;
2025 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002026 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002027 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002028 case AttributeList::AT_annotate:
2029 HandleAnnotateAttribute(New, Attr);
2030 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002031 case AttributeList::AT_noreturn:
2032 HandleNoReturnAttribute(New, Attr);
2033 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002034 case AttributeList::AT_format:
2035 HandleFormatAttribute(New, Attr);
2036 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002037 case AttributeList::AT_transparent_union:
2038 HandleTransparentUnionAttribute(New, Attr);
2039 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002040 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002041#if 0
2042 // TODO: when we have the full set of attributes, warn about unknown ones.
2043 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2044 Attr->getName()->getName());
2045#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002046 break;
2047 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002048}
2049
2050void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2051 AttributeList *declarator_postfix) {
2052 while (declspec_prefix) {
2053 HandleDeclAttribute(New, declspec_prefix);
2054 declspec_prefix = declspec_prefix->getNext();
2055 }
2056 while (declarator_postfix) {
2057 HandleDeclAttribute(New, declarator_postfix);
2058 declarator_postfix = declarator_postfix->getNext();
2059 }
2060}
2061
Nate Begeman213541a2008-04-18 23:10:10 +00002062void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002063 AttributeList *rawAttr) {
2064 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002065 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002066 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002067 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002068 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002069 return;
Steve Naroff73322922007-07-18 18:00:27 +00002070 }
2071 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2072 llvm::APSInt vecSize(32);
2073 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002074 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002075 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002076 return;
Steve Naroff73322922007-07-18 18:00:27 +00002077 }
2078 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2079 // in conjunction with complex types (pointers, arrays, functions, etc.).
2080 Type *canonType = curType.getCanonicalType().getTypePtr();
2081 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002082 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002083 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002084 return;
Steve Naroff73322922007-07-18 18:00:27 +00002085 }
2086 // unlike gcc's vector_size attribute, the size is specified as the
2087 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002088 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002089
2090 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002091 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002092 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002093 return;
Steve Naroff73322922007-07-18 18:00:27 +00002094 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002095 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002096 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002097 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002098 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002099}
2100
Reid Spencer5f016e22007-07-11 17:01:13 +00002101QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002102 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002103 // check the attribute arugments.
2104 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002105 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002106 std::string("1"));
2107 return QualType();
2108 }
2109 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2110 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002111 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002112 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002113 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 return QualType();
2115 }
2116 // navigate to the base type - we need to provide for vector pointers,
2117 // vector arrays, and functions returning vectors.
2118 Type *canonType = curType.getCanonicalType().getTypePtr();
2119
Steve Naroff73322922007-07-18 18:00:27 +00002120 if (canonType->isPointerType() || canonType->isArrayType() ||
2121 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002122 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002123 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2124 do {
2125 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2126 canonType = PT->getPointeeType().getTypePtr();
2127 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2128 canonType = AT->getElementType().getTypePtr();
2129 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2130 canonType = FT->getResultType().getTypePtr();
2131 } while (canonType->isPointerType() || canonType->isArrayType() ||
2132 canonType->isFunctionType());
2133 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 }
2135 // the base type must be integer or float.
2136 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002137 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002138 curType.getCanonicalType().getAsString());
2139 return QualType();
2140 }
Chris Lattner98be4942008-03-05 18:54:05 +00002141 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002142 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002143 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002144
2145 // the vector size needs to be an integral multiple of the type size.
2146 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002147 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 sizeExpr->getSourceRange());
2149 return QualType();
2150 }
2151 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002152 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 sizeExpr->getSourceRange());
2154 return QualType();
2155 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002156 // Instantiate the vector type, the number of elements is > 0, and not
2157 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002158 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002159}
2160
Chris Lattner2070d802008-02-20 23:25:22 +00002161void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002162 // check the attribute arguments.
2163 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002164 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002165 std::string("0"));
2166 return;
2167 }
2168
2169 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2170 TD->addAttr(new PackedAttr);
2171 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2172 // If the alignment is less than or equal to 8 bits, the packed attribute
2173 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002174 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002175 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002176 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002177 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002178 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002179 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002180 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002181 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2182 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002183}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002184
Ted Kremenekaecb3832008-02-27 20:43:06 +00002185void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2186 // check the attribute arguments.
2187 if (rawAttr->getNumArgs() != 0) {
2188 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2189 std::string("0"));
2190 return;
2191 }
2192
Ted Kremenek3465fb32008-03-03 16:52:27 +00002193 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2194
2195 if (!Fn) {
2196 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2197 "noreturn", "function");
2198 return;
2199 }
2200
Ted Kremenekaecb3832008-02-27 20:43:06 +00002201 d->addAttr(new NoReturnAttr());
2202}
2203
Chris Lattnerddee4232008-03-03 03:28:21 +00002204void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2205 // check the attribute arguments.
2206 if (rawAttr->getNumArgs() != 0) {
2207 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2208 std::string("0"));
2209 return;
2210 }
2211
2212 d->addAttr(new DeprecatedAttr());
2213}
2214
2215void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2216 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002217 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002218 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2219 std::string("1"));
2220 return;
2221 }
2222
Chris Lattner7b937ae2008-03-04 18:08:48 +00002223 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2224 Arg = Arg->IgnoreParenCasts();
2225 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2226
2227 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002228 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002229 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002230 return;
2231 }
2232
Chris Lattner7b937ae2008-03-04 18:08:48 +00002233 const char *TypeStr = Str->getStrData();
2234 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002235 llvm::GlobalValue::VisibilityTypes type;
2236
Chris Lattner7b937ae2008-03-04 18:08:48 +00002237 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002238 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002239 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002240 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002241 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002242 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002243 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002244 type = llvm::GlobalValue::ProtectedVisibility;
2245 else {
2246 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002247 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002248 return;
2249 }
2250
2251 d->addAttr(new VisibilityAttr(type));
2252}
2253
2254void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2255 // check the attribute arguments.
2256 if (rawAttr->getNumArgs() != 0) {
2257 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2258 std::string("0"));
2259 return;
2260 }
2261
2262 d->addAttr(new WeakAttr());
2263}
2264
2265void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2266 // check the attribute arguments.
2267 if (rawAttr->getNumArgs() != 0) {
2268 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2269 std::string("0"));
2270 return;
2271 }
2272
2273 d->addAttr(new DLLImportAttr());
2274}
2275
2276void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2277 // check the attribute arguments.
2278 if (rawAttr->getNumArgs() != 0) {
2279 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2280 std::string("0"));
2281 return;
2282 }
2283
2284 d->addAttr(new DLLExportAttr());
2285}
2286
Nate Begeman440b4562008-03-07 20:04:22 +00002287void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2288 // check the attribute arguments.
2289 if (rawAttr->getNumArgs() != 0) {
2290 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2291 std::string("0"));
2292 return;
2293 }
2294
2295 d->addAttr(new StdCallAttr());
2296}
2297
2298void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2299 // check the attribute arguments.
2300 if (rawAttr->getNumArgs() != 0) {
2301 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2302 std::string("0"));
2303 return;
2304 }
2305
2306 d->addAttr(new FastCallAttr());
2307}
2308
Chris Lattnerddee4232008-03-03 03:28:21 +00002309void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2310 // check the attribute arguments.
2311 if (rawAttr->getNumArgs() != 0) {
2312 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2313 std::string("0"));
2314 return;
2315 }
2316
2317 d->addAttr(new NoThrowAttr());
2318}
2319
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002320static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002321 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002322
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002323 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2324 Ty = decl->getType();
2325 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2326 Ty = decl->getType();
2327 else
2328 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002329
2330 if (Ty->isFunctionPointerType()) {
2331 const PointerType *PtrTy = Ty->getAsPointerType();
2332 Ty = PtrTy->getPointeeType();
2333 }
2334
2335 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2336 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2337
2338 return 0;
2339}
2340
2341
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002342/// Handle __attribute__((format(type,idx,firstarg))) attributes
2343/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002344void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2345
2346 if (!rawAttr->getParameterName()) {
2347 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2348 "format", std::string("1"));
2349 return;
2350 }
2351
2352 if (rawAttr->getNumArgs() != 2) {
2353 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2354 std::string("3"));
2355 return;
2356 }
2357
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002358 // GCC ignores the format attribute on K&R style function
2359 // prototypes, so we ignore it as well
2360 const FunctionTypeProto *proto = getFunctionProto(d);
2361
2362 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002363 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2364 "format", "function");
2365 return;
2366 }
2367
2368 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002369 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002370 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002371 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002372 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002373
2374 const char *Format = rawAttr->getParameterName()->getName();
2375 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2376
2377 // Normalize the argument, __foo__ becomes foo.
2378 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2379 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2380 Format += 2;
2381 FormatLen -= 4;
2382 }
2383
2384 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2385 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2386 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2387 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2388 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2389 "format", rawAttr->getParameterName()->getName());
2390 return;
2391 }
2392
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002393 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002394 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002395 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002396 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2397 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2398 "format", std::string("2"), IdxExpr->getSourceRange());
2399 return;
2400 }
2401
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002402 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002403 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2404 "format", std::string("2"), IdxExpr->getSourceRange());
2405 return;
2406 }
2407
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002408 // make sure the format string is really a string
2409 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2410 if (!Ty->isPointerType() ||
2411 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2412 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2413 IdxExpr->getSourceRange());
2414 return;
2415 }
2416
2417
2418 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002419 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002420 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002421 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2422 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2423 "format", std::string("3"), FirstArgExpr->getSourceRange());
2424 return;
2425 }
2426
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002427 // check if the function is variadic if the 3rd argument non-zero
2428 if (FirstArg != 0) {
2429 if (proto->isVariadic()) {
2430 ++NumArgs; // +1 for ...
2431 } else {
2432 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2433 return;
2434 }
2435 }
2436
2437 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2438 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002439 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002440 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002441 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2442 FirstArgExpr->getSourceRange());
2443 return;
2444 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002445 // if 0 it disables parameter checking (to use with e.g. va_list)
2446 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002447 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2448 "format", std::string("3"), FirstArgExpr->getSourceRange());
2449 return;
2450 }
2451
2452 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2453 Idx.getZExtValue(), FirstArg.getZExtValue()));
2454}
2455
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002456void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2457 // check the attribute arguments.
2458 if (rawAttr->getNumArgs() != 0) {
2459 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2460 std::string("0"));
2461 return;
2462 }
2463
2464 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2465
2466 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2467 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2468 "transparent_union", "union");
2469 return;
2470 }
2471
Chris Lattner22624942008-04-30 16:04:01 +00002472 //QualType QTy = Context.getTypeDeclType(decl);
2473 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002474
2475// FIXME
2476// Ty->addAttr(new TransparentUnionAttr());
2477}
2478
Nate Begemanc398f0b2008-02-21 19:30:49 +00002479void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2480 // check the attribute arguments.
2481 if (rawAttr->getNumArgs() != 1) {
2482 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2483 std::string("1"));
2484 return;
2485 }
2486 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2487 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002488
Nate Begemanc398f0b2008-02-21 19:30:49 +00002489 // Make sure that there is a string literal as the annotation's single
2490 // argument.
2491 if (!SE) {
2492 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2493 return;
2494 }
2495 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2496 SE->getByteLength())));
2497}
2498
Anders Carlsson78aaae92007-12-19 07:19:40 +00002499void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2500{
2501 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002502 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002503 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002504 std::string("1"));
2505 return;
2506 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002507
Anders Carlsson042c4e72008-02-16 19:51:27 +00002508 unsigned Align = 0;
2509
2510 if (rawAttr->getNumArgs() == 0) {
2511 // FIXME: This should be the target specific maximum alignment.
2512 // (For now we just use 128 bits which is the maximum on X86.
2513 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002514 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002515 } else {
2516 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2517 llvm::APSInt alignment(32);
2518 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002519 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002520 "aligned", alignmentExpr->getSourceRange());
2521 return;
2522 }
2523
2524 Align = alignment.getZExtValue() * 8;
2525 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002526
Anders Carlsson042c4e72008-02-16 19:51:27 +00002527 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002528}