blob: 328741ec0feeaf92d116c161b3d790047d9234c4 [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 Lattnerb048c982008-04-06 04:47:34 +000045void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattner0ed844b2008-04-04 06:12:32 +000046 assert(CD->getParent() == CurContext &&
Chris Lattnerb048c982008-04-06 04:47:34 +000047 "The next DeclContext should be directly contained in the current one.");
Chris Lattner0ed844b2008-04-04 06:12:32 +000048 CurContext = CD;
49}
50
Chris Lattnerb048c982008-04-06 04:47:34 +000051void Sema::PopDeclContext() {
52 assert(CurContext && "DeclContext imbalance!");
Chris Lattner0ed844b2008-04-04 06:12:32 +000053 CurContext = CurContext->getParent();
54}
55
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000056/// Add this decl to the scope shadowed decl chains.
57void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
58 IdResolver.AddDecl(D, S);
59 S->AddDecl(D);
60}
61
Steve Naroffb216c882007-10-09 22:01:59 +000062void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000063 if (S->decl_empty()) return;
64 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
65
Reid Spencer5f016e22007-07-11 17:01:13 +000066 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
67 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000068 Decl *TmpD = static_cast<Decl*>(*I);
69 assert(TmpD && "This decl didn't get pushed??");
70 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
71 assert(D && "This decl isn't a ScopedDecl?");
72
Reid Spencer5f016e22007-07-11 17:01:13 +000073 IdentifierInfo *II = D->getIdentifier();
74 if (!II) continue;
75
Chris Lattner7f925cc2008-04-11 07:00:53 +000076 // Unlink this decl from the identifier.
77 IdResolver.RemoveDecl(D);
78
Reid Spencer5f016e22007-07-11 17:01:13 +000079 // This will have to be revisited for C++: there we want to nest stuff in
80 // namespace decls etc. Even for C, we might want a top-level translation
81 // unit decl or something.
82 if (!CurFunctionDecl)
83 continue;
84
85 // Chain this decl to the containing function, it now owns the memory for
86 // the decl.
87 D->setNext(CurFunctionDecl->getDeclChain());
88 CurFunctionDecl->setDeclChain(D);
89 }
90}
91
Steve Naroffe8043c32008-04-01 23:04:06 +000092/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
93/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000094ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000095 // The third "scope" argument is 0 since we aren't enabling lazy built-in
96 // creation from this context.
97 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000098
Steve Naroffb327ce02008-04-02 14:35:35 +000099 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000100}
101
Steve Naroffe8043c32008-04-01 23:04:06 +0000102/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000103/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000104Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
105 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000107 unsigned NS = NSI;
108 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
109 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // Scan up the scope chain looking for a decl that matches this identifier
112 // that is in the appropriate namespace. This search should not take long, as
113 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000114 NamedDecl *ND = IdResolver.Lookup(II, NS);
115 if (ND) return ND;
116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 // If we didn't find a use of this identifier, and if the identifier
118 // corresponds to a compiler builtin, create the decl object for the builtin
119 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000120 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000121 if (enableLazyBuiltinCreation) {
122 // If this is a builtin on this (or all) targets, create the decl.
123 if (unsigned BuiltinID = II->getBuiltinID())
124 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
125 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000126 if (getLangOptions().ObjC1) {
127 // @interface and @compatibility_alias introduce typedef-like names.
128 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000129 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000130 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000131 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
132 if (IDI != ObjCInterfaceDecls.end())
133 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000134 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
135 if (I != ObjCAliasDecls.end())
136 return I->second->getClassInterface();
137 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 }
139 return 0;
140}
141
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000142void Sema::InitBuiltinVaListType()
143{
144 if (!Context.getBuiltinVaListType().isNull())
145 return;
146
147 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000148 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000149 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000150 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
151}
152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
154/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000155ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
156 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 Builtin::ID BID = (Builtin::ID)bid;
158
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000159 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000160 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000161 BID == Builtin::BI__builtin_va_end)
162 InitBuiltinVaListType();
163
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000164 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000165 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
166 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000167 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000168
Chris Lattner7f925cc2008-04-11 07:00:53 +0000169 // TUScope is the translation-unit scope to insert this function into.
170 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000171
172 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000173 IdResolver.AddGlobalDecl(New);
174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 return New;
176}
177
178/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
179/// and scope as a previous declaration 'Old'. Figure out how to resolve this
180/// situation, merging decls or emitting diagnostics as appropriate.
181///
Steve Naroffe8043c32008-04-01 23:04:06 +0000182TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Verify the old decl was also a typedef.
184 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
185 if (!Old) {
186 Diag(New->getLocation(), diag::err_redefinition_different_kind,
187 New->getName());
188 Diag(OldD->getLocation(), diag::err_previous_definition);
189 return New;
190 }
191
Steve Naroff8ee529b2007-10-31 18:42:27 +0000192 // Allow multiple definitions for ObjC built-in typedefs.
193 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000194 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000195 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000196
197 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
198 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
199 // *either* declaration is in a system header. The code below implements
200 // this adhoc compatibility rule. FIXME: The following code will not
201 // work properly when compiling ".i" files (containing preprocessed output).
202 SourceManager &SrcMgr = Context.getSourceManager();
203 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
204 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
205 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
206 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
207 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
208
Steve Naroffc5e2f342008-03-26 21:27:00 +0000209 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
210 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
211 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000212 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000213 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000214
Reid Spencer5f016e22007-07-11 17:01:13 +0000215 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
216 // TODO: This is totally simplistic. It should handle merging functions
217 // together etc, merging extern int X; int X; ...
218 Diag(New->getLocation(), diag::err_redefinition, New->getName());
219 Diag(Old->getLocation(), diag::err_previous_definition);
220 return New;
221}
222
Chris Lattnerddee4232008-03-03 03:28:21 +0000223/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
224static bool DeclHasAttr(const Decl *decl, const Attr *target) {
225 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
226 if (attr->getKind() == target->getKind())
227 return true;
228
229 return false;
230}
231
232/// MergeAttributes - append attributes from the Old decl to the New one.
233static void MergeAttributes(Decl *New, Decl *Old) {
234 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
235
236// FIXME: fix this code to cleanup the Old attrs correctly
237 while (attr) {
238 tmp = attr;
239 attr = attr->getNext();
240
241 if (!DeclHasAttr(New, tmp)) {
242 New->addAttr(tmp);
243 } else {
244 tmp->setNext(0);
245 delete(tmp);
246 }
247 }
248}
249
Chris Lattner04421082008-04-08 04:40:51 +0000250/// MergeFunctionDecl - We just parsed a function 'New' from
251/// declarator D which has the same name and scope as a previous
252/// declaration 'Old'. Figure out how to resolve this situation,
253/// merging decls or emitting diagnostics as appropriate.
Reid Spencer5f016e22007-07-11 17:01:13 +0000254///
Steve Naroffe8043c32008-04-01 23:04:06 +0000255FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // Verify the old decl was also a function.
257 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
258 if (!Old) {
259 Diag(New->getLocation(), diag::err_redefinition_different_kind,
260 New->getName());
261 Diag(OldD->getLocation(), diag::err_previous_definition);
262 return New;
263 }
Chris Lattner04421082008-04-08 04:40:51 +0000264
Chris Lattnerddee4232008-03-03 03:28:21 +0000265 MergeAttributes(New, Old);
266
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000267 QualType OldQType = Context.getCanonicalType(Old->getType());
268 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000269
Chris Lattner04421082008-04-08 04:40:51 +0000270 // C++ [dcl.fct]p3:
271 // All declarations for a function shall agree exactly in both the
272 // return type and the parameter-type-list.
273 if (getLangOptions().CPlusPlus && OldQType == NewQType)
274 return MergeCXXFunctionDecl(New, Old);
275
276 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000277 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000278 if (!getLangOptions().CPlusPlus &&
279 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000280 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000281 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000282
Steve Naroff837618c2008-01-16 15:01:34 +0000283 // A function that has already been declared has been redeclared or defined
284 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000285 diag::kind PrevDiag;
286 if (Old->getBody())
287 PrevDiag = diag::err_previous_definition;
288 else if (Old->isImplicit())
289 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000290 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000291 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
294 // TODO: This is totally simplistic. It should handle merging functions
295 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000296 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
297 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 return New;
299}
300
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000301/// equivalentArrayTypes - Used to determine whether two array types are
302/// equivalent.
303/// We need to check this explicitly as an incomplete array definition is
304/// considered a VariableArrayType, so will not match a complete array
305/// definition that would be otherwise equivalent.
306static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
307 const ArrayType *NewAT = NewQType->getAsArrayType();
308 const ArrayType *OldAT = OldQType->getAsArrayType();
309
310 if (!NewAT || !OldAT)
311 return false;
312
313 // If either (or both) array types in incomplete we need to strip off the
314 // outer VariableArrayType. Once the outer VAT is removed the remaining
315 // types must be identical if the array types are to be considered
316 // equivalent.
317 // eg. int[][1] and int[1][1] become
318 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
319 // removing the outermost VAT gives
320 // CAT(1, int) and CAT(1, int)
321 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000322 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000323 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
324 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000325 NewQType = NewAT->getElementType().getCanonicalType();
326 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000327 }
328
329 return NewQType == OldQType;
330}
331
Reid Spencer5f016e22007-07-11 17:01:13 +0000332/// MergeVarDecl - We just parsed a variable 'New' which has the same name
333/// and scope as a previous declaration 'Old'. Figure out how to resolve this
334/// situation, merging decls or emitting diagnostics as appropriate.
335///
336/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
337/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
338///
Steve Naroffe8043c32008-04-01 23:04:06 +0000339VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000340 // Verify the old decl was also a variable.
341 VarDecl *Old = dyn_cast<VarDecl>(OldD);
342 if (!Old) {
343 Diag(New->getLocation(), diag::err_redefinition_different_kind,
344 New->getName());
345 Diag(OldD->getLocation(), diag::err_previous_definition);
346 return New;
347 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000348
349 MergeAttributes(New, Old);
350
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000352 QualType OldCType = Context.getCanonicalType(Old->getType());
353 QualType NewCType = Context.getCanonicalType(New->getType());
354 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 Diag(New->getLocation(), diag::err_redefinition, New->getName());
356 Diag(Old->getLocation(), diag::err_previous_definition);
357 return New;
358 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000359 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
360 if (New->getStorageClass() == VarDecl::Static &&
361 (Old->getStorageClass() == VarDecl::None ||
362 Old->getStorageClass() == VarDecl::Extern)) {
363 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
364 Diag(Old->getLocation(), diag::err_previous_definition);
365 return New;
366 }
367 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
368 if (New->getStorageClass() != VarDecl::Static &&
369 Old->getStorageClass() == VarDecl::Static) {
370 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
371 Diag(Old->getLocation(), diag::err_previous_definition);
372 return New;
373 }
374 // We've verified the types match, now handle "tentative" definitions.
375 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
376 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
377
378 if (OldFSDecl && NewFSDecl) {
379 // Handle C "tentative" external object definitions (C99 6.9.2).
380 bool OldIsTentative = false;
381 bool NewIsTentative = false;
382
383 if (!OldFSDecl->getInit() &&
384 (OldFSDecl->getStorageClass() == VarDecl::None ||
385 OldFSDecl->getStorageClass() == VarDecl::Static))
386 OldIsTentative = true;
387
388 // FIXME: this check doesn't work (since the initializer hasn't been
389 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
390 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
391 // thrown out the old decl.
392 if (!NewFSDecl->getInit() &&
393 (NewFSDecl->getStorageClass() == VarDecl::None ||
394 NewFSDecl->getStorageClass() == VarDecl::Static))
395 ; // change to NewIsTentative = true; once the code is moved.
396
397 if (NewIsTentative || OldIsTentative)
398 return New;
399 }
400 if (Old->getStorageClass() != VarDecl::Extern &&
401 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 Diag(New->getLocation(), diag::err_redefinition, New->getName());
403 Diag(Old->getLocation(), diag::err_previous_definition);
404 }
405 return New;
406}
407
Chris Lattner04421082008-04-08 04:40:51 +0000408/// CheckParmsForFunctionDef - Check that the parameters of the given
409/// function are appropriate for the definition of a function. This
410/// takes care of any checks that cannot be performed on the
411/// declaration itself, e.g., that the types of each of the function
412/// parameters are complete.
413bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
414 bool HasInvalidParm = false;
415 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
416 ParmVarDecl *Param = FD->getParamDecl(p);
417
418 // C99 6.7.5.3p4: the parameters in a parameter type list in a
419 // function declarator that is part of a function definition of
420 // that function shall not have incomplete type.
421 if (Param->getType()->isIncompleteType() &&
422 !Param->isInvalidDecl()) {
423 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
424 Param->getType().getAsString());
425 Param->setInvalidDecl();
426 HasInvalidParm = true;
427 }
428 }
429
430 return HasInvalidParm;
431}
432
433/// CreateImplicitParameter - Creates an implicit function parameter
434/// in the scope S and with the given type. This routine is used, for
435/// example, to create the implicit "self" parameter in an Objective-C
436/// method.
437ParmVarDecl *
438Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
439 SourceLocation IdLoc, QualType Type) {
440 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
441 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000442 if (Id)
443 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000444
445 return New;
446}
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
449/// no declarator (e.g. "struct foo;") is parsed.
450Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
451 // TODO: emit error on 'int;' or 'const enum foo;'.
452 // TODO: emit error on 'typedef int;'
453 // if (!DS.isMissingDeclaratorOk()) Diag(...);
454
Steve Naroff92199282007-11-17 21:37:36 +0000455 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000456}
457
Steve Naroffd0091aa2008-01-10 22:15:12 +0000458bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000459 // Get the type before calling CheckSingleAssignmentConstraints(), since
460 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000461 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000462
Chris Lattner5cf216b2008-01-04 18:04:52 +0000463 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
464 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
465 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000466}
467
Steve Naroff9e8925e2007-09-04 14:36:54 +0000468bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000469 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000470 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000471 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000472 return true; // types weren't compatible.
473
Steve Naroff9e8925e2007-09-04 14:36:54 +0000474 if (savExpr != expr) // The type was promoted, update initializer list.
475 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000476 return false;
477}
478
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000479bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000480 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000481 // C99 6.7.8p14. We have an array of character type with unknown size
482 // being initialized to a string literal.
483 llvm::APSInt ConstVal(32);
484 ConstVal = strLiteral->getByteLength() + 1;
485 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000486 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000487 ArrayType::Normal, 0);
488 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
489 // C99 6.7.8p14. We have an array of character type with known size.
490 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
491 Diag(strLiteral->getSourceRange().getBegin(),
492 diag::warn_initializer_string_for_char_array_too_long,
493 strLiteral->getSourceRange());
494 } else {
495 assert(0 && "HandleStringLiteralInit(): Invalid array type");
496 }
497 // Set type from "char *" to "constant array of char".
498 strLiteral->setType(DeclT);
499 // For now, we always return false (meaning success).
500 return false;
501}
502
503StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000504 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000505 if (AT && AT->getElementType()->isCharType()) {
506 return dyn_cast<StringLiteral>(Init);
507 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000508 return 0;
509}
510
Steve Naroffa9960332008-01-25 00:51:06 +0000511// CheckInitializerListTypes - Checks the types of elements of an initializer
512// list. This function is recursive: it calls itself to initialize subelements
513// of aggregate types. Note that the topLevel parameter essentially refers to
514// whether this expression "owns" the initializer list passed in, or if this
515// initialization is taking elements out of a parent initializer. Each
516// call to this function adds zero or more to startIndex, reports any errors,
517// and returns true if it found any inconsistent types.
518bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
519 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000520 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000521
522 if (DeclType->isScalarType()) {
523 // The simplest case: initializing a single scalar
524 if (topLevel) {
525 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
526 IList->getSourceRange());
527 }
528 if (startIndex < IList->getNumInits()) {
529 Expr* expr = IList->getInit(startIndex);
530 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
531 // FIXME: Should an error be reported here instead?
532 unsigned newIndex = 0;
533 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
534 } else {
535 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
536 }
537 ++startIndex;
538 }
539 // FIXME: Should an error be reported for empty initializer list + scalar?
540 } else if (DeclType->isVectorType()) {
541 if (startIndex < IList->getNumInits()) {
542 const VectorType *VT = DeclType->getAsVectorType();
543 int maxElements = VT->getNumElements();
544 QualType elementType = VT->getElementType();
545
546 for (int i = 0; i < maxElements; ++i) {
547 // Don't attempt to go past the end of the init list
548 if (startIndex >= IList->getNumInits())
549 break;
550 Expr* expr = IList->getInit(startIndex);
551 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
552 unsigned newIndex = 0;
553 hadError |= CheckInitializerListTypes(SubInitList, elementType,
554 true, newIndex);
555 ++startIndex;
556 } else {
557 hadError |= CheckInitializerListTypes(IList, elementType,
558 false, startIndex);
559 }
560 }
561 }
562 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
563 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000564 if (startIndex < IList->getNumInits() && !topLevel &&
565 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
566 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000567 // We found a compatible struct; per the standard, this initializes the
568 // struct. (The C standard technically says that this only applies for
569 // initializers for declarations with automatic scope; however, this
570 // construct is unambiguous anyway because a struct cannot contain
571 // a type compatible with itself. We'll output an error when we check
572 // if the initializer is constant.)
573 // FIXME: Is a call to CheckSingleInitializer required here?
574 ++startIndex;
575 } else {
576 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000577
Steve Naroff406db932008-02-11 21:52:37 +0000578 // If the record is invalid, some of it's members are invalid. To avoid
579 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000580 if (structDecl->isInvalidDecl())
581 return true;
582
Steve Naroffa9960332008-01-25 00:51:06 +0000583 // If structDecl is a forward declaration, this loop won't do anything;
584 // That's okay, because an error should get printed out elsewhere. It
585 // might be worthwhile to skip over the rest of the initializer, though.
586 int numMembers = structDecl->getNumMembers() -
587 structDecl->hasFlexibleArrayMember();
588 for (int i = 0; i < numMembers; i++) {
589 // Don't attempt to go past the end of the init list
590 if (startIndex >= IList->getNumInits())
591 break;
592 FieldDecl * curField = structDecl->getMember(i);
593 if (!curField->getIdentifier()) {
594 // Don't initialize unnamed fields, e.g. "int : 20;"
595 continue;
596 }
597 QualType fieldType = curField->getType();
598 Expr* expr = IList->getInit(startIndex);
599 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
600 unsigned newStart = 0;
601 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
602 true, newStart);
603 ++startIndex;
604 } else {
605 hadError |= CheckInitializerListTypes(IList, fieldType,
606 false, startIndex);
607 }
608 if (DeclType->isUnionType())
609 break;
610 }
611 // FIXME: Implement flexible array initialization GCC extension (it's a
612 // really messy extension to implement, unfortunately...the necessary
613 // information isn't actually even here!)
614 }
615 } else if (DeclType->isArrayType()) {
616 // Check for the special-case of initializing an array with a string.
617 if (startIndex < IList->getNumInits()) {
618 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
619 DeclType)) {
620 CheckStringLiteralInit(lit, DeclType);
621 ++startIndex;
622 if (topLevel && startIndex < IList->getNumInits()) {
623 // We have leftover initializers; warn
624 Diag(IList->getInit(startIndex)->getLocStart(),
625 diag::err_excess_initializers_in_char_array_initializer,
626 IList->getInit(startIndex)->getSourceRange());
627 }
628 return false;
629 }
630 }
631 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000632 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000633 // FIXME: use a proper constant
634 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000635 } else if (const VariableArrayType *VAT =
636 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000637 // Check for VLAs; in standard C it would be possible to check this
638 // earlier, but I don't know where clang accepts VLAs (gcc accepts
639 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000640 Diag(VAT->getSizeExpr()->getLocStart(),
641 diag::err_variable_object_no_init,
642 VAT->getSizeExpr()->getSourceRange());
643 hadError = true;
644 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000645 } else {
646 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
647 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
648 }
649 QualType elementType = DeclType->getAsArrayType()->getElementType();
650 int numElements = 0;
651 for (int i = 0; i < maxElements; ++i, ++numElements) {
652 // Don't attempt to go past the end of the init list
653 if (startIndex >= IList->getNumInits())
654 break;
655 Expr* expr = IList->getInit(startIndex);
656 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
657 unsigned newIndex = 0;
658 hadError |= CheckInitializerListTypes(SubInitList, elementType,
659 true, newIndex);
660 ++startIndex;
661 } else {
662 hadError |= CheckInitializerListTypes(IList, elementType,
663 false, startIndex);
664 }
665 }
Eli Friedman9db13972008-02-15 12:53:51 +0000666 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000667 // If this is an incomplete array type, the actual type needs to
668 // be calculated here
669 if (numElements == 0) {
670 // Sizing an array implicitly to zero is not allowed
671 // (It could in theory be allowed, but it doesn't really matter.)
672 Diag(IList->getLocStart(),
673 diag::err_at_least_one_initializer_needed_to_size_array);
674 hadError = true;
675 } else {
676 llvm::APSInt ConstVal(32);
677 ConstVal = numElements;
678 DeclType = Context.getConstantArrayType(elementType, ConstVal,
679 ArrayType::Normal, 0);
680 }
681 }
682 } else {
683 assert(0 && "Aggregate that isn't a function or array?!");
684 }
685 } else {
686 // In C, all types are either scalars or aggregates, but
687 // additional handling is needed here for C++ (and possibly others?).
688 assert(0 && "Unsupported initializer type");
689 }
690
691 // If this init list is a base list, we set the type; an initializer doesn't
692 // fundamentally have a type, but this makes the ASTs a bit easier to read
693 if (topLevel)
694 IList->setType(DeclType);
695
696 if (topLevel && startIndex < IList->getNumInits()) {
697 // We have leftover initializers; warn
698 Diag(IList->getInit(startIndex)->getLocStart(),
699 diag::warn_excess_initializers,
700 IList->getInit(startIndex)->getSourceRange());
701 }
702 return hadError;
703}
704
705bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000706 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
707 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000708 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000709 return Diag(VAT->getSizeExpr()->getLocStart(),
710 diag::err_variable_object_no_init,
711 VAT->getSizeExpr()->getSourceRange());
712
Steve Naroff2fdc3742007-12-10 22:44:33 +0000713 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
714 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000715 // FIXME: Handle wide strings
716 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
717 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000718
719 if (DeclType->isArrayType())
720 return Diag(Init->getLocStart(),
721 diag::err_array_init_list_required,
722 Init->getSourceRange());
723
Steve Naroffd0091aa2008-01-10 22:15:12 +0000724 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000725 }
Steve Naroffa9960332008-01-25 00:51:06 +0000726 unsigned newIndex = 0;
727 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000728}
729
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000730Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000731Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000732 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000733 IdentifierInfo *II = D.getIdentifier();
734
Chris Lattnere80a59c2007-07-25 00:24:17 +0000735 // All of these full declarators require an identifier. If it doesn't have
736 // one, the ParsedFreeStandingDeclSpec action should be used.
737 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000738 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000739 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000740 D.getDeclSpec().getSourceRange(), D.getSourceRange());
741 return 0;
742 }
743
Chris Lattner31e05722007-08-26 06:24:45 +0000744 // The scope passed in may not be a decl scope. Zip up the scope tree until
745 // we find one that is.
746 while ((S->getFlags() & Scope::DeclScope) == 0)
747 S = S->getParent();
748
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000750 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000751 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000752 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000753
754 // In C++, the previous declaration we find might be a tag type
755 // (class or enum). In this case, the new declaration will hide the
756 // tag type.
757 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
758 PrevDecl = 0;
759
Chris Lattner41af0932007-11-14 06:34:38 +0000760 QualType R = GetTypeForDeclarator(D, S);
761 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
762
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000764 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000765 if (!NewTD) return 0;
766
767 // Handle attributes prior to checking for duplicates in MergeVarDecl
768 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
769 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000770 // Merge the decl with the existing one if appropriate. If the decl is
771 // in an outer scope, it isn't the same thing.
772 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
774 if (NewTD == 0) return 0;
775 }
776 New = NewTD;
777 if (S->getParent() == 0) {
778 // C99 6.7.7p2: If a typedef name specifies a variably modified type
779 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000780 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
781 // FIXME: Diagnostic needs to be fixed.
782 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000783 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 }
785 }
Chris Lattner41af0932007-11-14 06:34:38 +0000786 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000787 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 switch (D.getDeclSpec().getStorageClassSpec()) {
789 default: assert(0 && "Unknown storage class!");
790 case DeclSpec::SCS_auto:
791 case DeclSpec::SCS_register:
792 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
793 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000794 InvalidDecl = true;
795 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
797 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
798 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000799 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 }
801
Chris Lattnera98e58d2008-03-15 21:24:04 +0000802 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000803 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
804 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000805 II, R, SC, isInline,
806 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000807 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000808 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
809 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000810
811 // Copy the parameter declarations from the declarator D to
812 // the function declaration NewFD, if they are available.
813 if (D.getNumTypeObjects() > 0 &&
814 D.getTypeObject(0).Fun.hasPrototype) {
815 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
816
817 // Create Decl objects for each parameter, adding them to the
818 // FunctionDecl.
819 llvm::SmallVector<ParmVarDecl*, 16> Params;
820
821 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
822 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000823 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000824 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
825 FTI.ArgInfo[0].Param &&
826 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
827 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
828 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000829 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
830
Chris Lattnerdef026a2008-04-10 02:26:16 +0000831 // In C++, the empty parameter-type-list must be spelled "void"; a
832 // typedef of void is not permitted.
833 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000834 Param->getType() != Context.VoidTy) {
835 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
836 }
837
Chris Lattner04421082008-04-08 04:40:51 +0000838 } else {
839 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
840 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
841 }
842
843 NewFD->setParams(&Params[0], Params.size());
844 }
845
Steve Naroffffce4d52008-01-09 23:34:55 +0000846 // Merge the decl with the existing one if appropriate. Since C functions
847 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 if (PrevDecl) {
849 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
850 if (NewFD == 0) return 0;
851 }
852 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000853
854 // In C++, check default arguments now that we have merged decls.
855 if (getLangOptions().CPlusPlus)
856 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000858 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000859 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
860 D.getIdentifier()->getName());
861 InvalidDecl = true;
862 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000863
864 VarDecl *NewVD;
865 VarDecl::StorageClass SC;
866 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000867 default: assert(0 && "Unknown storage class!");
868 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
869 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
870 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
871 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
872 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
873 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000874 }
875 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 // C99 6.9p2: The storage-class specifiers auto and register shall not
877 // appear in the declaration specifiers in an external declaration.
878 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
879 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
880 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000881 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000883 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
884 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000885 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000886 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000887 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
888 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000889 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000890 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 // Handle attributes prior to checking for duplicates in MergeVarDecl
892 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
893 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000894
895 // Emit an error if an address space was applied to decl with local storage.
896 // This includes arrays of objects with address space qualifiers, but not
897 // automatic variables that point to other address spaces.
898 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000899 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
900 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
901 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000902 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000903 // Merge the decl with the existing one if appropriate. If the decl is
904 // in an outer scope, it isn't the same thing.
905 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 NewVD = MergeVarDecl(NewVD, PrevDecl);
907 if (NewVD == 0) return 0;
908 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 New = NewVD;
910 }
911
912 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000913 if (II)
914 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000915 // If any semantic error occurred, mark the decl as invalid.
916 if (D.getInvalidType() || InvalidDecl)
917 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000918
919 return New;
920}
921
Steve Naroffd0091aa2008-01-10 22:15:12 +0000922bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
923 SourceLocation loc;
924 // FIXME: Remove the isReference check and handle assignment to a reference.
925 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
926 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
927 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
928 return true;
929 }
930 return false;
931}
932
Steve Naroffbb204692007-09-12 14:07:44 +0000933void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000934 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000935 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000936 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000937
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000938 // If there is no declaration, there was an error parsing it. Just ignore
939 // the initializer.
940 if (RealDecl == 0) {
941 delete Init;
942 return;
943 }
Steve Naroffbb204692007-09-12 14:07:44 +0000944
Steve Naroff410e3e22007-09-12 20:13:48 +0000945 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
946 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000947 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
948 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000949 RealDecl->setInvalidDecl();
950 return;
951 }
Steve Naroffbb204692007-09-12 14:07:44 +0000952 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000953 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000954 QualType DclT = VDecl->getType(), SavT = DclT;
955 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000956 VarDecl::StorageClass SC = BVD->getStorageClass();
957 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000958 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000959 BVD->setInvalidDecl();
960 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000961 if (CheckInitializerTypes(Init, DclT))
962 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000963 if (SC == VarDecl::Static) // C99 6.7.8p4.
964 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000965 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000966 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000967 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000968 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000969 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000970 if (CheckInitializerTypes(Init, DclT))
971 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000972
973 // C99 6.7.8p4. All file scoped initializers need to be constant.
974 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000975 }
976 // If the type changed, it means we had an incomplete type that was
977 // completed by the initializer. For example:
978 // int ary[] = { 1, 3, 5 };
979 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000980 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000981 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000982 Init->setType(DclT);
983 }
Steve Naroffbb204692007-09-12 14:07:44 +0000984
985 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000986 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000987 return;
988}
989
Reid Spencer5f016e22007-07-11 17:01:13 +0000990/// The declarators are chained together backwards, reverse the list.
991Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
992 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000993 Decl *GroupDecl = static_cast<Decl*>(group);
994 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000995 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000996
997 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
998 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000999 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001001 else { // reverse the list.
1002 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001003 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001004 Group->setNextDeclarator(NewGroup);
1005 NewGroup = Group;
1006 Group = Next;
1007 }
1008 }
1009 // Perform semantic analysis that depends on having fully processed both
1010 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001011 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001012 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1013 if (!IDecl)
1014 continue;
1015 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
1016 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
1017 QualType T = IDecl->getType();
1018
1019 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1020 // static storage duration, it shall not have a variable length array.
1021 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001022 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001023 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1024 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001025 }
1026 }
1027 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1028 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1029 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001030 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001031 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1032 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001033 IDecl->setInvalidDecl();
1034 }
1035 }
1036 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1037 // object that has file scope without an initializer, and without a
1038 // storage-class specifier or with the storage-class specifier "static",
1039 // constitutes a tentative definition. Note: A tentative definition with
1040 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +00001041 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
1042 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001043 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001044 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1045 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001046 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001047 // C99 6.9.2p3: If the declaration of an identifier for an object is
1048 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1049 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001050 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1051 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001052 IDecl->setInvalidDecl();
1053 }
1054 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 }
1056 return NewGroup;
1057}
Steve Naroffe1223f72007-08-28 03:03:08 +00001058
Chris Lattner04421082008-04-08 04:40:51 +00001059/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1060/// to introduce parameters into function prototype scope.
1061Sema::DeclTy *
1062Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1063 DeclSpec &DS = D.getDeclSpec();
1064
1065 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1066 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1067 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1068 Diag(DS.getStorageClassSpecLoc(),
1069 diag::err_invalid_storage_class_in_func_decl);
1070 DS.ClearStorageClassSpecs();
1071 }
1072 if (DS.isThreadSpecified()) {
1073 Diag(DS.getThreadSpecLoc(),
1074 diag::err_invalid_storage_class_in_func_decl);
1075 DS.ClearStorageClassSpecs();
1076 }
1077
1078
1079 // In this context, we *do not* check D.getInvalidType(). If the declarator
1080 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1081 // though it will not reflect the user specified type.
1082 QualType parmDeclType = GetTypeForDeclarator(D, S);
1083
1084 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1085
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1087 // Can this happen for params? We already checked that they don't conflict
1088 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001089 IdentifierInfo *II = D.getIdentifier();
1090 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1091 if (S->isDeclScope(PrevDecl)) {
1092 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1093 dyn_cast<NamedDecl>(PrevDecl)->getName());
1094
1095 // Recover by removing the name
1096 II = 0;
1097 D.SetIdentifier(0, D.getIdentifierLoc());
1098 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001100
1101 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1102 // Doing the promotion here has a win and a loss. The win is the type for
1103 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1104 // code generator). The loss is the orginal type isn't preserved. For example:
1105 //
1106 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1107 // int blockvardecl[5];
1108 // sizeof(parmvardecl); // size == 4
1109 // sizeof(blockvardecl); // size == 20
1110 // }
1111 //
1112 // For expressions, all implicit conversions are captured using the
1113 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1114 //
1115 // FIXME: If a source translation tool needs to see the original type, then
1116 // we need to consider storing both types (in ParmVarDecl)...
1117 //
Chris Lattnere6327742008-04-02 05:18:44 +00001118 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001119 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001120 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001121 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001122 parmDeclType = Context.getPointerType(parmDeclType);
1123
Chris Lattner04421082008-04-08 04:40:51 +00001124 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1125 D.getIdentifierLoc(), II,
1126 parmDeclType, VarDecl::None,
1127 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001128
Chris Lattner04421082008-04-08 04:40:51 +00001129 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001130 New->setInvalidDecl();
1131
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001132 if (II)
1133 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001134
Chris Lattner04421082008-04-08 04:40:51 +00001135 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001137
Reid Spencer5f016e22007-07-11 17:01:13 +00001138}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001139
Chris Lattnerb652cea2007-10-09 17:14:05 +00001140Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 assert(CurFunctionDecl == 0 && "Function parsing confused");
1142 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1143 "Not a function declarator!");
1144 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001145
Reid Spencer5f016e22007-07-11 17:01:13 +00001146 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1147 // for a K&R function.
1148 if (!FTI.hasPrototype) {
1149 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001150 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001151 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1152 FTI.ArgInfo[i].Ident->getName());
1153 // Implicitly declare the argument as type 'int' for lack of a better
1154 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001155 DeclSpec DS;
1156 const char* PrevSpec; // unused
1157 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1158 PrevSpec);
1159 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1160 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1161 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 }
1163 }
Chris Lattner52804082008-02-17 19:31:09 +00001164
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 // Since this is a function definition, act as though we have information
1166 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001167 if (FTI.NumArgs)
1168 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001169 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001170 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001171 }
1172
1173 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001174
1175 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001176 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001177 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001178 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1179 if (FD->getBody()) {
1180 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1181 D.getIdentifier()->getName());
1182 Diag(FD->getLocation(), diag::err_previous_definition);
1183 }
1184 }
Steve Narofffabbc342008-02-12 01:09:36 +00001185 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001186 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001188 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001189
1190 // Check the validity of our function parameters
1191 CheckParmsForFunctionDef(FD);
1192
1193 // Introduce our parameters into the function scope
1194 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1195 ParmVarDecl *Param = FD->getParamDecl(p);
1196 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001197 if (Param->getIdentifier())
1198 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 }
Chris Lattner04421082008-04-08 04:40:51 +00001200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 return FD;
1202}
1203
Steve Naroffd6d054d2007-11-11 23:20:51 +00001204Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1205 Decl *dcl = static_cast<Decl *>(D);
1206 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1207 FD->setBody((Stmt*)Body);
1208 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001209 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001211 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001212 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001213 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001214 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001215 // Verify and clean out per-function state.
1216
1217 // Check goto/label use.
1218 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1219 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1220 // Verify that we have no forward references left. If so, there was a goto
1221 // or address of a label taken, but no definition of it. Label fwd
1222 // definitions are indicated with a null substmt.
1223 if (I->second->getSubStmt() == 0) {
1224 LabelStmt *L = I->second;
1225 // Emit error.
1226 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1227
1228 // At this point, we have gotos that use the bogus label. Stitch it into
1229 // the function body so that they aren't leaked and that the AST is well
1230 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001231 if (Body) {
1232 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1233 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1234 } else {
1235 // The whole function wasn't parsed correctly, just delete this.
1236 delete L;
1237 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 }
1239 }
1240 LabelMap.clear();
1241
Steve Naroffd6d054d2007-11-11 23:20:51 +00001242 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001243}
1244
Reid Spencer5f016e22007-07-11 17:01:13 +00001245/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1246/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001247ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1248 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 if (getLangOptions().C99) // Extension in C99.
1250 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1251 else // Legal in C90, but warn about it.
1252 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1253
1254 // FIXME: handle stuff like:
1255 // void foo() { extern float X(); }
1256 // void bar() { X(); } <-- implicit decl for X in another scope.
1257
1258 // Set a Declarator for the implicit definition: int foo();
1259 const char *Dummy;
1260 DeclSpec DS;
1261 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1262 Error = Error; // Silence warning.
1263 assert(!Error && "Error setting up implicit decl!");
1264 Declarator D(DS, Declarator::BlockContext);
1265 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1266 D.SetIdentifier(&II, Loc);
1267
1268 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001269 if (Scope *FnS = S->getFnParent())
1270 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 while (S->getParent())
1272 S = S->getParent();
1273
Steve Naroffe2ef8152008-04-04 14:32:09 +00001274 FunctionDecl *FD =
1275 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1276 FD->setImplicit();
1277 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001278}
1279
1280
Chris Lattner41af0932007-11-14 06:34:38 +00001281TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001282 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001283 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001284 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001285
1286 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001287 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1288 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001289 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001290 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001291 if (D.getInvalidType())
1292 NewTD->setInvalidDecl();
1293 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001294}
1295
Steve Naroff08d92e42007-09-15 18:49:24 +00001296/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001297/// former case, Name will be non-null. In the later case, Name will be null.
1298/// TagType indicates what kind of tag this is. TK indicates whether this is a
1299/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001300Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 SourceLocation KWLoc, IdentifierInfo *Name,
1302 SourceLocation NameLoc, AttributeList *Attr) {
1303 // If this is a use of an existing tag, it must have a name.
1304 assert((Name != 0 || TK == TK_Definition) &&
1305 "Nameless record must be a definition!");
1306
1307 Decl::Kind Kind;
1308 switch (TagType) {
1309 default: assert(0 && "Unknown tag type!");
1310 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1311 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001312 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1314 }
1315
1316 // If this is a named struct, check to see if there was a previous forward
1317 // declaration or definition.
1318 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001319 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001320
1321 // If this is a use of a previous tag, or if the tag is already declared in
1322 // the same scope (so that the definition/declaration completes or
1323 // rementions the tag), reuse the decl.
1324 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1325 // Make sure that this wasn't declared as an enum and now used as a struct
1326 // or something similar.
1327 if (PrevDecl->getKind() != Kind) {
1328 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1329 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1330 }
1331
1332 // If this is a use or a forward declaration, we're good.
1333 if (TK != TK_Definition)
1334 return PrevDecl;
1335
1336 // Diagnose attempts to redefine a tag.
1337 if (PrevDecl->isDefinition()) {
1338 Diag(NameLoc, diag::err_redefinition, Name->getName());
1339 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1340 // If this is a redefinition, recover by making this struct be
1341 // anonymous, which will make any later references get the previous
1342 // definition.
1343 Name = 0;
1344 } else {
1345 // Okay, this is definition of a previously declared or referenced tag.
1346 // Move the location of the decl to be the definition site.
1347 PrevDecl->setLocation(NameLoc);
1348 return PrevDecl;
1349 }
1350 }
1351 // If we get here, this is a definition of a new struct type in a nested
1352 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1353 // type.
1354 }
1355
1356 // If there is an identifier, use the location of the identifier as the
1357 // location of the decl, otherwise use the location of the struct/union
1358 // keyword.
1359 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1360
1361 // Otherwise, if this is the first time we've seen this tag, create the decl.
1362 TagDecl *New;
1363 switch (Kind) {
1364 default: assert(0 && "Unknown tag kind!");
1365 case Decl::Enum:
1366 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1367 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001368 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // If this is an undefined enum, warn.
1370 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1371 break;
1372 case Decl::Union:
1373 case Decl::Struct:
1374 case Decl::Class:
1375 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1376 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001377 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 break;
1379 }
1380
1381 // If this has an identifier, add it to the scope stack.
1382 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001383 // The scope passed in may not be a decl scope. Zip up the scope tree until
1384 // we find one that is.
1385 while ((S->getFlags() & Scope::DeclScope) == 0)
1386 S = S->getParent();
1387
1388 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001389 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001391
Anders Carlssonad148062008-02-16 00:29:18 +00001392 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 return New;
1394}
1395
Steve Naroff08d92e42007-09-15 18:49:24 +00001396/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001397/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001398Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001399 SourceLocation DeclStart,
1400 Declarator &D, ExprTy *BitfieldWidth) {
1401 IdentifierInfo *II = D.getIdentifier();
1402 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 SourceLocation Loc = DeclStart;
1404 if (II) Loc = D.getIdentifierLoc();
1405
1406 // FIXME: Unnamed fields can be handled in various different ways, for
1407 // example, unnamed unions inject all members into the struct namespace!
1408
1409
1410 if (BitWidth) {
1411 // TODO: Validate.
1412 //printf("WARNING: BITFIELDS IGNORED!\n");
1413
1414 // 6.7.2.1p3
1415 // 6.7.2.1p4
1416
1417 } else {
1418 // Not a bitfield.
1419
1420 // validate II.
1421
1422 }
1423
1424 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001425 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1426 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001427
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1429 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001430 if (T->isVariablyModifiedType()) {
1431 // FIXME: This diagnostic needs work
1432 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001433 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001436 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001437
Anders Carlssonad148062008-02-16 00:29:18 +00001438 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1439 D.getAttributes());
1440
Steve Naroff5912a352007-08-28 20:14:24 +00001441 if (D.getInvalidType() || InvalidDecl)
1442 NewFD->setInvalidDecl();
1443 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001444}
1445
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001446/// TranslateIvarVisibility - Translate visibility from a token ID to an
1447/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001448static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001449TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001450 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001451 case tok::objc_private: return ObjCIvarDecl::Private;
1452 case tok::objc_public: return ObjCIvarDecl::Public;
1453 case tok::objc_protected: return ObjCIvarDecl::Protected;
1454 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001455 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001456 }
1457}
1458
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001459/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1460/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001461Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001462 SourceLocation DeclStart,
1463 Declarator &D, ExprTy *BitfieldWidth,
1464 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001465 IdentifierInfo *II = D.getIdentifier();
1466 Expr *BitWidth = (Expr*)BitfieldWidth;
1467 SourceLocation Loc = DeclStart;
1468 if (II) Loc = D.getIdentifierLoc();
1469
1470 // FIXME: Unnamed fields can be handled in various different ways, for
1471 // example, unnamed unions inject all members into the struct namespace!
1472
1473
1474 if (BitWidth) {
1475 // TODO: Validate.
1476 //printf("WARNING: BITFIELDS IGNORED!\n");
1477
1478 // 6.7.2.1p3
1479 // 6.7.2.1p4
1480
1481 } else {
1482 // Not a bitfield.
1483
1484 // validate II.
1485
1486 }
1487
1488 QualType T = GetTypeForDeclarator(D, S);
1489 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1490 bool InvalidDecl = false;
1491
1492 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1493 // than a variably modified type.
1494 if (T->isVariablyModifiedType()) {
1495 // FIXME: This diagnostic needs work
1496 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1497 InvalidDecl = true;
1498 }
1499
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001500 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001501
1502 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1503 D.getAttributes());
1504
1505 if (D.getInvalidType() || InvalidDecl)
1506 NewID->setInvalidDecl();
1507 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001508 if (Visibility != tok::objc_not_keyword)
1509 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001510 return NewID;
1511}
1512
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001513void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001514 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001515 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001516 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001517 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1518 assert(EnclosingDecl && "missing record or interface decl");
1519 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1520
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001521 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 // Diagnose code like:
1523 // struct S { struct S {} X; };
1524 // We discover this when we complete the outer S. Reject and ignore the
1525 // outer S.
1526 Diag(Record->getLocation(), diag::err_nested_redefinition,
1527 Record->getKindName());
1528 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001529 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 return;
1531 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 // Verify that all the fields are okay.
1533 unsigned NumNamedMembers = 0;
1534 llvm::SmallVector<FieldDecl*, 32> RecFields;
1535 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001536
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001538
Steve Naroff74216642007-09-14 22:20:54 +00001539 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1540 assert(FD && "missing field decl");
1541
1542 // Remember all fields.
1543 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001544
1545 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001546 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001549 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001550 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001552 FD->setInvalidDecl();
1553 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 continue;
1555 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1557 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001558 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001559 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001560 FD->setInvalidDecl();
1561 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001562 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001563 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 if (i != NumFields-1 || // ... that the last member ...
1565 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001566 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001568 FD->setInvalidDecl();
1569 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 continue;
1571 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001572 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1574 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001575 FD->setInvalidDecl();
1576 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001577 continue;
1578 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001580 if (Record)
1581 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1584 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001585 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1587 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001588 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 Record->setHasFlexibleArrayMember(true);
1590 } else {
1591 // If this is a struct/class and this is not the last element, reject
1592 // it. Note that GCC supports variable sized arrays in the middle of
1593 // structures.
1594 if (i != NumFields-1) {
1595 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1596 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001597 FD->setInvalidDecl();
1598 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 continue;
1600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 // We support flexible arrays at the end of structs in other structs
1602 // as an extension.
1603 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1604 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001605 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001606 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 }
1608 }
1609 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001610 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001612 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1613 FD->getName());
1614 FD->setInvalidDecl();
1615 EnclosingDecl->setInvalidDecl();
1616 continue;
1617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 // Keep track of the number of named members.
1619 if (IdentifierInfo *II = FD->getIdentifier()) {
1620 // Detect duplicate member names.
1621 if (!FieldIDs.insert(II)) {
1622 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1623 // Find the previous decl.
1624 SourceLocation PrevLoc;
1625 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1626 assert(i != e && "Didn't find previous def!");
1627 if (RecFields[i]->getIdentifier() == II) {
1628 PrevLoc = RecFields[i]->getLocation();
1629 break;
1630 }
1631 }
1632 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001633 FD->setInvalidDecl();
1634 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 continue;
1636 }
1637 ++NumNamedMembers;
1638 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 }
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001642 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001643 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001644 Consumer.HandleTagDeclDefinition(Record);
1645 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001646 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1647 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1648 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1649 else if (ObjCImplementationDecl *IMPDecl =
1650 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001651 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1652 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001653 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001654 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001655 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001656}
1657
Steve Naroff08d92e42007-09-15 18:49:24 +00001658Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 DeclTy *lastEnumConst,
1660 SourceLocation IdLoc, IdentifierInfo *Id,
1661 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001662 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 EnumConstantDecl *LastEnumConst =
1664 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1665 Expr *Val = static_cast<Expr*>(val);
1666
Chris Lattner31e05722007-08-26 06:24:45 +00001667 // The scope passed in may not be a decl scope. Zip up the scope tree until
1668 // we find one that is.
1669 while ((S->getFlags() & Scope::DeclScope) == 0)
1670 S = S->getParent();
1671
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 // Verify that there isn't already something declared with this name in this
1673 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001674 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 if (S->isDeclScope(PrevDecl)) {
1676 if (isa<EnumConstantDecl>(PrevDecl))
1677 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1678 else
1679 Diag(IdLoc, diag::err_redefinition, Id->getName());
1680 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001681 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 return 0;
1683 }
1684 }
1685
1686 llvm::APSInt EnumVal(32);
1687 QualType EltTy;
1688 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001689 // Make sure to promote the operand type to int.
1690 UsualUnaryConversions(Val);
1691
Reid Spencer5f016e22007-07-11 17:01:13 +00001692 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1693 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001694 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001695 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1696 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001697 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001698 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001699 } else {
1700 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001702 }
1703
1704 if (!Val) {
1705 if (LastEnumConst) {
1706 // Assign the last value + 1.
1707 EnumVal = LastEnumConst->getInitVal();
1708 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001709
1710 // Check for overflow on increment.
1711 if (EnumVal < LastEnumConst->getInitVal())
1712 Diag(IdLoc, diag::warn_enum_value_overflow);
1713
Chris Lattnerb7416f92007-08-27 17:37:24 +00001714 EltTy = LastEnumConst->getType();
1715 } else {
1716 // First value, set to zero.
1717 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001718 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001719 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001720 }
1721
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001722 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001723 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1724 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001725 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001726
1727 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001728 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 return New;
1730}
1731
Steve Naroff08d92e42007-09-15 18:49:24 +00001732void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 DeclTy **Elements, unsigned NumElements) {
1734 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1735 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1736
Chris Lattnere37f0be2007-08-28 05:10:31 +00001737 // TODO: If the result value doesn't fit in an int, it must be a long or long
1738 // long value. ISO C does not support this, but GCC does as an extension,
1739 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001740 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001741
Chris Lattnerac609682007-08-28 06:15:15 +00001742 // Verify that all the values are okay, compute the size of the values, and
1743 // reverse the list.
1744 unsigned NumNegativeBits = 0;
1745 unsigned NumPositiveBits = 0;
1746
1747 // Keep track of whether all elements have type int.
1748 bool AllElementsInt = true;
1749
Reid Spencer5f016e22007-07-11 17:01:13 +00001750 EnumConstantDecl *EltList = 0;
1751 for (unsigned i = 0; i != NumElements; ++i) {
1752 EnumConstantDecl *ECD =
1753 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1754 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001755
1756 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001757 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001758 assert(InitVal.getBitWidth() >= IntWidth &&
1759 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001760 if (InitVal.getBitWidth() > IntWidth) {
1761 llvm::APSInt V(InitVal);
1762 V.trunc(IntWidth);
1763 V.extend(InitVal.getBitWidth());
1764 if (V != InitVal)
1765 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1766 InitVal.toString());
1767 }
Chris Lattnerac609682007-08-28 06:15:15 +00001768
1769 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001770 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001771 NumPositiveBits = std::max(NumPositiveBits,
1772 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001773 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001774 NumNegativeBits = std::max(NumNegativeBits,
1775 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001776
Chris Lattnerac609682007-08-28 06:15:15 +00001777 // Keep track of whether every enum element has type int (very commmon).
1778 if (AllElementsInt)
1779 AllElementsInt = ECD->getType() == Context.IntTy;
1780
Reid Spencer5f016e22007-07-11 17:01:13 +00001781 ECD->setNextDeclarator(EltList);
1782 EltList = ECD;
1783 }
1784
Chris Lattnerac609682007-08-28 06:15:15 +00001785 // Figure out the type that should be used for this enum.
1786 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1787 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001788 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001789
1790 if (NumNegativeBits) {
1791 // If there is a negative value, figure out the smallest integer type (of
1792 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001793 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001794 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001795 BestWidth = IntWidth;
1796 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001797 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001798
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001799 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001800 BestType = Context.LongTy;
1801 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001802 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001803
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001804 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001805 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1806 BestType = Context.LongLongTy;
1807 }
1808 }
1809 } else {
1810 // If there is no negative value, figure out which of uint, ulong, ulonglong
1811 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001812 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001813 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001814 BestWidth = IntWidth;
1815 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001816 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001817 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001818 } else {
1819 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001820 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001821 "How could an initializer get larger than ULL?");
1822 BestType = Context.UnsignedLongLongTy;
1823 }
1824 }
1825
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001826 // Loop over all of the enumerator constants, changing their types to match
1827 // the type of the enum if needed.
1828 for (unsigned i = 0; i != NumElements; ++i) {
1829 EnumConstantDecl *ECD =
1830 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1831 if (!ECD) continue; // Already issued a diagnostic.
1832
1833 // Standard C says the enumerators have int type, but we allow, as an
1834 // extension, the enumerators to be larger than int size. If each
1835 // enumerator value fits in an int, type it as an int, otherwise type it the
1836 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1837 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001838 if (ECD->getType() == Context.IntTy) {
1839 // Make sure the init value is signed.
1840 llvm::APSInt IV = ECD->getInitVal();
1841 IV.setIsSigned(true);
1842 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001843 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001844 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001845
1846 // Determine whether the value fits into an int.
1847 llvm::APSInt InitVal = ECD->getInitVal();
1848 bool FitsInInt;
1849 if (InitVal.isUnsigned() || !InitVal.isNegative())
1850 FitsInInt = InitVal.getActiveBits() < IntWidth;
1851 else
1852 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1853
1854 // If it fits into an integer type, force it. Otherwise force it to match
1855 // the enum decl type.
1856 QualType NewTy;
1857 unsigned NewWidth;
1858 bool NewSign;
1859 if (FitsInInt) {
1860 NewTy = Context.IntTy;
1861 NewWidth = IntWidth;
1862 NewSign = true;
1863 } else if (ECD->getType() == BestType) {
1864 // Already the right type!
1865 continue;
1866 } else {
1867 NewTy = BestType;
1868 NewWidth = BestWidth;
1869 NewSign = BestType->isSignedIntegerType();
1870 }
1871
1872 // Adjust the APSInt value.
1873 InitVal.extOrTrunc(NewWidth);
1874 InitVal.setIsSigned(NewSign);
1875 ECD->setInitVal(InitVal);
1876
1877 // Adjust the Expr initializer and type.
1878 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1879 ECD->setType(NewTy);
1880 }
Chris Lattnerac609682007-08-28 06:15:15 +00001881
Chris Lattnere00b18c2007-08-28 18:24:31 +00001882 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001883 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001884}
1885
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001886Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1887 ExprTy *expr) {
1888 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1889
Chris Lattner8e25d862008-03-16 00:16:02 +00001890 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001891}
1892
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001893Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001894 SourceLocation LBrace,
1895 SourceLocation RBrace,
1896 const char *Lang,
1897 unsigned StrSize,
1898 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001899 LinkageSpecDecl::LanguageIDs Language;
1900 Decl *dcl = static_cast<Decl *>(D);
1901 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1902 Language = LinkageSpecDecl::lang_c;
1903 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1904 Language = LinkageSpecDecl::lang_cxx;
1905 else {
1906 Diag(Loc, diag::err_bad_language);
1907 return 0;
1908 }
1909
1910 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001911 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001912}
1913
Chris Lattner74788ba2008-02-21 00:48:22 +00001914void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001915
Chris Lattner74788ba2008-02-21 00:48:22 +00001916 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001917 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001919 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 if (!newType.isNull()) // install the new vector type into the decl
1921 vDecl->setType(newType);
1922 }
1923 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1924 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001925 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 if (!newType.isNull()) // install the new vector type into the decl
1927 tDecl->setUnderlyingType(newType);
1928 }
Chris Lattner212839c2008-02-20 23:17:35 +00001929 break;
1930 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001931 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001932 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001933 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001934 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001935 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001936 break;
1937 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001938 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1939 QualType newType = HandleAddressSpaceTypeAttribute(
1940 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001941 Attr);
1942 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001943 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1944 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001945 Attr);
1946 // install the new addr spaced type into the decl
1947 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001948 }
Chris Lattner212839c2008-02-20 23:17:35 +00001949 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001950 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001951 HandleDeprecatedAttribute(New, Attr);
1952 break;
1953 case AttributeList::AT_visibility:
1954 HandleVisibilityAttribute(New, Attr);
1955 break;
1956 case AttributeList::AT_weak:
1957 HandleWeakAttribute(New, Attr);
1958 break;
1959 case AttributeList::AT_dllimport:
1960 HandleDLLImportAttribute(New, Attr);
1961 break;
1962 case AttributeList::AT_dllexport:
1963 HandleDLLExportAttribute(New, Attr);
1964 break;
1965 case AttributeList::AT_nothrow:
1966 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001967 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001968 case AttributeList::AT_stdcall:
1969 HandleStdCallAttribute(New, Attr);
1970 break;
1971 case AttributeList::AT_fastcall:
1972 HandleFastCallAttribute(New, Attr);
1973 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001974 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001975 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001976 break;
1977 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001978 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001979 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001980 case AttributeList::AT_annotate:
1981 HandleAnnotateAttribute(New, Attr);
1982 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001983 case AttributeList::AT_noreturn:
1984 HandleNoReturnAttribute(New, Attr);
1985 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001986 case AttributeList::AT_format:
1987 HandleFormatAttribute(New, Attr);
1988 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001989 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001990#if 0
1991 // TODO: when we have the full set of attributes, warn about unknown ones.
1992 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1993 Attr->getName()->getName());
1994#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001995 break;
1996 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001997}
1998
1999void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2000 AttributeList *declarator_postfix) {
2001 while (declspec_prefix) {
2002 HandleDeclAttribute(New, declspec_prefix);
2003 declspec_prefix = declspec_prefix->getNext();
2004 }
2005 while (declarator_postfix) {
2006 HandleDeclAttribute(New, declarator_postfix);
2007 declarator_postfix = declarator_postfix->getNext();
2008 }
2009}
2010
Steve Naroffbea0b342007-07-29 16:33:31 +00002011void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2012 AttributeList *rawAttr) {
2013 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002014 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002015 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002016 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002017 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002018 return;
Steve Naroff73322922007-07-18 18:00:27 +00002019 }
2020 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2021 llvm::APSInt vecSize(32);
2022 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002023 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002024 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002025 return;
Steve Naroff73322922007-07-18 18:00:27 +00002026 }
2027 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2028 // in conjunction with complex types (pointers, arrays, functions, etc.).
2029 Type *canonType = curType.getCanonicalType().getTypePtr();
2030 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002031 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002032 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002033 return;
Steve Naroff73322922007-07-18 18:00:27 +00002034 }
2035 // unlike gcc's vector_size attribute, the size is specified as the
2036 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002037 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002038
2039 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002040 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002041 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002042 return;
Steve Naroff73322922007-07-18 18:00:27 +00002043 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002044 // Instantiate/Install the vector type, the number of elements is > 0.
2045 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2046 // Remember this typedef decl, we will need it later for diagnostics.
2047 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002048}
2049
Reid Spencer5f016e22007-07-11 17:01:13 +00002050QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002051 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 // check the attribute arugments.
2053 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002054 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 std::string("1"));
2056 return QualType();
2057 }
2058 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2059 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002060 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002061 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002062 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002063 return QualType();
2064 }
2065 // navigate to the base type - we need to provide for vector pointers,
2066 // vector arrays, and functions returning vectors.
2067 Type *canonType = curType.getCanonicalType().getTypePtr();
2068
Steve Naroff73322922007-07-18 18:00:27 +00002069 if (canonType->isPointerType() || canonType->isArrayType() ||
2070 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002071 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002072 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2073 do {
2074 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2075 canonType = PT->getPointeeType().getTypePtr();
2076 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2077 canonType = AT->getElementType().getTypePtr();
2078 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2079 canonType = FT->getResultType().getTypePtr();
2080 } while (canonType->isPointerType() || canonType->isArrayType() ||
2081 canonType->isFunctionType());
2082 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002083 }
2084 // the base type must be integer or float.
2085 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002086 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 curType.getCanonicalType().getAsString());
2088 return QualType();
2089 }
Chris Lattner98be4942008-03-05 18:54:05 +00002090 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002092 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002093
2094 // the vector size needs to be an integral multiple of the type size.
2095 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002096 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 sizeExpr->getSourceRange());
2098 return QualType();
2099 }
2100 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002101 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002102 sizeExpr->getSourceRange());
2103 return QualType();
2104 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002105 // Instantiate the vector type, the number of elements is > 0, and not
2106 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002107 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002108}
2109
Chris Lattner2070d802008-02-20 23:25:22 +00002110void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002111 // check the attribute arguments.
2112 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002113 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002114 std::string("0"));
2115 return;
2116 }
2117
2118 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2119 TD->addAttr(new PackedAttr);
2120 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2121 // If the alignment is less than or equal to 8 bits, the packed attribute
2122 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002123 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002124 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002125 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002126 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002127 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002128 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002129 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002130 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2131 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002132}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002133
Ted Kremenekaecb3832008-02-27 20:43:06 +00002134void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2135 // check the attribute arguments.
2136 if (rawAttr->getNumArgs() != 0) {
2137 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2138 std::string("0"));
2139 return;
2140 }
2141
Ted Kremenek3465fb32008-03-03 16:52:27 +00002142 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2143
2144 if (!Fn) {
2145 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2146 "noreturn", "function");
2147 return;
2148 }
2149
Ted Kremenekaecb3832008-02-27 20:43:06 +00002150 d->addAttr(new NoReturnAttr());
2151}
2152
Chris Lattnerddee4232008-03-03 03:28:21 +00002153void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2154 // check the attribute arguments.
2155 if (rawAttr->getNumArgs() != 0) {
2156 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2157 std::string("0"));
2158 return;
2159 }
2160
2161 d->addAttr(new DeprecatedAttr());
2162}
2163
2164void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2165 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002166 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002167 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2168 std::string("1"));
2169 return;
2170 }
2171
Chris Lattner7b937ae2008-03-04 18:08:48 +00002172 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2173 Arg = Arg->IgnoreParenCasts();
2174 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2175
2176 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002177 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002178 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002179 return;
2180 }
2181
Chris Lattner7b937ae2008-03-04 18:08:48 +00002182 const char *TypeStr = Str->getStrData();
2183 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002184 llvm::GlobalValue::VisibilityTypes type;
2185
Chris Lattner7b937ae2008-03-04 18:08:48 +00002186 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002187 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002188 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002189 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002190 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002191 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002192 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002193 type = llvm::GlobalValue::ProtectedVisibility;
2194 else {
2195 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002196 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002197 return;
2198 }
2199
2200 d->addAttr(new VisibilityAttr(type));
2201}
2202
2203void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2204 // check the attribute arguments.
2205 if (rawAttr->getNumArgs() != 0) {
2206 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2207 std::string("0"));
2208 return;
2209 }
2210
2211 d->addAttr(new WeakAttr());
2212}
2213
2214void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2215 // check the attribute arguments.
2216 if (rawAttr->getNumArgs() != 0) {
2217 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2218 std::string("0"));
2219 return;
2220 }
2221
2222 d->addAttr(new DLLImportAttr());
2223}
2224
2225void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2226 // check the attribute arguments.
2227 if (rawAttr->getNumArgs() != 0) {
2228 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2229 std::string("0"));
2230 return;
2231 }
2232
2233 d->addAttr(new DLLExportAttr());
2234}
2235
Nate Begeman440b4562008-03-07 20:04:22 +00002236void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2237 // check the attribute arguments.
2238 if (rawAttr->getNumArgs() != 0) {
2239 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2240 std::string("0"));
2241 return;
2242 }
2243
2244 d->addAttr(new StdCallAttr());
2245}
2246
2247void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2248 // check the attribute arguments.
2249 if (rawAttr->getNumArgs() != 0) {
2250 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2251 std::string("0"));
2252 return;
2253 }
2254
2255 d->addAttr(new FastCallAttr());
2256}
2257
Chris Lattnerddee4232008-03-03 03:28:21 +00002258void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2259 // check the attribute arguments.
2260 if (rawAttr->getNumArgs() != 0) {
2261 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2262 std::string("0"));
2263 return;
2264 }
2265
2266 d->addAttr(new NoThrowAttr());
2267}
2268
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002269static const FunctionTypeProto *getFunctionProto(Decl *d) {
2270 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2271 if (!decl) return 0;
2272
2273 QualType Ty = decl->getType();
2274
2275 if (Ty->isFunctionPointerType()) {
2276 const PointerType *PtrTy = Ty->getAsPointerType();
2277 Ty = PtrTy->getPointeeType();
2278 }
2279
2280 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2281 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2282
2283 return 0;
2284}
2285
2286
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002287/// Handle __attribute__((format(type,idx,firstarg))) attributes
2288/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002289void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2290
2291 if (!rawAttr->getParameterName()) {
2292 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2293 "format", std::string("1"));
2294 return;
2295 }
2296
2297 if (rawAttr->getNumArgs() != 2) {
2298 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2299 std::string("3"));
2300 return;
2301 }
2302
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002303 // GCC ignores the format attribute on K&R style function
2304 // prototypes, so we ignore it as well
2305 const FunctionTypeProto *proto = getFunctionProto(d);
2306
2307 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002308 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2309 "format", "function");
2310 return;
2311 }
2312
2313 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002314 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002315 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002316 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002317 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002318
2319 const char *Format = rawAttr->getParameterName()->getName();
2320 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2321
2322 // Normalize the argument, __foo__ becomes foo.
2323 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2324 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2325 Format += 2;
2326 FormatLen -= 4;
2327 }
2328
2329 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2330 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2331 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2332 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2333 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2334 "format", rawAttr->getParameterName()->getName());
2335 return;
2336 }
2337
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002338 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002339 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002340 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002341 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2342 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2343 "format", std::string("2"), IdxExpr->getSourceRange());
2344 return;
2345 }
2346
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002347 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002348 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2349 "format", std::string("2"), IdxExpr->getSourceRange());
2350 return;
2351 }
2352
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002353 // make sure the format string is really a string
2354 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2355 if (!Ty->isPointerType() ||
2356 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2357 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2358 IdxExpr->getSourceRange());
2359 return;
2360 }
2361
2362
2363 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002364 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002365 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002366 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2367 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2368 "format", std::string("3"), FirstArgExpr->getSourceRange());
2369 return;
2370 }
2371
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002372 // check if the function is variadic if the 3rd argument non-zero
2373 if (FirstArg != 0) {
2374 if (proto->isVariadic()) {
2375 ++NumArgs; // +1 for ...
2376 } else {
2377 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2378 return;
2379 }
2380 }
2381
2382 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2383 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002384 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002385 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002386 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2387 FirstArgExpr->getSourceRange());
2388 return;
2389 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002390 // if 0 it disables parameter checking (to use with e.g. va_list)
2391 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002392 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2393 "format", std::string("3"), FirstArgExpr->getSourceRange());
2394 return;
2395 }
2396
2397 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2398 Idx.getZExtValue(), FirstArg.getZExtValue()));
2399}
2400
Nate Begemanc398f0b2008-02-21 19:30:49 +00002401void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2402 // check the attribute arguments.
2403 if (rawAttr->getNumArgs() != 1) {
2404 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2405 std::string("1"));
2406 return;
2407 }
2408 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2409 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002410
Nate Begemanc398f0b2008-02-21 19:30:49 +00002411 // Make sure that there is a string literal as the annotation's single
2412 // argument.
2413 if (!SE) {
2414 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2415 return;
2416 }
2417 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2418 SE->getByteLength())));
2419}
2420
Anders Carlsson78aaae92007-12-19 07:19:40 +00002421void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2422{
2423 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002424 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002425 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002426 std::string("1"));
2427 return;
2428 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002429
Anders Carlsson042c4e72008-02-16 19:51:27 +00002430 unsigned Align = 0;
2431
2432 if (rawAttr->getNumArgs() == 0) {
2433 // FIXME: This should be the target specific maximum alignment.
2434 // (For now we just use 128 bits which is the maximum on X86.
2435 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002436 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002437 } else {
2438 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2439 llvm::APSInt alignment(32);
2440 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002441 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002442 "aligned", alignmentExpr->getSourceRange());
2443 return;
2444 }
2445
2446 Align = alignment.getZExtValue() * 8;
2447 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002448
Anders Carlsson042c4e72008-02-16 19:51:27 +00002449 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002450}