blob: 7a86a8e7d3d24c45abf91fad4eef5bc593175596 [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
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000040 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattnerb048c982008-04-06 04:47:34 +000043void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattner0ed844b2008-04-04 06:12:32 +000044 assert(CD->getParent() == CurContext &&
Chris Lattnerb048c982008-04-06 04:47:34 +000045 "The next DeclContext should be directly contained in the current one.");
Chris Lattner0ed844b2008-04-04 06:12:32 +000046 CurContext = CD;
47}
48
Chris Lattnerb048c982008-04-06 04:47:34 +000049void Sema::PopDeclContext() {
50 assert(CurContext && "DeclContext imbalance!");
Chris Lattner0ed844b2008-04-04 06:12:32 +000051 CurContext = CurContext->getParent();
52}
53
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000054/// Add this decl to the scope shadowed decl chains.
55void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
56 IdResolver.AddDecl(D, S);
57 S->AddDecl(D);
58}
59
Steve Naroffb216c882007-10-09 22:01:59 +000060void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000061 if (S->decl_empty()) return;
62 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
65 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000066 Decl *TmpD = static_cast<Decl*>(*I);
67 assert(TmpD && "This decl didn't get pushed??");
68 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
69 assert(D && "This decl isn't a ScopedDecl?");
70
Reid Spencer5f016e22007-07-11 17:01:13 +000071 IdentifierInfo *II = D->getIdentifier();
72 if (!II) continue;
73
Chris Lattner7f925cc2008-04-11 07:00:53 +000074 // Unlink this decl from the identifier.
75 IdResolver.RemoveDecl(D);
76
Reid Spencer5f016e22007-07-11 17:01:13 +000077 // This will have to be revisited for C++: there we want to nest stuff in
78 // namespace decls etc. Even for C, we might want a top-level translation
79 // unit decl or something.
80 if (!CurFunctionDecl)
81 continue;
82
83 // Chain this decl to the containing function, it now owns the memory for
84 // the decl.
85 D->setNext(CurFunctionDecl->getDeclChain());
86 CurFunctionDecl->setDeclChain(D);
87 }
88}
89
Steve Naroffe8043c32008-04-01 23:04:06 +000090/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
91/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000092ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000093 // The third "scope" argument is 0 since we aren't enabling lazy built-in
94 // creation from this context.
95 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000096
Steve Naroffb327ce02008-04-02 14:35:35 +000097 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000098}
99
Steve Naroffe8043c32008-04-01 23:04:06 +0000100/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000101/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000102Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
103 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (II == 0) return 0;
105 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 // Scan up the scope chain looking for a decl that matches this identifier
108 // that is in the appropriate namespace. This search should not take long, as
109 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000110 NamedDecl *ND = IdResolver.Lookup(II, NS);
111 if (ND) return ND;
112
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 // If we didn't find a use of this identifier, and if the identifier
114 // corresponds to a compiler builtin, create the decl object for the builtin
115 // now, injecting it into translation unit scope, and return it.
116 if (NS == Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000117 if (enableLazyBuiltinCreation) {
118 // If this is a builtin on this (or all) targets, create the decl.
119 if (unsigned BuiltinID = II->getBuiltinID())
120 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
121 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000122 if (getLangOptions().ObjC1) {
123 // @interface and @compatibility_alias introduce typedef-like names.
124 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000125 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000126 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000127 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
128 if (IDI != ObjCInterfaceDecls.end())
129 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000130 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
131 if (I != ObjCAliasDecls.end())
132 return I->second->getClassInterface();
133 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 }
135 return 0;
136}
137
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000138void Sema::InitBuiltinVaListType()
139{
140 if (!Context.getBuiltinVaListType().isNull())
141 return;
142
143 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000144 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000145 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000146 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
147}
148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
150/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000151ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
152 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 Builtin::ID BID = (Builtin::ID)bid;
154
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000155 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000156 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000157 BID == Builtin::BI__builtin_va_end)
158 InitBuiltinVaListType();
159
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000160 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000161 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
162 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000163 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000164
Chris Lattner7f925cc2008-04-11 07:00:53 +0000165 // TUScope is the translation-unit scope to insert this function into.
166 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000167
168 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000169 IdResolver.AddGlobalDecl(New);
170
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 return New;
172}
173
174/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
175/// and scope as a previous declaration 'Old'. Figure out how to resolve this
176/// situation, merging decls or emitting diagnostics as appropriate.
177///
Steve Naroffe8043c32008-04-01 23:04:06 +0000178TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // Verify the old decl was also a typedef.
180 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
181 if (!Old) {
182 Diag(New->getLocation(), diag::err_redefinition_different_kind,
183 New->getName());
184 Diag(OldD->getLocation(), diag::err_previous_definition);
185 return New;
186 }
187
Steve Naroff8ee529b2007-10-31 18:42:27 +0000188 // Allow multiple definitions for ObjC built-in typedefs.
189 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000191 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000192
193 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
194 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
195 // *either* declaration is in a system header. The code below implements
196 // this adhoc compatibility rule. FIXME: The following code will not
197 // work properly when compiling ".i" files (containing preprocessed output).
198 SourceManager &SrcMgr = Context.getSourceManager();
199 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
200 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
201 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
202 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
203 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
204
Steve Naroffc5e2f342008-03-26 21:27:00 +0000205 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
206 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
207 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000208 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000209 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000210
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
212 // TODO: This is totally simplistic. It should handle merging functions
213 // together etc, merging extern int X; int X; ...
214 Diag(New->getLocation(), diag::err_redefinition, New->getName());
215 Diag(Old->getLocation(), diag::err_previous_definition);
216 return New;
217}
218
Chris Lattnerddee4232008-03-03 03:28:21 +0000219/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
220static bool DeclHasAttr(const Decl *decl, const Attr *target) {
221 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
222 if (attr->getKind() == target->getKind())
223 return true;
224
225 return false;
226}
227
228/// MergeAttributes - append attributes from the Old decl to the New one.
229static void MergeAttributes(Decl *New, Decl *Old) {
230 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
231
232// FIXME: fix this code to cleanup the Old attrs correctly
233 while (attr) {
234 tmp = attr;
235 attr = attr->getNext();
236
237 if (!DeclHasAttr(New, tmp)) {
238 New->addAttr(tmp);
239 } else {
240 tmp->setNext(0);
241 delete(tmp);
242 }
243 }
244}
245
Chris Lattner04421082008-04-08 04:40:51 +0000246/// MergeFunctionDecl - We just parsed a function 'New' from
247/// declarator D which has the same name and scope as a previous
248/// declaration 'Old'. Figure out how to resolve this situation,
249/// merging decls or emitting diagnostics as appropriate.
Reid Spencer5f016e22007-07-11 17:01:13 +0000250///
Steve Naroffe8043c32008-04-01 23:04:06 +0000251FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 // Verify the old decl was also a function.
253 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
254 if (!Old) {
255 Diag(New->getLocation(), diag::err_redefinition_different_kind,
256 New->getName());
257 Diag(OldD->getLocation(), diag::err_previous_definition);
258 return New;
259 }
Chris Lattner04421082008-04-08 04:40:51 +0000260
Chris Lattnerddee4232008-03-03 03:28:21 +0000261 MergeAttributes(New, Old);
262
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000263 QualType OldQType = Context.getCanonicalType(Old->getType());
264 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000265
Chris Lattner04421082008-04-08 04:40:51 +0000266 // C++ [dcl.fct]p3:
267 // All declarations for a function shall agree exactly in both the
268 // return type and the parameter-type-list.
269 if (getLangOptions().CPlusPlus && OldQType == NewQType)
270 return MergeCXXFunctionDecl(New, Old);
271
272 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000273 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000274 if (!getLangOptions().CPlusPlus &&
275 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000276 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000277 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000278
Steve Naroff837618c2008-01-16 15:01:34 +0000279 // A function that has already been declared has been redeclared or defined
280 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000281 diag::kind PrevDiag;
282 if (Old->getBody())
283 PrevDiag = diag::err_previous_definition;
284 else if (Old->isImplicit())
285 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000286 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000287 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
290 // TODO: This is totally simplistic. It should handle merging functions
291 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000292 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
293 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000294 return New;
295}
296
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000297/// equivalentArrayTypes - Used to determine whether two array types are
298/// equivalent.
299/// We need to check this explicitly as an incomplete array definition is
300/// considered a VariableArrayType, so will not match a complete array
301/// definition that would be otherwise equivalent.
302static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
303 const ArrayType *NewAT = NewQType->getAsArrayType();
304 const ArrayType *OldAT = OldQType->getAsArrayType();
305
306 if (!NewAT || !OldAT)
307 return false;
308
309 // If either (or both) array types in incomplete we need to strip off the
310 // outer VariableArrayType. Once the outer VAT is removed the remaining
311 // types must be identical if the array types are to be considered
312 // equivalent.
313 // eg. int[][1] and int[1][1] become
314 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
315 // removing the outermost VAT gives
316 // CAT(1, int) and CAT(1, int)
317 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000318 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000319 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
320 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000321 NewQType = NewAT->getElementType().getCanonicalType();
322 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000323 }
324
325 return NewQType == OldQType;
326}
327
Reid Spencer5f016e22007-07-11 17:01:13 +0000328/// MergeVarDecl - We just parsed a variable 'New' which has the same name
329/// and scope as a previous declaration 'Old'. Figure out how to resolve this
330/// situation, merging decls or emitting diagnostics as appropriate.
331///
332/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
333/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
334///
Steve Naroffe8043c32008-04-01 23:04:06 +0000335VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 // Verify the old decl was also a variable.
337 VarDecl *Old = dyn_cast<VarDecl>(OldD);
338 if (!Old) {
339 Diag(New->getLocation(), diag::err_redefinition_different_kind,
340 New->getName());
341 Diag(OldD->getLocation(), diag::err_previous_definition);
342 return New;
343 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000344
345 MergeAttributes(New, Old);
346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000348 QualType OldCType = Context.getCanonicalType(Old->getType());
349 QualType NewCType = Context.getCanonicalType(New->getType());
350 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 Diag(New->getLocation(), diag::err_redefinition, New->getName());
352 Diag(Old->getLocation(), diag::err_previous_definition);
353 return New;
354 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000355 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
356 if (New->getStorageClass() == VarDecl::Static &&
357 (Old->getStorageClass() == VarDecl::None ||
358 Old->getStorageClass() == VarDecl::Extern)) {
359 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
360 Diag(Old->getLocation(), diag::err_previous_definition);
361 return New;
362 }
363 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
364 if (New->getStorageClass() != VarDecl::Static &&
365 Old->getStorageClass() == VarDecl::Static) {
366 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
367 Diag(Old->getLocation(), diag::err_previous_definition);
368 return New;
369 }
370 // We've verified the types match, now handle "tentative" definitions.
371 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
372 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
373
374 if (OldFSDecl && NewFSDecl) {
375 // Handle C "tentative" external object definitions (C99 6.9.2).
376 bool OldIsTentative = false;
377 bool NewIsTentative = false;
378
379 if (!OldFSDecl->getInit() &&
380 (OldFSDecl->getStorageClass() == VarDecl::None ||
381 OldFSDecl->getStorageClass() == VarDecl::Static))
382 OldIsTentative = true;
383
384 // FIXME: this check doesn't work (since the initializer hasn't been
385 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
386 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
387 // thrown out the old decl.
388 if (!NewFSDecl->getInit() &&
389 (NewFSDecl->getStorageClass() == VarDecl::None ||
390 NewFSDecl->getStorageClass() == VarDecl::Static))
391 ; // change to NewIsTentative = true; once the code is moved.
392
393 if (NewIsTentative || OldIsTentative)
394 return New;
395 }
396 if (Old->getStorageClass() != VarDecl::Extern &&
397 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000398 Diag(New->getLocation(), diag::err_redefinition, New->getName());
399 Diag(Old->getLocation(), diag::err_previous_definition);
400 }
401 return New;
402}
403
Chris Lattner04421082008-04-08 04:40:51 +0000404/// CheckParmsForFunctionDef - Check that the parameters of the given
405/// function are appropriate for the definition of a function. This
406/// takes care of any checks that cannot be performed on the
407/// declaration itself, e.g., that the types of each of the function
408/// parameters are complete.
409bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
410 bool HasInvalidParm = false;
411 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
412 ParmVarDecl *Param = FD->getParamDecl(p);
413
414 // C99 6.7.5.3p4: the parameters in a parameter type list in a
415 // function declarator that is part of a function definition of
416 // that function shall not have incomplete type.
417 if (Param->getType()->isIncompleteType() &&
418 !Param->isInvalidDecl()) {
419 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
420 Param->getType().getAsString());
421 Param->setInvalidDecl();
422 HasInvalidParm = true;
423 }
424 }
425
426 return HasInvalidParm;
427}
428
429/// CreateImplicitParameter - Creates an implicit function parameter
430/// in the scope S and with the given type. This routine is used, for
431/// example, to create the implicit "self" parameter in an Objective-C
432/// method.
433ParmVarDecl *
434Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
435 SourceLocation IdLoc, QualType Type) {
436 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
437 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000438 if (Id)
439 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000440
441 return New;
442}
443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
445/// no declarator (e.g. "struct foo;") is parsed.
446Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
447 // TODO: emit error on 'int;' or 'const enum foo;'.
448 // TODO: emit error on 'typedef int;'
449 // if (!DS.isMissingDeclaratorOk()) Diag(...);
450
Steve Naroff92199282007-11-17 21:37:36 +0000451 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000452}
453
Steve Naroffd0091aa2008-01-10 22:15:12 +0000454bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000455 // Get the type before calling CheckSingleAssignmentConstraints(), since
456 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000457 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000458
Chris Lattner5cf216b2008-01-04 18:04:52 +0000459 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
460 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
461 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000462}
463
Steve Naroff9e8925e2007-09-04 14:36:54 +0000464bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000465 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000466 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000467 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000468 return true; // types weren't compatible.
469
Steve Naroff9e8925e2007-09-04 14:36:54 +0000470 if (savExpr != expr) // The type was promoted, update initializer list.
471 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000472 return false;
473}
474
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000475bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000476 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000477 // C99 6.7.8p14. We have an array of character type with unknown size
478 // being initialized to a string literal.
479 llvm::APSInt ConstVal(32);
480 ConstVal = strLiteral->getByteLength() + 1;
481 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000482 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000483 ArrayType::Normal, 0);
484 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
485 // C99 6.7.8p14. We have an array of character type with known size.
486 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
487 Diag(strLiteral->getSourceRange().getBegin(),
488 diag::warn_initializer_string_for_char_array_too_long,
489 strLiteral->getSourceRange());
490 } else {
491 assert(0 && "HandleStringLiteralInit(): Invalid array type");
492 }
493 // Set type from "char *" to "constant array of char".
494 strLiteral->setType(DeclT);
495 // For now, we always return false (meaning success).
496 return false;
497}
498
499StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000500 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000501 if (AT && AT->getElementType()->isCharType()) {
502 return dyn_cast<StringLiteral>(Init);
503 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000504 return 0;
505}
506
Steve Naroffa9960332008-01-25 00:51:06 +0000507// CheckInitializerListTypes - Checks the types of elements of an initializer
508// list. This function is recursive: it calls itself to initialize subelements
509// of aggregate types. Note that the topLevel parameter essentially refers to
510// whether this expression "owns" the initializer list passed in, or if this
511// initialization is taking elements out of a parent initializer. Each
512// call to this function adds zero or more to startIndex, reports any errors,
513// and returns true if it found any inconsistent types.
514bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
515 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000516 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000517
518 if (DeclType->isScalarType()) {
519 // The simplest case: initializing a single scalar
520 if (topLevel) {
521 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
522 IList->getSourceRange());
523 }
524 if (startIndex < IList->getNumInits()) {
525 Expr* expr = IList->getInit(startIndex);
526 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
527 // FIXME: Should an error be reported here instead?
528 unsigned newIndex = 0;
529 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
530 } else {
531 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
532 }
533 ++startIndex;
534 }
535 // FIXME: Should an error be reported for empty initializer list + scalar?
536 } else if (DeclType->isVectorType()) {
537 if (startIndex < IList->getNumInits()) {
538 const VectorType *VT = DeclType->getAsVectorType();
539 int maxElements = VT->getNumElements();
540 QualType elementType = VT->getElementType();
541
542 for (int i = 0; i < maxElements; ++i) {
543 // Don't attempt to go past the end of the init list
544 if (startIndex >= IList->getNumInits())
545 break;
546 Expr* expr = IList->getInit(startIndex);
547 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
548 unsigned newIndex = 0;
549 hadError |= CheckInitializerListTypes(SubInitList, elementType,
550 true, newIndex);
551 ++startIndex;
552 } else {
553 hadError |= CheckInitializerListTypes(IList, elementType,
554 false, startIndex);
555 }
556 }
557 }
558 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
559 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000560 if (startIndex < IList->getNumInits() && !topLevel &&
561 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
562 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000563 // We found a compatible struct; per the standard, this initializes the
564 // struct. (The C standard technically says that this only applies for
565 // initializers for declarations with automatic scope; however, this
566 // construct is unambiguous anyway because a struct cannot contain
567 // a type compatible with itself. We'll output an error when we check
568 // if the initializer is constant.)
569 // FIXME: Is a call to CheckSingleInitializer required here?
570 ++startIndex;
571 } else {
572 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000573
Steve Naroff406db932008-02-11 21:52:37 +0000574 // If the record is invalid, some of it's members are invalid. To avoid
575 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000576 if (structDecl->isInvalidDecl())
577 return true;
578
Steve Naroffa9960332008-01-25 00:51:06 +0000579 // If structDecl is a forward declaration, this loop won't do anything;
580 // That's okay, because an error should get printed out elsewhere. It
581 // might be worthwhile to skip over the rest of the initializer, though.
582 int numMembers = structDecl->getNumMembers() -
583 structDecl->hasFlexibleArrayMember();
584 for (int i = 0; i < numMembers; i++) {
585 // Don't attempt to go past the end of the init list
586 if (startIndex >= IList->getNumInits())
587 break;
588 FieldDecl * curField = structDecl->getMember(i);
589 if (!curField->getIdentifier()) {
590 // Don't initialize unnamed fields, e.g. "int : 20;"
591 continue;
592 }
593 QualType fieldType = curField->getType();
594 Expr* expr = IList->getInit(startIndex);
595 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
596 unsigned newStart = 0;
597 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
598 true, newStart);
599 ++startIndex;
600 } else {
601 hadError |= CheckInitializerListTypes(IList, fieldType,
602 false, startIndex);
603 }
604 if (DeclType->isUnionType())
605 break;
606 }
607 // FIXME: Implement flexible array initialization GCC extension (it's a
608 // really messy extension to implement, unfortunately...the necessary
609 // information isn't actually even here!)
610 }
611 } else if (DeclType->isArrayType()) {
612 // Check for the special-case of initializing an array with a string.
613 if (startIndex < IList->getNumInits()) {
614 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
615 DeclType)) {
616 CheckStringLiteralInit(lit, DeclType);
617 ++startIndex;
618 if (topLevel && startIndex < IList->getNumInits()) {
619 // We have leftover initializers; warn
620 Diag(IList->getInit(startIndex)->getLocStart(),
621 diag::err_excess_initializers_in_char_array_initializer,
622 IList->getInit(startIndex)->getSourceRange());
623 }
624 return false;
625 }
626 }
627 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000628 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000629 // FIXME: use a proper constant
630 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000631 } else if (const VariableArrayType *VAT =
632 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000633 // Check for VLAs; in standard C it would be possible to check this
634 // earlier, but I don't know where clang accepts VLAs (gcc accepts
635 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000636 Diag(VAT->getSizeExpr()->getLocStart(),
637 diag::err_variable_object_no_init,
638 VAT->getSizeExpr()->getSourceRange());
639 hadError = true;
640 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000641 } else {
642 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
643 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
644 }
645 QualType elementType = DeclType->getAsArrayType()->getElementType();
646 int numElements = 0;
647 for (int i = 0; i < maxElements; ++i, ++numElements) {
648 // Don't attempt to go past the end of the init list
649 if (startIndex >= IList->getNumInits())
650 break;
651 Expr* expr = IList->getInit(startIndex);
652 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
653 unsigned newIndex = 0;
654 hadError |= CheckInitializerListTypes(SubInitList, elementType,
655 true, newIndex);
656 ++startIndex;
657 } else {
658 hadError |= CheckInitializerListTypes(IList, elementType,
659 false, startIndex);
660 }
661 }
Eli Friedman9db13972008-02-15 12:53:51 +0000662 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000663 // If this is an incomplete array type, the actual type needs to
664 // be calculated here
665 if (numElements == 0) {
666 // Sizing an array implicitly to zero is not allowed
667 // (It could in theory be allowed, but it doesn't really matter.)
668 Diag(IList->getLocStart(),
669 diag::err_at_least_one_initializer_needed_to_size_array);
670 hadError = true;
671 } else {
672 llvm::APSInt ConstVal(32);
673 ConstVal = numElements;
674 DeclType = Context.getConstantArrayType(elementType, ConstVal,
675 ArrayType::Normal, 0);
676 }
677 }
678 } else {
679 assert(0 && "Aggregate that isn't a function or array?!");
680 }
681 } else {
682 // In C, all types are either scalars or aggregates, but
683 // additional handling is needed here for C++ (and possibly others?).
684 assert(0 && "Unsupported initializer type");
685 }
686
687 // If this init list is a base list, we set the type; an initializer doesn't
688 // fundamentally have a type, but this makes the ASTs a bit easier to read
689 if (topLevel)
690 IList->setType(DeclType);
691
692 if (topLevel && startIndex < IList->getNumInits()) {
693 // We have leftover initializers; warn
694 Diag(IList->getInit(startIndex)->getLocStart(),
695 diag::warn_excess_initializers,
696 IList->getInit(startIndex)->getSourceRange());
697 }
698 return hadError;
699}
700
701bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000702 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
703 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000704 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000705 return Diag(VAT->getSizeExpr()->getLocStart(),
706 diag::err_variable_object_no_init,
707 VAT->getSizeExpr()->getSourceRange());
708
Steve Naroff2fdc3742007-12-10 22:44:33 +0000709 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
710 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000711 // FIXME: Handle wide strings
712 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
713 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000714
715 if (DeclType->isArrayType())
716 return Diag(Init->getLocStart(),
717 diag::err_array_init_list_required,
718 Init->getSourceRange());
719
Steve Naroffd0091aa2008-01-10 22:15:12 +0000720 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000721 }
Steve Naroffa9960332008-01-25 00:51:06 +0000722 unsigned newIndex = 0;
723 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000724}
725
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000726Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000727Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000728 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 IdentifierInfo *II = D.getIdentifier();
730
Chris Lattnere80a59c2007-07-25 00:24:17 +0000731 // All of these full declarators require an identifier. If it doesn't have
732 // one, the ParsedFreeStandingDeclSpec action should be used.
733 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000734 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000735 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000736 D.getDeclSpec().getSourceRange(), D.getSourceRange());
737 return 0;
738 }
739
Chris Lattner31e05722007-08-26 06:24:45 +0000740 // The scope passed in may not be a decl scope. Zip up the scope tree until
741 // we find one that is.
742 while ((S->getFlags() & Scope::DeclScope) == 0)
743 S = S->getParent();
744
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000746 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000747 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000748 bool InvalidDecl = false;
749
Chris Lattner41af0932007-11-14 06:34:38 +0000750 QualType R = GetTypeForDeclarator(D, S);
751 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
752
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000754 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 if (!NewTD) return 0;
756
757 // Handle attributes prior to checking for duplicates in MergeVarDecl
758 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
759 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000760 // Merge the decl with the existing one if appropriate. If the decl is
761 // in an outer scope, it isn't the same thing.
762 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
764 if (NewTD == 0) return 0;
765 }
766 New = NewTD;
767 if (S->getParent() == 0) {
768 // C99 6.7.7p2: If a typedef name specifies a variably modified type
769 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000770 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
771 // FIXME: Diagnostic needs to be fixed.
772 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000773 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 }
775 }
Chris Lattner41af0932007-11-14 06:34:38 +0000776 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000777 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 switch (D.getDeclSpec().getStorageClassSpec()) {
779 default: assert(0 && "Unknown storage class!");
780 case DeclSpec::SCS_auto:
781 case DeclSpec::SCS_register:
782 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
783 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000784 InvalidDecl = true;
785 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
787 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
788 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000789 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000790 }
791
Chris Lattnera98e58d2008-03-15 21:24:04 +0000792 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000793 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
794 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000795 II, R, SC, isInline,
796 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000797 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000798 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
799 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000800
801 // Copy the parameter declarations from the declarator D to
802 // the function declaration NewFD, if they are available.
803 if (D.getNumTypeObjects() > 0 &&
804 D.getTypeObject(0).Fun.hasPrototype) {
805 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
806
807 // Create Decl objects for each parameter, adding them to the
808 // FunctionDecl.
809 llvm::SmallVector<ParmVarDecl*, 16> Params;
810
811 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
812 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000813 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000814 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
815 FTI.ArgInfo[0].Param &&
816 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
817 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
818 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000819 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
820
Chris Lattnerdef026a2008-04-10 02:26:16 +0000821 // In C++, the empty parameter-type-list must be spelled "void"; a
822 // typedef of void is not permitted.
823 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000824 Param->getType() != Context.VoidTy) {
825 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
826 }
827
Chris Lattner04421082008-04-08 04:40:51 +0000828 } else {
829 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
830 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
831 }
832
833 NewFD->setParams(&Params[0], Params.size());
834 }
835
Steve Naroffffce4d52008-01-09 23:34:55 +0000836 // Merge the decl with the existing one if appropriate. Since C functions
837 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 if (PrevDecl) {
839 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
840 if (NewFD == 0) return 0;
841 }
842 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000843
844 // In C++, check default arguments now that we have merged decls.
845 if (getLangOptions().CPlusPlus)
846 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000847 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000848 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000849 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
850 D.getIdentifier()->getName());
851 InvalidDecl = true;
852 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000853
854 VarDecl *NewVD;
855 VarDecl::StorageClass SC;
856 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000857 default: assert(0 && "Unknown storage class!");
858 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
859 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
860 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
861 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
862 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
863 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 }
865 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000866 // C99 6.9p2: The storage-class specifiers auto and register shall not
867 // appear in the declaration specifiers in an external declaration.
868 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
869 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
870 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000871 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000873 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
874 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000875 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000876 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000877 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
878 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000879 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000880 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 // Handle attributes prior to checking for duplicates in MergeVarDecl
882 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
883 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000884
885 // Emit an error if an address space was applied to decl with local storage.
886 // This includes arrays of objects with address space qualifiers, but not
887 // automatic variables that point to other address spaces.
888 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000889 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
890 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
891 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000892 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000893 // Merge the decl with the existing one if appropriate. If the decl is
894 // in an outer scope, it isn't the same thing.
895 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 NewVD = MergeVarDecl(NewVD, PrevDecl);
897 if (NewVD == 0) return 0;
898 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 New = NewVD;
900 }
901
902 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000903 if (II)
904 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000905 // If any semantic error occurred, mark the decl as invalid.
906 if (D.getInvalidType() || InvalidDecl)
907 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000908
909 return New;
910}
911
Steve Naroffd0091aa2008-01-10 22:15:12 +0000912bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
913 SourceLocation loc;
914 // FIXME: Remove the isReference check and handle assignment to a reference.
915 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
916 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
917 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
918 return true;
919 }
920 return false;
921}
922
Steve Naroffbb204692007-09-12 14:07:44 +0000923void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000924 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000925 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000926 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000927
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000928 // If there is no declaration, there was an error parsing it. Just ignore
929 // the initializer.
930 if (RealDecl == 0) {
931 delete Init;
932 return;
933 }
Steve Naroffbb204692007-09-12 14:07:44 +0000934
Steve Naroff410e3e22007-09-12 20:13:48 +0000935 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
936 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000937 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
938 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000939 RealDecl->setInvalidDecl();
940 return;
941 }
Steve Naroffbb204692007-09-12 14:07:44 +0000942 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000943 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000944 QualType DclT = VDecl->getType(), SavT = DclT;
945 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000946 VarDecl::StorageClass SC = BVD->getStorageClass();
947 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000948 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000949 BVD->setInvalidDecl();
950 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000951 if (CheckInitializerTypes(Init, DclT))
952 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000953 if (SC == VarDecl::Static) // C99 6.7.8p4.
954 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000955 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000956 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000957 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000958 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000959 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000960 if (CheckInitializerTypes(Init, DclT))
961 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000962
963 // C99 6.7.8p4. All file scoped initializers need to be constant.
964 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000965 }
966 // If the type changed, it means we had an incomplete type that was
967 // completed by the initializer. For example:
968 // int ary[] = { 1, 3, 5 };
969 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000970 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000971 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000972 Init->setType(DclT);
973 }
Steve Naroffbb204692007-09-12 14:07:44 +0000974
975 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000976 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000977 return;
978}
979
Reid Spencer5f016e22007-07-11 17:01:13 +0000980/// The declarators are chained together backwards, reverse the list.
981Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
982 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000983 Decl *GroupDecl = static_cast<Decl*>(group);
984 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000985 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000986
987 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
988 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000989 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000991 else { // reverse the list.
992 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000993 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000994 Group->setNextDeclarator(NewGroup);
995 NewGroup = Group;
996 Group = Next;
997 }
998 }
999 // Perform semantic analysis that depends on having fully processed both
1000 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001001 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001002 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1003 if (!IDecl)
1004 continue;
1005 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
1006 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
1007 QualType T = IDecl->getType();
1008
1009 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1010 // static storage duration, it shall not have a variable length array.
1011 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001012 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001013 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1014 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001015 }
1016 }
1017 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1018 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1019 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001020 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001021 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1022 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001023 IDecl->setInvalidDecl();
1024 }
1025 }
1026 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1027 // object that has file scope without an initializer, and without a
1028 // storage-class specifier or with the storage-class specifier "static",
1029 // constitutes a tentative definition. Note: A tentative definition with
1030 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +00001031 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
1032 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001033 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001034 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1035 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001036 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001037 // C99 6.9.2p3: If the declaration of an identifier for an object is
1038 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1039 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001040 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1041 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001042 IDecl->setInvalidDecl();
1043 }
1044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 }
1046 return NewGroup;
1047}
Steve Naroffe1223f72007-08-28 03:03:08 +00001048
Chris Lattner04421082008-04-08 04:40:51 +00001049/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1050/// to introduce parameters into function prototype scope.
1051Sema::DeclTy *
1052Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1053 DeclSpec &DS = D.getDeclSpec();
1054
1055 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1056 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1057 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1058 Diag(DS.getStorageClassSpecLoc(),
1059 diag::err_invalid_storage_class_in_func_decl);
1060 DS.ClearStorageClassSpecs();
1061 }
1062 if (DS.isThreadSpecified()) {
1063 Diag(DS.getThreadSpecLoc(),
1064 diag::err_invalid_storage_class_in_func_decl);
1065 DS.ClearStorageClassSpecs();
1066 }
1067
1068
1069 // In this context, we *do not* check D.getInvalidType(). If the declarator
1070 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1071 // though it will not reflect the user specified type.
1072 QualType parmDeclType = GetTypeForDeclarator(D, S);
1073
1074 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1075
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1077 // Can this happen for params? We already checked that they don't conflict
1078 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001079 IdentifierInfo *II = D.getIdentifier();
1080 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1081 if (S->isDeclScope(PrevDecl)) {
1082 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1083 dyn_cast<NamedDecl>(PrevDecl)->getName());
1084
1085 // Recover by removing the name
1086 II = 0;
1087 D.SetIdentifier(0, D.getIdentifierLoc());
1088 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001089 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001090
1091 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1092 // Doing the promotion here has a win and a loss. The win is the type for
1093 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1094 // code generator). The loss is the orginal type isn't preserved. For example:
1095 //
1096 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1097 // int blockvardecl[5];
1098 // sizeof(parmvardecl); // size == 4
1099 // sizeof(blockvardecl); // size == 20
1100 // }
1101 //
1102 // For expressions, all implicit conversions are captured using the
1103 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1104 //
1105 // FIXME: If a source translation tool needs to see the original type, then
1106 // we need to consider storing both types (in ParmVarDecl)...
1107 //
Chris Lattnere6327742008-04-02 05:18:44 +00001108 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001109 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001110 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001111 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001112 parmDeclType = Context.getPointerType(parmDeclType);
1113
Chris Lattner04421082008-04-08 04:40:51 +00001114 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1115 D.getIdentifierLoc(), II,
1116 parmDeclType, VarDecl::None,
1117 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001118
Chris Lattner04421082008-04-08 04:40:51 +00001119 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001120 New->setInvalidDecl();
1121
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001122 if (II)
1123 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001124
Chris Lattner04421082008-04-08 04:40:51 +00001125 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001129
Chris Lattnerb652cea2007-10-09 17:14:05 +00001130Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 assert(CurFunctionDecl == 0 && "Function parsing confused");
1132 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1133 "Not a function declarator!");
1134 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1137 // for a K&R function.
1138 if (!FTI.hasPrototype) {
1139 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001140 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1142 FTI.ArgInfo[i].Ident->getName());
1143 // Implicitly declare the argument as type 'int' for lack of a better
1144 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001145 DeclSpec DS;
1146 const char* PrevSpec; // unused
1147 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1148 PrevSpec);
1149 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1150 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1151 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 }
1153 }
Chris Lattner52804082008-02-17 19:31:09 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // Since this is a function definition, act as though we have information
1156 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001157 if (FTI.NumArgs)
1158 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001160 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 }
1162
1163 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001164
1165 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001166 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001167 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001168 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1169 if (FD->getBody()) {
1170 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1171 D.getIdentifier()->getName());
1172 Diag(FD->getLocation(), diag::err_previous_definition);
1173 }
1174 }
Steve Narofffabbc342008-02-12 01:09:36 +00001175 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001176 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001178 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001179
1180 // Check the validity of our function parameters
1181 CheckParmsForFunctionDef(FD);
1182
1183 // Introduce our parameters into the function scope
1184 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1185 ParmVarDecl *Param = FD->getParamDecl(p);
1186 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001187 if (Param->getIdentifier())
1188 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 }
Chris Lattner04421082008-04-08 04:40:51 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 return FD;
1192}
1193
Steve Naroffd6d054d2007-11-11 23:20:51 +00001194Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1195 Decl *dcl = static_cast<Decl *>(D);
1196 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1197 FD->setBody((Stmt*)Body);
1198 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001199 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001200 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001201 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001202 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001203 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001204 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001205 // Verify and clean out per-function state.
1206
1207 // Check goto/label use.
1208 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1209 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1210 // Verify that we have no forward references left. If so, there was a goto
1211 // or address of a label taken, but no definition of it. Label fwd
1212 // definitions are indicated with a null substmt.
1213 if (I->second->getSubStmt() == 0) {
1214 LabelStmt *L = I->second;
1215 // Emit error.
1216 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1217
1218 // At this point, we have gotos that use the bogus label. Stitch it into
1219 // the function body so that they aren't leaked and that the AST is well
1220 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001221 if (Body) {
1222 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1223 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1224 } else {
1225 // The whole function wasn't parsed correctly, just delete this.
1226 delete L;
1227 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001228 }
1229 }
1230 LabelMap.clear();
1231
Steve Naroffd6d054d2007-11-11 23:20:51 +00001232 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001233}
1234
Reid Spencer5f016e22007-07-11 17:01:13 +00001235/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1236/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001237ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1238 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 if (getLangOptions().C99) // Extension in C99.
1240 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1241 else // Legal in C90, but warn about it.
1242 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1243
1244 // FIXME: handle stuff like:
1245 // void foo() { extern float X(); }
1246 // void bar() { X(); } <-- implicit decl for X in another scope.
1247
1248 // Set a Declarator for the implicit definition: int foo();
1249 const char *Dummy;
1250 DeclSpec DS;
1251 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1252 Error = Error; // Silence warning.
1253 assert(!Error && "Error setting up implicit decl!");
1254 Declarator D(DS, Declarator::BlockContext);
1255 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1256 D.SetIdentifier(&II, Loc);
1257
1258 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001259 if (Scope *FnS = S->getFnParent())
1260 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 while (S->getParent())
1262 S = S->getParent();
1263
Steve Naroffe2ef8152008-04-04 14:32:09 +00001264 FunctionDecl *FD =
1265 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1266 FD->setImplicit();
1267 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001268}
1269
1270
Chris Lattner41af0932007-11-14 06:34:38 +00001271TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001272 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001274 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001275
1276 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001277 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1278 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001279 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001280 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001281 if (D.getInvalidType())
1282 NewTD->setInvalidDecl();
1283 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001284}
1285
Steve Naroff08d92e42007-09-15 18:49:24 +00001286/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001287/// former case, Name will be non-null. In the later case, Name will be null.
1288/// TagType indicates what kind of tag this is. TK indicates whether this is a
1289/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001290Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 SourceLocation KWLoc, IdentifierInfo *Name,
1292 SourceLocation NameLoc, AttributeList *Attr) {
1293 // If this is a use of an existing tag, it must have a name.
1294 assert((Name != 0 || TK == TK_Definition) &&
1295 "Nameless record must be a definition!");
1296
1297 Decl::Kind Kind;
1298 switch (TagType) {
1299 default: assert(0 && "Unknown tag type!");
1300 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1301 case DeclSpec::TST_union: Kind = Decl::Union; break;
1302//case DeclSpec::TST_class: Kind = Decl::Class; break;
1303 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1304 }
1305
1306 // If this is a named struct, check to see if there was a previous forward
1307 // declaration or definition.
1308 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001309 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001310
1311 // If this is a use of a previous tag, or if the tag is already declared in
1312 // the same scope (so that the definition/declaration completes or
1313 // rementions the tag), reuse the decl.
1314 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1315 // Make sure that this wasn't declared as an enum and now used as a struct
1316 // or something similar.
1317 if (PrevDecl->getKind() != Kind) {
1318 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1319 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1320 }
1321
1322 // If this is a use or a forward declaration, we're good.
1323 if (TK != TK_Definition)
1324 return PrevDecl;
1325
1326 // Diagnose attempts to redefine a tag.
1327 if (PrevDecl->isDefinition()) {
1328 Diag(NameLoc, diag::err_redefinition, Name->getName());
1329 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1330 // If this is a redefinition, recover by making this struct be
1331 // anonymous, which will make any later references get the previous
1332 // definition.
1333 Name = 0;
1334 } else {
1335 // Okay, this is definition of a previously declared or referenced tag.
1336 // Move the location of the decl to be the definition site.
1337 PrevDecl->setLocation(NameLoc);
1338 return PrevDecl;
1339 }
1340 }
1341 // If we get here, this is a definition of a new struct type in a nested
1342 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1343 // type.
1344 }
1345
1346 // If there is an identifier, use the location of the identifier as the
1347 // location of the decl, otherwise use the location of the struct/union
1348 // keyword.
1349 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1350
1351 // Otherwise, if this is the first time we've seen this tag, create the decl.
1352 TagDecl *New;
1353 switch (Kind) {
1354 default: assert(0 && "Unknown tag kind!");
1355 case Decl::Enum:
1356 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1357 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001358 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 // If this is an undefined enum, warn.
1360 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1361 break;
1362 case Decl::Union:
1363 case Decl::Struct:
1364 case Decl::Class:
1365 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1366 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001367 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 break;
1369 }
1370
1371 // If this has an identifier, add it to the scope stack.
1372 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001373 // The scope passed in may not be a decl scope. Zip up the scope tree until
1374 // we find one that is.
1375 while ((S->getFlags() & Scope::DeclScope) == 0)
1376 S = S->getParent();
1377
1378 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001379 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001381
Anders Carlssonad148062008-02-16 00:29:18 +00001382 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 return New;
1384}
1385
Steve Naroff08d92e42007-09-15 18:49:24 +00001386/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001387/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001388Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 SourceLocation DeclStart,
1390 Declarator &D, ExprTy *BitfieldWidth) {
1391 IdentifierInfo *II = D.getIdentifier();
1392 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 SourceLocation Loc = DeclStart;
1394 if (II) Loc = D.getIdentifierLoc();
1395
1396 // FIXME: Unnamed fields can be handled in various different ways, for
1397 // example, unnamed unions inject all members into the struct namespace!
1398
1399
1400 if (BitWidth) {
1401 // TODO: Validate.
1402 //printf("WARNING: BITFIELDS IGNORED!\n");
1403
1404 // 6.7.2.1p3
1405 // 6.7.2.1p4
1406
1407 } else {
1408 // Not a bitfield.
1409
1410 // validate II.
1411
1412 }
1413
1414 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001415 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1416 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1419 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001420 if (T->isVariablyModifiedType()) {
1421 // FIXME: This diagnostic needs work
1422 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001423 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001426 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001427
Anders Carlssonad148062008-02-16 00:29:18 +00001428 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1429 D.getAttributes());
1430
Steve Naroff5912a352007-08-28 20:14:24 +00001431 if (D.getInvalidType() || InvalidDecl)
1432 NewFD->setInvalidDecl();
1433 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001434}
1435
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001436/// TranslateIvarVisibility - Translate visibility from a token ID to an
1437/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001438static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001439TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001440 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001441 case tok::objc_private: return ObjCIvarDecl::Private;
1442 case tok::objc_public: return ObjCIvarDecl::Public;
1443 case tok::objc_protected: return ObjCIvarDecl::Protected;
1444 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001445 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001446 }
1447}
1448
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001449/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1450/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001451Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001452 SourceLocation DeclStart,
1453 Declarator &D, ExprTy *BitfieldWidth,
1454 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001455 IdentifierInfo *II = D.getIdentifier();
1456 Expr *BitWidth = (Expr*)BitfieldWidth;
1457 SourceLocation Loc = DeclStart;
1458 if (II) Loc = D.getIdentifierLoc();
1459
1460 // FIXME: Unnamed fields can be handled in various different ways, for
1461 // example, unnamed unions inject all members into the struct namespace!
1462
1463
1464 if (BitWidth) {
1465 // TODO: Validate.
1466 //printf("WARNING: BITFIELDS IGNORED!\n");
1467
1468 // 6.7.2.1p3
1469 // 6.7.2.1p4
1470
1471 } else {
1472 // Not a bitfield.
1473
1474 // validate II.
1475
1476 }
1477
1478 QualType T = GetTypeForDeclarator(D, S);
1479 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1480 bool InvalidDecl = false;
1481
1482 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1483 // than a variably modified type.
1484 if (T->isVariablyModifiedType()) {
1485 // FIXME: This diagnostic needs work
1486 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1487 InvalidDecl = true;
1488 }
1489
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001490 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001491
1492 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1493 D.getAttributes());
1494
1495 if (D.getInvalidType() || InvalidDecl)
1496 NewID->setInvalidDecl();
1497 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001498 if (Visibility != tok::objc_not_keyword)
1499 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001500 return NewID;
1501}
1502
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001503void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001504 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001505 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001506 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001507 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1508 assert(EnclosingDecl && "missing record or interface decl");
1509 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1510
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001511 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // Diagnose code like:
1513 // struct S { struct S {} X; };
1514 // We discover this when we complete the outer S. Reject and ignore the
1515 // outer S.
1516 Diag(Record->getLocation(), diag::err_nested_redefinition,
1517 Record->getKindName());
1518 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001519 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 return;
1521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001522 // Verify that all the fields are okay.
1523 unsigned NumNamedMembers = 0;
1524 llvm::SmallVector<FieldDecl*, 32> RecFields;
1525 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001526
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001528
Steve Naroff74216642007-09-14 22:20:54 +00001529 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1530 assert(FD && "missing field decl");
1531
1532 // Remember all fields.
1533 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534
1535 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001536 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001537
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001539 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001540 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001542 FD->setInvalidDecl();
1543 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 continue;
1545 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1547 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001548 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001549 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001550 FD->setInvalidDecl();
1551 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001552 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001553 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 if (i != NumFields-1 || // ... that the last member ...
1555 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001556 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001558 FD->setInvalidDecl();
1559 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 continue;
1561 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001562 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1564 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001565 FD->setInvalidDecl();
1566 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 continue;
1568 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001570 if (Record)
1571 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1574 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001575 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1577 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001578 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 Record->setHasFlexibleArrayMember(true);
1580 } else {
1581 // If this is a struct/class and this is not the last element, reject
1582 // it. Note that GCC supports variable sized arrays in the middle of
1583 // structures.
1584 if (i != NumFields-1) {
1585 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1586 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001587 FD->setInvalidDecl();
1588 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 continue;
1590 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 // We support flexible arrays at the end of structs in other structs
1592 // as an extension.
1593 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1594 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001595 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001596 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
1598 }
1599 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001600 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001601 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001602 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1603 FD->getName());
1604 FD->setInvalidDecl();
1605 EnclosingDecl->setInvalidDecl();
1606 continue;
1607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 // Keep track of the number of named members.
1609 if (IdentifierInfo *II = FD->getIdentifier()) {
1610 // Detect duplicate member names.
1611 if (!FieldIDs.insert(II)) {
1612 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1613 // Find the previous decl.
1614 SourceLocation PrevLoc;
1615 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1616 assert(i != e && "Didn't find previous def!");
1617 if (RecFields[i]->getIdentifier() == II) {
1618 PrevLoc = RecFields[i]->getLocation();
1619 break;
1620 }
1621 }
1622 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001623 FD->setInvalidDecl();
1624 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001625 continue;
1626 }
1627 ++NumNamedMembers;
1628 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001629 }
1630
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001632 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001633 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001634 Consumer.HandleTagDeclDefinition(Record);
1635 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001636 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1637 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1638 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1639 else if (ObjCImplementationDecl *IMPDecl =
1640 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001641 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1642 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001643 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001644 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001645 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001646}
1647
Steve Naroff08d92e42007-09-15 18:49:24 +00001648Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 DeclTy *lastEnumConst,
1650 SourceLocation IdLoc, IdentifierInfo *Id,
1651 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001652 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 EnumConstantDecl *LastEnumConst =
1654 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1655 Expr *Val = static_cast<Expr*>(val);
1656
Chris Lattner31e05722007-08-26 06:24:45 +00001657 // The scope passed in may not be a decl scope. Zip up the scope tree until
1658 // we find one that is.
1659 while ((S->getFlags() & Scope::DeclScope) == 0)
1660 S = S->getParent();
1661
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 // Verify that there isn't already something declared with this name in this
1663 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001664 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 if (S->isDeclScope(PrevDecl)) {
1666 if (isa<EnumConstantDecl>(PrevDecl))
1667 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1668 else
1669 Diag(IdLoc, diag::err_redefinition, Id->getName());
1670 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001671 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 return 0;
1673 }
1674 }
1675
1676 llvm::APSInt EnumVal(32);
1677 QualType EltTy;
1678 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001679 // Make sure to promote the operand type to int.
1680 UsualUnaryConversions(Val);
1681
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1683 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001684 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1686 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001687 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001688 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001689 } else {
1690 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001692 }
1693
1694 if (!Val) {
1695 if (LastEnumConst) {
1696 // Assign the last value + 1.
1697 EnumVal = LastEnumConst->getInitVal();
1698 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001699
1700 // Check for overflow on increment.
1701 if (EnumVal < LastEnumConst->getInitVal())
1702 Diag(IdLoc, diag::warn_enum_value_overflow);
1703
Chris Lattnerb7416f92007-08-27 17:37:24 +00001704 EltTy = LastEnumConst->getType();
1705 } else {
1706 // First value, set to zero.
1707 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001708 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001709 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 }
1711
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001712 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001713 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1714 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001715 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001716
1717 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001718 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001719 return New;
1720}
1721
Steve Naroff08d92e42007-09-15 18:49:24 +00001722void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 DeclTy **Elements, unsigned NumElements) {
1724 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1725 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1726
Chris Lattnere37f0be2007-08-28 05:10:31 +00001727 // TODO: If the result value doesn't fit in an int, it must be a long or long
1728 // long value. ISO C does not support this, but GCC does as an extension,
1729 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001730 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001731
Chris Lattnerac609682007-08-28 06:15:15 +00001732 // Verify that all the values are okay, compute the size of the values, and
1733 // reverse the list.
1734 unsigned NumNegativeBits = 0;
1735 unsigned NumPositiveBits = 0;
1736
1737 // Keep track of whether all elements have type int.
1738 bool AllElementsInt = true;
1739
Reid Spencer5f016e22007-07-11 17:01:13 +00001740 EnumConstantDecl *EltList = 0;
1741 for (unsigned i = 0; i != NumElements; ++i) {
1742 EnumConstantDecl *ECD =
1743 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1744 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001745
1746 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001747 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001748 assert(InitVal.getBitWidth() >= IntWidth &&
1749 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001750 if (InitVal.getBitWidth() > IntWidth) {
1751 llvm::APSInt V(InitVal);
1752 V.trunc(IntWidth);
1753 V.extend(InitVal.getBitWidth());
1754 if (V != InitVal)
1755 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1756 InitVal.toString());
1757 }
Chris Lattnerac609682007-08-28 06:15:15 +00001758
1759 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001760 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001761 NumPositiveBits = std::max(NumPositiveBits,
1762 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001763 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001764 NumNegativeBits = std::max(NumNegativeBits,
1765 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001766
Chris Lattnerac609682007-08-28 06:15:15 +00001767 // Keep track of whether every enum element has type int (very commmon).
1768 if (AllElementsInt)
1769 AllElementsInt = ECD->getType() == Context.IntTy;
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 ECD->setNextDeclarator(EltList);
1772 EltList = ECD;
1773 }
1774
Chris Lattnerac609682007-08-28 06:15:15 +00001775 // Figure out the type that should be used for this enum.
1776 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1777 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001778 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001779
1780 if (NumNegativeBits) {
1781 // If there is a negative value, figure out the smallest integer type (of
1782 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001783 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001784 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001785 BestWidth = IntWidth;
1786 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001787 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001788
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001789 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001790 BestType = Context.LongTy;
1791 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001792 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001793
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001794 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001795 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1796 BestType = Context.LongLongTy;
1797 }
1798 }
1799 } else {
1800 // If there is no negative value, figure out which of uint, ulong, ulonglong
1801 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001802 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001803 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001804 BestWidth = IntWidth;
1805 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001806 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001807 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001808 } else {
1809 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001810 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001811 "How could an initializer get larger than ULL?");
1812 BestType = Context.UnsignedLongLongTy;
1813 }
1814 }
1815
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001816 // Loop over all of the enumerator constants, changing their types to match
1817 // the type of the enum if needed.
1818 for (unsigned i = 0; i != NumElements; ++i) {
1819 EnumConstantDecl *ECD =
1820 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1821 if (!ECD) continue; // Already issued a diagnostic.
1822
1823 // Standard C says the enumerators have int type, but we allow, as an
1824 // extension, the enumerators to be larger than int size. If each
1825 // enumerator value fits in an int, type it as an int, otherwise type it the
1826 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1827 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001828 if (ECD->getType() == Context.IntTy) {
1829 // Make sure the init value is signed.
1830 llvm::APSInt IV = ECD->getInitVal();
1831 IV.setIsSigned(true);
1832 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001833 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001834 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001835
1836 // Determine whether the value fits into an int.
1837 llvm::APSInt InitVal = ECD->getInitVal();
1838 bool FitsInInt;
1839 if (InitVal.isUnsigned() || !InitVal.isNegative())
1840 FitsInInt = InitVal.getActiveBits() < IntWidth;
1841 else
1842 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1843
1844 // If it fits into an integer type, force it. Otherwise force it to match
1845 // the enum decl type.
1846 QualType NewTy;
1847 unsigned NewWidth;
1848 bool NewSign;
1849 if (FitsInInt) {
1850 NewTy = Context.IntTy;
1851 NewWidth = IntWidth;
1852 NewSign = true;
1853 } else if (ECD->getType() == BestType) {
1854 // Already the right type!
1855 continue;
1856 } else {
1857 NewTy = BestType;
1858 NewWidth = BestWidth;
1859 NewSign = BestType->isSignedIntegerType();
1860 }
1861
1862 // Adjust the APSInt value.
1863 InitVal.extOrTrunc(NewWidth);
1864 InitVal.setIsSigned(NewSign);
1865 ECD->setInitVal(InitVal);
1866
1867 // Adjust the Expr initializer and type.
1868 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1869 ECD->setType(NewTy);
1870 }
Chris Lattnerac609682007-08-28 06:15:15 +00001871
Chris Lattnere00b18c2007-08-28 18:24:31 +00001872 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001873 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001874}
1875
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001876Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1877 ExprTy *expr) {
1878 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1879
Chris Lattner8e25d862008-03-16 00:16:02 +00001880 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001881}
1882
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001883Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001884 SourceLocation LBrace,
1885 SourceLocation RBrace,
1886 const char *Lang,
1887 unsigned StrSize,
1888 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001889 LinkageSpecDecl::LanguageIDs Language;
1890 Decl *dcl = static_cast<Decl *>(D);
1891 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1892 Language = LinkageSpecDecl::lang_c;
1893 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1894 Language = LinkageSpecDecl::lang_cxx;
1895 else {
1896 Diag(Loc, diag::err_bad_language);
1897 return 0;
1898 }
1899
1900 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001901 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001902}
1903
Chris Lattner74788ba2008-02-21 00:48:22 +00001904void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001905
Chris Lattner74788ba2008-02-21 00:48:22 +00001906 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001907 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001909 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 if (!newType.isNull()) // install the new vector type into the decl
1911 vDecl->setType(newType);
1912 }
1913 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1914 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001915 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001916 if (!newType.isNull()) // install the new vector type into the decl
1917 tDecl->setUnderlyingType(newType);
1918 }
Chris Lattner212839c2008-02-20 23:17:35 +00001919 break;
1920 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001921 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001922 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001923 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001924 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001925 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001926 break;
1927 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001928 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1929 QualType newType = HandleAddressSpaceTypeAttribute(
1930 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001931 Attr);
1932 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001933 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1934 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001935 Attr);
1936 // install the new addr spaced type into the decl
1937 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001938 }
Chris Lattner212839c2008-02-20 23:17:35 +00001939 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001940 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001941 HandleDeprecatedAttribute(New, Attr);
1942 break;
1943 case AttributeList::AT_visibility:
1944 HandleVisibilityAttribute(New, Attr);
1945 break;
1946 case AttributeList::AT_weak:
1947 HandleWeakAttribute(New, Attr);
1948 break;
1949 case AttributeList::AT_dllimport:
1950 HandleDLLImportAttribute(New, Attr);
1951 break;
1952 case AttributeList::AT_dllexport:
1953 HandleDLLExportAttribute(New, Attr);
1954 break;
1955 case AttributeList::AT_nothrow:
1956 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001957 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001958 case AttributeList::AT_stdcall:
1959 HandleStdCallAttribute(New, Attr);
1960 break;
1961 case AttributeList::AT_fastcall:
1962 HandleFastCallAttribute(New, Attr);
1963 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001964 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001965 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001966 break;
1967 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001968 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001969 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001970 case AttributeList::AT_annotate:
1971 HandleAnnotateAttribute(New, Attr);
1972 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001973 case AttributeList::AT_noreturn:
1974 HandleNoReturnAttribute(New, Attr);
1975 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001976 case AttributeList::AT_format:
1977 HandleFormatAttribute(New, Attr);
1978 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001979 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001980#if 0
1981 // TODO: when we have the full set of attributes, warn about unknown ones.
1982 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1983 Attr->getName()->getName());
1984#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001985 break;
1986 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001987}
1988
1989void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1990 AttributeList *declarator_postfix) {
1991 while (declspec_prefix) {
1992 HandleDeclAttribute(New, declspec_prefix);
1993 declspec_prefix = declspec_prefix->getNext();
1994 }
1995 while (declarator_postfix) {
1996 HandleDeclAttribute(New, declarator_postfix);
1997 declarator_postfix = declarator_postfix->getNext();
1998 }
1999}
2000
Steve Naroffbea0b342007-07-29 16:33:31 +00002001void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2002 AttributeList *rawAttr) {
2003 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002004 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002005 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002006 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002007 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002008 return;
Steve Naroff73322922007-07-18 18:00:27 +00002009 }
2010 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2011 llvm::APSInt vecSize(32);
2012 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002013 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002014 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002015 return;
Steve Naroff73322922007-07-18 18:00:27 +00002016 }
2017 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2018 // in conjunction with complex types (pointers, arrays, functions, etc.).
2019 Type *canonType = curType.getCanonicalType().getTypePtr();
2020 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002021 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002022 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002023 return;
Steve Naroff73322922007-07-18 18:00:27 +00002024 }
2025 // unlike gcc's vector_size attribute, the size is specified as the
2026 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002027 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002028
2029 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002030 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002031 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002032 return;
Steve Naroff73322922007-07-18 18:00:27 +00002033 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002034 // Instantiate/Install the vector type, the number of elements is > 0.
2035 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2036 // Remember this typedef decl, we will need it later for diagnostics.
2037 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002038}
2039
Reid Spencer5f016e22007-07-11 17:01:13 +00002040QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002041 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 // check the attribute arugments.
2043 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002044 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 std::string("1"));
2046 return QualType();
2047 }
2048 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2049 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002050 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002051 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002052 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 return QualType();
2054 }
2055 // navigate to the base type - we need to provide for vector pointers,
2056 // vector arrays, and functions returning vectors.
2057 Type *canonType = curType.getCanonicalType().getTypePtr();
2058
Steve Naroff73322922007-07-18 18:00:27 +00002059 if (canonType->isPointerType() || canonType->isArrayType() ||
2060 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002061 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002062 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2063 do {
2064 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2065 canonType = PT->getPointeeType().getTypePtr();
2066 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2067 canonType = AT->getElementType().getTypePtr();
2068 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2069 canonType = FT->getResultType().getTypePtr();
2070 } while (canonType->isPointerType() || canonType->isArrayType() ||
2071 canonType->isFunctionType());
2072 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 }
2074 // the base type must be integer or float.
2075 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002076 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 curType.getCanonicalType().getAsString());
2078 return QualType();
2079 }
Chris Lattner98be4942008-03-05 18:54:05 +00002080 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002082 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002083
2084 // the vector size needs to be an integral multiple of the type size.
2085 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002086 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 sizeExpr->getSourceRange());
2088 return QualType();
2089 }
2090 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002091 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 sizeExpr->getSourceRange());
2093 return QualType();
2094 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002095 // Instantiate the vector type, the number of elements is > 0, and not
2096 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002097 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002098}
2099
Chris Lattner2070d802008-02-20 23:25:22 +00002100void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002101 // check the attribute arguments.
2102 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002103 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002104 std::string("0"));
2105 return;
2106 }
2107
2108 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2109 TD->addAttr(new PackedAttr);
2110 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2111 // If the alignment is less than or equal to 8 bits, the packed attribute
2112 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002113 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002114 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002115 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002116 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002117 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002118 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002119 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002120 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2121 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002122}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002123
Ted Kremenekaecb3832008-02-27 20:43:06 +00002124void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2125 // check the attribute arguments.
2126 if (rawAttr->getNumArgs() != 0) {
2127 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2128 std::string("0"));
2129 return;
2130 }
2131
Ted Kremenek3465fb32008-03-03 16:52:27 +00002132 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2133
2134 if (!Fn) {
2135 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2136 "noreturn", "function");
2137 return;
2138 }
2139
Ted Kremenekaecb3832008-02-27 20:43:06 +00002140 d->addAttr(new NoReturnAttr());
2141}
2142
Chris Lattnerddee4232008-03-03 03:28:21 +00002143void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2144 // check the attribute arguments.
2145 if (rawAttr->getNumArgs() != 0) {
2146 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2147 std::string("0"));
2148 return;
2149 }
2150
2151 d->addAttr(new DeprecatedAttr());
2152}
2153
2154void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2155 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002156 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002157 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2158 std::string("1"));
2159 return;
2160 }
2161
Chris Lattner7b937ae2008-03-04 18:08:48 +00002162 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2163 Arg = Arg->IgnoreParenCasts();
2164 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2165
2166 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002167 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002168 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002169 return;
2170 }
2171
Chris Lattner7b937ae2008-03-04 18:08:48 +00002172 const char *TypeStr = Str->getStrData();
2173 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002174 llvm::GlobalValue::VisibilityTypes type;
2175
Chris Lattner7b937ae2008-03-04 18:08:48 +00002176 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002177 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002178 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002179 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002180 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002181 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002182 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002183 type = llvm::GlobalValue::ProtectedVisibility;
2184 else {
2185 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002186 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002187 return;
2188 }
2189
2190 d->addAttr(new VisibilityAttr(type));
2191}
2192
2193void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2194 // check the attribute arguments.
2195 if (rawAttr->getNumArgs() != 0) {
2196 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2197 std::string("0"));
2198 return;
2199 }
2200
2201 d->addAttr(new WeakAttr());
2202}
2203
2204void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2205 // check the attribute arguments.
2206 if (rawAttr->getNumArgs() != 0) {
2207 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2208 std::string("0"));
2209 return;
2210 }
2211
2212 d->addAttr(new DLLImportAttr());
2213}
2214
2215void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2216 // check the attribute arguments.
2217 if (rawAttr->getNumArgs() != 0) {
2218 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2219 std::string("0"));
2220 return;
2221 }
2222
2223 d->addAttr(new DLLExportAttr());
2224}
2225
Nate Begeman440b4562008-03-07 20:04:22 +00002226void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2227 // check the attribute arguments.
2228 if (rawAttr->getNumArgs() != 0) {
2229 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2230 std::string("0"));
2231 return;
2232 }
2233
2234 d->addAttr(new StdCallAttr());
2235}
2236
2237void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2238 // check the attribute arguments.
2239 if (rawAttr->getNumArgs() != 0) {
2240 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2241 std::string("0"));
2242 return;
2243 }
2244
2245 d->addAttr(new FastCallAttr());
2246}
2247
Chris Lattnerddee4232008-03-03 03:28:21 +00002248void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2249 // check the attribute arguments.
2250 if (rawAttr->getNumArgs() != 0) {
2251 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2252 std::string("0"));
2253 return;
2254 }
2255
2256 d->addAttr(new NoThrowAttr());
2257}
2258
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002259static const FunctionTypeProto *getFunctionProto(Decl *d) {
2260 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2261 if (!decl) return 0;
2262
2263 QualType Ty = decl->getType();
2264
2265 if (Ty->isFunctionPointerType()) {
2266 const PointerType *PtrTy = Ty->getAsPointerType();
2267 Ty = PtrTy->getPointeeType();
2268 }
2269
2270 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2271 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2272
2273 return 0;
2274}
2275
2276
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002277/// Handle __attribute__((format(type,idx,firstarg))) attributes
2278/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002279void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2280
2281 if (!rawAttr->getParameterName()) {
2282 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2283 "format", std::string("1"));
2284 return;
2285 }
2286
2287 if (rawAttr->getNumArgs() != 2) {
2288 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2289 std::string("3"));
2290 return;
2291 }
2292
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002293 // GCC ignores the format attribute on K&R style function
2294 // prototypes, so we ignore it as well
2295 const FunctionTypeProto *proto = getFunctionProto(d);
2296
2297 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002298 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2299 "format", "function");
2300 return;
2301 }
2302
2303 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002304 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002305 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002306 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002307 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002308
2309 const char *Format = rawAttr->getParameterName()->getName();
2310 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2311
2312 // Normalize the argument, __foo__ becomes foo.
2313 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2314 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2315 Format += 2;
2316 FormatLen -= 4;
2317 }
2318
2319 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2320 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2321 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2322 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2323 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2324 "format", rawAttr->getParameterName()->getName());
2325 return;
2326 }
2327
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002328 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002329 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002330 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002331 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2332 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2333 "format", std::string("2"), IdxExpr->getSourceRange());
2334 return;
2335 }
2336
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002337 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002338 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2339 "format", std::string("2"), IdxExpr->getSourceRange());
2340 return;
2341 }
2342
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002343 // make sure the format string is really a string
2344 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2345 if (!Ty->isPointerType() ||
2346 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2347 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2348 IdxExpr->getSourceRange());
2349 return;
2350 }
2351
2352
2353 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002354 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002355 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002356 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2357 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2358 "format", std::string("3"), FirstArgExpr->getSourceRange());
2359 return;
2360 }
2361
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002362 // check if the function is variadic if the 3rd argument non-zero
2363 if (FirstArg != 0) {
2364 if (proto->isVariadic()) {
2365 ++NumArgs; // +1 for ...
2366 } else {
2367 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2368 return;
2369 }
2370 }
2371
2372 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2373 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002374 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002375 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002376 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2377 FirstArgExpr->getSourceRange());
2378 return;
2379 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002380 // if 0 it disables parameter checking (to use with e.g. va_list)
2381 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002382 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2383 "format", std::string("3"), FirstArgExpr->getSourceRange());
2384 return;
2385 }
2386
2387 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2388 Idx.getZExtValue(), FirstArg.getZExtValue()));
2389}
2390
Nate Begemanc398f0b2008-02-21 19:30:49 +00002391void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2392 // check the attribute arguments.
2393 if (rawAttr->getNumArgs() != 1) {
2394 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2395 std::string("1"));
2396 return;
2397 }
2398 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2399 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002400
Nate Begemanc398f0b2008-02-21 19:30:49 +00002401 // Make sure that there is a string literal as the annotation's single
2402 // argument.
2403 if (!SE) {
2404 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2405 return;
2406 }
2407 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2408 SE->getByteLength())));
2409}
2410
Anders Carlsson78aaae92007-12-19 07:19:40 +00002411void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2412{
2413 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002414 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002415 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002416 std::string("1"));
2417 return;
2418 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002419
Anders Carlsson042c4e72008-02-16 19:51:27 +00002420 unsigned Align = 0;
2421
2422 if (rawAttr->getNumArgs() == 0) {
2423 // FIXME: This should be the target specific maximum alignment.
2424 // (For now we just use 128 bits which is the maximum on X86.
2425 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002426 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002427 } else {
2428 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2429 llvm::APSInt alignment(32);
2430 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002431 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002432 "aligned", alignmentExpr->getSourceRange());
2433 return;
2434 }
2435
2436 Align = alignment.getZExtValue() * 8;
2437 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002438
Anders Carlsson042c4e72008-02-16 19:51:27 +00002439 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002440}