blob: ada6ceb68a675ed679295348b5fae18ef391288b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
Douglas Gregor2ce52f32008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000042 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Chris Lattner9fdf9c62008-04-22 18:39:57 +000045void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000046 assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
Chris Lattner9fdf9c62008-04-22 18:39:57 +000047 || DC->getParent() == CurContext ) &&
Chris Lattnerb048c982008-04-06 04:47:34 +000048 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000049 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000050}
51
Chris Lattnerb048c982008-04-06 04:47:34 +000052void Sema::PopDeclContext() {
53 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000054 // If CurContext is a ObjC method, getParent() will return NULL.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +000055 CurContext = isa<ObjCMethodDecl>(CurContext)
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000056 ? Context.getTranslationUnitDecl()
57 : CurContext->getParent();
Chris Lattner0ed844b2008-04-04 06:12:32 +000058}
59
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000060/// Add this decl to the scope shadowed decl chains.
61void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
62 IdResolver.AddDecl(D, S);
63 S->AddDecl(D);
64}
65
Steve Naroffb216c882007-10-09 22:01:59 +000066void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000067 if (S->decl_empty()) return;
68 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
69
Reid Spencer5f016e22007-07-11 17:01:13 +000070 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
71 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000072 Decl *TmpD = static_cast<Decl*>(*I);
73 assert(TmpD && "This decl didn't get pushed??");
74 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
75 assert(D && "This decl isn't a ScopedDecl?");
76
Reid Spencer5f016e22007-07-11 17:01:13 +000077 IdentifierInfo *II = D->getIdentifier();
78 if (!II) continue;
79
Chris Lattner7f925cc2008-04-11 07:00:53 +000080 // Unlink this decl from the identifier.
81 IdResolver.RemoveDecl(D);
82
Reid Spencer5f016e22007-07-11 17:01:13 +000083 // This will have to be revisited for C++: there we want to nest stuff in
84 // namespace decls etc. Even for C, we might want a top-level translation
85 // unit decl or something.
86 if (!CurFunctionDecl)
87 continue;
88
89 // Chain this decl to the containing function, it now owns the memory for
90 // the decl.
91 D->setNext(CurFunctionDecl->getDeclChain());
92 CurFunctionDecl->setDeclChain(D);
93 }
94}
95
Steve Naroffe8043c32008-04-01 23:04:06 +000096/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
97/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000098ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000099 // The third "scope" argument is 0 since we aren't enabling lazy built-in
100 // creation from this context.
101 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000102
Steve Naroffb327ce02008-04-02 14:35:35 +0000103 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104}
105
Steve Naroffe8043c32008-04-01 23:04:06 +0000106/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000107/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000108Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
109 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000111 unsigned NS = NSI;
112 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
113 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000118 NamedDecl *ND = IdResolver.Lookup(II, NS);
119 if (ND) return ND;
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 // If we didn't find a use of this identifier, and if the identifier
122 // corresponds to a compiler builtin, create the decl object for the builtin
123 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000124 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000125 if (enableLazyBuiltinCreation) {
126 // If this is a builtin on this (or all) targets, create the decl.
127 if (unsigned BuiltinID = II->getBuiltinID())
128 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
129 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000130 if (getLangOptions().ObjC1) {
131 // @interface and @compatibility_alias introduce typedef-like names.
132 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000133 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000134 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000135 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
136 if (IDI != ObjCInterfaceDecls.end())
137 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000138 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
139 if (I != ObjCAliasDecls.end())
140 return I->second->getClassInterface();
141 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 }
143 return 0;
144}
145
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000146void Sema::InitBuiltinVaListType()
147{
148 if (!Context.getBuiltinVaListType().isNull())
149 return;
150
151 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000152 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000153 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000154 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
155}
156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
158/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000159ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
160 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 Builtin::ID BID = (Builtin::ID)bid;
162
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000164 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000165 BID == Builtin::BI__builtin_va_end)
166 InitBuiltinVaListType();
167
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000168 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000169 FunctionDecl *New = FunctionDecl::Create(Context,
170 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000171 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000172 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
Chris Lattner7f925cc2008-04-11 07:00:53 +0000174 // TUScope is the translation-unit scope to insert this function into.
175 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000176
177 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000178 IdResolver.AddGlobalDecl(New);
179
Reid Spencer5f016e22007-07-11 17:01:13 +0000180 return New;
181}
182
183/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
184/// and scope as a previous declaration 'Old'. Figure out how to resolve this
185/// situation, merging decls or emitting diagnostics as appropriate.
186///
Steve Naroffe8043c32008-04-01 23:04:06 +0000187TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 // Verify the old decl was also a typedef.
189 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
190 if (!Old) {
191 Diag(New->getLocation(), diag::err_redefinition_different_kind,
192 New->getName());
193 Diag(OldD->getLocation(), diag::err_previous_definition);
194 return New;
195 }
196
Steve Naroff8ee529b2007-10-31 18:42:27 +0000197 // Allow multiple definitions for ObjC built-in typedefs.
198 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000200 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000201
202 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
203 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
204 // *either* declaration is in a system header. The code below implements
205 // this adhoc compatibility rule. FIXME: The following code will not
206 // work properly when compiling ".i" files (containing preprocessed output).
207 SourceManager &SrcMgr = Context.getSourceManager();
208 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
209 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
210 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
211 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
212 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
213
Steve Naroffc5e2f342008-03-26 21:27:00 +0000214 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
215 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
216 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000217 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000218 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000219
Reid Spencer5f016e22007-07-11 17:01:13 +0000220 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
221 // TODO: This is totally simplistic. It should handle merging functions
222 // together etc, merging extern int X; int X; ...
223 Diag(New->getLocation(), diag::err_redefinition, New->getName());
224 Diag(Old->getLocation(), diag::err_previous_definition);
225 return New;
226}
227
Chris Lattnerddee4232008-03-03 03:28:21 +0000228/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
229static bool DeclHasAttr(const Decl *decl, const Attr *target) {
230 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
231 if (attr->getKind() == target->getKind())
232 return true;
233
234 return false;
235}
236
237/// MergeAttributes - append attributes from the Old decl to the New one.
238static void MergeAttributes(Decl *New, Decl *Old) {
239 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
240
241// FIXME: fix this code to cleanup the Old attrs correctly
242 while (attr) {
243 tmp = attr;
244 attr = attr->getNext();
245
246 if (!DeclHasAttr(New, tmp)) {
247 New->addAttr(tmp);
248 } else {
249 tmp->setNext(0);
250 delete(tmp);
251 }
252 }
253}
254
Chris Lattner04421082008-04-08 04:40:51 +0000255/// MergeFunctionDecl - We just parsed a function 'New' from
256/// declarator D which has the same name and scope as a previous
257/// declaration 'Old'. Figure out how to resolve this situation,
258/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000259/// Redeclaration will be set true if thisNew is a redeclaration OldD.
260FunctionDecl *
261Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
262 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000263 // Verify the old decl was also a function.
264 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
265 if (!Old) {
266 Diag(New->getLocation(), diag::err_redefinition_different_kind,
267 New->getName());
268 Diag(OldD->getLocation(), diag::err_previous_definition);
269 return New;
270 }
Chris Lattner04421082008-04-08 04:40:51 +0000271
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000272 QualType OldQType = Context.getCanonicalType(Old->getType());
273 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000274
Chris Lattner04421082008-04-08 04:40:51 +0000275 // C++ [dcl.fct]p3:
276 // All declarations for a function shall agree exactly in both the
277 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000278 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
279 MergeAttributes(New, Old);
280 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000281 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000282 }
Chris Lattner04421082008-04-08 04:40:51 +0000283
284 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000285 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000286 if (!getLangOptions().CPlusPlus &&
287 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000288 MergeAttributes(New, Old);
289 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000290 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000291 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000292
Steve Naroff837618c2008-01-16 15:01:34 +0000293 // A function that has already been declared has been redeclared or defined
294 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000295 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000296 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000297 PrevDiag = diag::err_previous_definition;
298 else if (Old->isImplicit())
299 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000300 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000301 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
304 // TODO: This is totally simplistic. It should handle merging functions
305 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000306 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
307 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 return New;
309}
310
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000311/// equivalentArrayTypes - Used to determine whether two array types are
312/// equivalent.
313/// We need to check this explicitly as an incomplete array definition is
314/// considered a VariableArrayType, so will not match a complete array
315/// definition that would be otherwise equivalent.
316static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
317 const ArrayType *NewAT = NewQType->getAsArrayType();
318 const ArrayType *OldAT = OldQType->getAsArrayType();
319
320 if (!NewAT || !OldAT)
321 return false;
322
323 // If either (or both) array types in incomplete we need to strip off the
324 // outer VariableArrayType. Once the outer VAT is removed the remaining
325 // types must be identical if the array types are to be considered
326 // equivalent.
327 // eg. int[][1] and int[1][1] become
328 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
329 // removing the outermost VAT gives
330 // CAT(1, int) and CAT(1, int)
331 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000332 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000333 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
334 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000335 NewQType = NewAT->getElementType().getCanonicalType();
336 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000337 }
338
339 return NewQType == OldQType;
340}
341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342/// MergeVarDecl - We just parsed a variable 'New' which has the same name
343/// and scope as a previous declaration 'Old'. Figure out how to resolve this
344/// situation, merging decls or emitting diagnostics as appropriate.
345///
346/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
347/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
348///
Steve Naroffe8043c32008-04-01 23:04:06 +0000349VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // Verify the old decl was also a variable.
351 VarDecl *Old = dyn_cast<VarDecl>(OldD);
352 if (!Old) {
353 Diag(New->getLocation(), diag::err_redefinition_different_kind,
354 New->getName());
355 Diag(OldD->getLocation(), diag::err_previous_definition);
356 return New;
357 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000358
359 MergeAttributes(New, Old);
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000362 QualType OldCType = Context.getCanonicalType(Old->getType());
363 QualType NewCType = Context.getCanonicalType(New->getType());
364 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 Diag(New->getLocation(), diag::err_redefinition, New->getName());
366 Diag(Old->getLocation(), diag::err_previous_definition);
367 return New;
368 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000369 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
370 if (New->getStorageClass() == VarDecl::Static &&
371 (Old->getStorageClass() == VarDecl::None ||
372 Old->getStorageClass() == VarDecl::Extern)) {
373 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
374 Diag(Old->getLocation(), diag::err_previous_definition);
375 return New;
376 }
377 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
378 if (New->getStorageClass() != VarDecl::Static &&
379 Old->getStorageClass() == VarDecl::Static) {
380 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
381 Diag(Old->getLocation(), diag::err_previous_definition);
382 return New;
383 }
384 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff248a7532008-04-15 22:42:06 +0000385 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb7b032e2008-01-30 00:44:01 +0000386 // Handle C "tentative" external object definitions (C99 6.9.2).
387 bool OldIsTentative = false;
388 bool NewIsTentative = false;
389
Steve Naroff248a7532008-04-15 22:42:06 +0000390 if (!Old->getInit() &&
391 (Old->getStorageClass() == VarDecl::None ||
392 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000393 OldIsTentative = true;
394
395 // FIXME: this check doesn't work (since the initializer hasn't been
396 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
397 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
398 // thrown out the old decl.
Steve Naroff248a7532008-04-15 22:42:06 +0000399 if (!New->getInit() &&
400 (New->getStorageClass() == VarDecl::None ||
401 New->getStorageClass() == VarDecl::Static))
Steve Naroffb7b032e2008-01-30 00:44:01 +0000402 ; // change to NewIsTentative = true; once the code is moved.
403
404 if (NewIsTentative || OldIsTentative)
405 return New;
406 }
407 if (Old->getStorageClass() != VarDecl::Extern &&
408 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 Diag(New->getLocation(), diag::err_redefinition, New->getName());
410 Diag(Old->getLocation(), diag::err_previous_definition);
411 }
412 return New;
413}
414
Chris Lattner04421082008-04-08 04:40:51 +0000415/// CheckParmsForFunctionDef - Check that the parameters of the given
416/// function are appropriate for the definition of a function. This
417/// takes care of any checks that cannot be performed on the
418/// declaration itself, e.g., that the types of each of the function
419/// parameters are complete.
420bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
421 bool HasInvalidParm = false;
422 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
423 ParmVarDecl *Param = FD->getParamDecl(p);
424
425 // C99 6.7.5.3p4: the parameters in a parameter type list in a
426 // function declarator that is part of a function definition of
427 // that function shall not have incomplete type.
428 if (Param->getType()->isIncompleteType() &&
429 !Param->isInvalidDecl()) {
430 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
431 Param->getType().getAsString());
432 Param->setInvalidDecl();
433 HasInvalidParm = true;
434 }
435 }
436
437 return HasInvalidParm;
438}
439
440/// CreateImplicitParameter - Creates an implicit function parameter
441/// in the scope S and with the given type. This routine is used, for
442/// example, to create the implicit "self" parameter in an Objective-C
443/// method.
444ParmVarDecl *
445Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
446 SourceLocation IdLoc, QualType Type) {
447 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
448 VarDecl::None, 0, 0);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000449 if (Id)
450 PushOnScopeChains(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000451
452 return New;
453}
454
Reid Spencer5f016e22007-07-11 17:01:13 +0000455/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
456/// no declarator (e.g. "struct foo;") is parsed.
457Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
458 // TODO: emit error on 'int;' or 'const enum foo;'.
459 // TODO: emit error on 'typedef int;'
460 // if (!DS.isMissingDeclaratorOk()) Diag(...);
461
Steve Naroff92199282007-11-17 21:37:36 +0000462 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000463}
464
Steve Naroffd0091aa2008-01-10 22:15:12 +0000465bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000466 // Get the type before calling CheckSingleAssignmentConstraints(), since
467 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000468 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000469
Chris Lattner5cf216b2008-01-04 18:04:52 +0000470 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
471 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
472 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000473}
474
Steve Naroff9e8925e2007-09-04 14:36:54 +0000475bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000476 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000477 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000478 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000479 return true; // types weren't compatible.
480
Steve Naroff9e8925e2007-09-04 14:36:54 +0000481 if (savExpr != expr) // The type was promoted, update initializer list.
482 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000483 return false;
484}
485
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000486bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000487 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000488 // C99 6.7.8p14. We have an array of character type with unknown size
489 // being initialized to a string literal.
490 llvm::APSInt ConstVal(32);
491 ConstVal = strLiteral->getByteLength() + 1;
492 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000493 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000494 ArrayType::Normal, 0);
495 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
496 // C99 6.7.8p14. We have an array of character type with known size.
497 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
498 Diag(strLiteral->getSourceRange().getBegin(),
499 diag::warn_initializer_string_for_char_array_too_long,
500 strLiteral->getSourceRange());
501 } else {
502 assert(0 && "HandleStringLiteralInit(): Invalid array type");
503 }
504 // Set type from "char *" to "constant array of char".
505 strLiteral->setType(DeclT);
506 // For now, we always return false (meaning success).
507 return false;
508}
509
510StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000511 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000512 if (AT && AT->getElementType()->isCharType()) {
513 return dyn_cast<StringLiteral>(Init);
514 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000515 return 0;
516}
517
Steve Naroffa9960332008-01-25 00:51:06 +0000518// CheckInitializerListTypes - Checks the types of elements of an initializer
519// list. This function is recursive: it calls itself to initialize subelements
520// of aggregate types. Note that the topLevel parameter essentially refers to
521// whether this expression "owns" the initializer list passed in, or if this
522// initialization is taking elements out of a parent initializer. Each
523// call to this function adds zero or more to startIndex, reports any errors,
524// and returns true if it found any inconsistent types.
525bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
526 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000527 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000528
529 if (DeclType->isScalarType()) {
530 // The simplest case: initializing a single scalar
531 if (topLevel) {
532 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
533 IList->getSourceRange());
534 }
535 if (startIndex < IList->getNumInits()) {
536 Expr* expr = IList->getInit(startIndex);
537 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
538 // FIXME: Should an error be reported here instead?
539 unsigned newIndex = 0;
540 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
541 } else {
542 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
543 }
544 ++startIndex;
545 }
546 // FIXME: Should an error be reported for empty initializer list + scalar?
547 } else if (DeclType->isVectorType()) {
548 if (startIndex < IList->getNumInits()) {
549 const VectorType *VT = DeclType->getAsVectorType();
550 int maxElements = VT->getNumElements();
551 QualType elementType = VT->getElementType();
552
553 for (int i = 0; i < maxElements; ++i) {
554 // Don't attempt to go past the end of the init list
555 if (startIndex >= IList->getNumInits())
556 break;
557 Expr* expr = IList->getInit(startIndex);
558 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
559 unsigned newIndex = 0;
560 hadError |= CheckInitializerListTypes(SubInitList, elementType,
561 true, newIndex);
562 ++startIndex;
563 } else {
564 hadError |= CheckInitializerListTypes(IList, elementType,
565 false, startIndex);
566 }
567 }
568 }
569 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
570 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000571 if (startIndex < IList->getNumInits() && !topLevel &&
572 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
573 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000574 // We found a compatible struct; per the standard, this initializes the
575 // struct. (The C standard technically says that this only applies for
576 // initializers for declarations with automatic scope; however, this
577 // construct is unambiguous anyway because a struct cannot contain
578 // a type compatible with itself. We'll output an error when we check
579 // if the initializer is constant.)
580 // FIXME: Is a call to CheckSingleInitializer required here?
581 ++startIndex;
582 } else {
583 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000584
Steve Naroff406db932008-02-11 21:52:37 +0000585 // If the record is invalid, some of it's members are invalid. To avoid
586 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000587 if (structDecl->isInvalidDecl())
588 return true;
589
Steve Naroffa9960332008-01-25 00:51:06 +0000590 // If structDecl is a forward declaration, this loop won't do anything;
591 // That's okay, because an error should get printed out elsewhere. It
592 // might be worthwhile to skip over the rest of the initializer, though.
593 int numMembers = structDecl->getNumMembers() -
594 structDecl->hasFlexibleArrayMember();
595 for (int i = 0; i < numMembers; i++) {
596 // Don't attempt to go past the end of the init list
597 if (startIndex >= IList->getNumInits())
598 break;
599 FieldDecl * curField = structDecl->getMember(i);
600 if (!curField->getIdentifier()) {
601 // Don't initialize unnamed fields, e.g. "int : 20;"
602 continue;
603 }
604 QualType fieldType = curField->getType();
605 Expr* expr = IList->getInit(startIndex);
606 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
607 unsigned newStart = 0;
608 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
609 true, newStart);
610 ++startIndex;
611 } else {
612 hadError |= CheckInitializerListTypes(IList, fieldType,
613 false, startIndex);
614 }
615 if (DeclType->isUnionType())
616 break;
617 }
618 // FIXME: Implement flexible array initialization GCC extension (it's a
619 // really messy extension to implement, unfortunately...the necessary
620 // information isn't actually even here!)
621 }
622 } else if (DeclType->isArrayType()) {
623 // Check for the special-case of initializing an array with a string.
624 if (startIndex < IList->getNumInits()) {
625 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
626 DeclType)) {
627 CheckStringLiteralInit(lit, DeclType);
628 ++startIndex;
629 if (topLevel && startIndex < IList->getNumInits()) {
630 // We have leftover initializers; warn
631 Diag(IList->getInit(startIndex)->getLocStart(),
632 diag::err_excess_initializers_in_char_array_initializer,
633 IList->getInit(startIndex)->getSourceRange());
634 }
635 return false;
636 }
637 }
638 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000639 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000640 // FIXME: use a proper constant
641 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000642 } else if (const VariableArrayType *VAT =
643 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000644 // Check for VLAs; in standard C it would be possible to check this
645 // earlier, but I don't know where clang accepts VLAs (gcc accepts
646 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000647 Diag(VAT->getSizeExpr()->getLocStart(),
648 diag::err_variable_object_no_init,
649 VAT->getSizeExpr()->getSourceRange());
650 hadError = true;
651 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000652 } else {
653 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
654 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
655 }
656 QualType elementType = DeclType->getAsArrayType()->getElementType();
657 int numElements = 0;
658 for (int i = 0; i < maxElements; ++i, ++numElements) {
659 // Don't attempt to go past the end of the init list
660 if (startIndex >= IList->getNumInits())
661 break;
662 Expr* expr = IList->getInit(startIndex);
663 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
664 unsigned newIndex = 0;
665 hadError |= CheckInitializerListTypes(SubInitList, elementType,
666 true, newIndex);
667 ++startIndex;
668 } else {
669 hadError |= CheckInitializerListTypes(IList, elementType,
670 false, startIndex);
671 }
672 }
Eli Friedman9db13972008-02-15 12:53:51 +0000673 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000674 // If this is an incomplete array type, the actual type needs to
675 // be calculated here
676 if (numElements == 0) {
677 // Sizing an array implicitly to zero is not allowed
678 // (It could in theory be allowed, but it doesn't really matter.)
679 Diag(IList->getLocStart(),
680 diag::err_at_least_one_initializer_needed_to_size_array);
681 hadError = true;
682 } else {
683 llvm::APSInt ConstVal(32);
684 ConstVal = numElements;
685 DeclType = Context.getConstantArrayType(elementType, ConstVal,
686 ArrayType::Normal, 0);
687 }
688 }
689 } else {
690 assert(0 && "Aggregate that isn't a function or array?!");
691 }
692 } else {
693 // In C, all types are either scalars or aggregates, but
694 // additional handling is needed here for C++ (and possibly others?).
695 assert(0 && "Unsupported initializer type");
696 }
697
698 // If this init list is a base list, we set the type; an initializer doesn't
699 // fundamentally have a type, but this makes the ASTs a bit easier to read
700 if (topLevel)
701 IList->setType(DeclType);
702
703 if (topLevel && startIndex < IList->getNumInits()) {
704 // We have leftover initializers; warn
705 Diag(IList->getInit(startIndex)->getLocStart(),
706 diag::warn_excess_initializers,
707 IList->getInit(startIndex)->getSourceRange());
708 }
709 return hadError;
710}
711
712bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000713 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
714 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000715 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000716 return Diag(VAT->getSizeExpr()->getLocStart(),
717 diag::err_variable_object_no_init,
718 VAT->getSizeExpr()->getSourceRange());
719
Steve Naroff2fdc3742007-12-10 22:44:33 +0000720 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
721 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000722 // FIXME: Handle wide strings
723 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
724 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000725
726 if (DeclType->isArrayType())
727 return Diag(Init->getLocStart(),
728 diag::err_array_init_list_required,
729 Init->getSourceRange());
730
Steve Naroffd0091aa2008-01-10 22:15:12 +0000731 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000732 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000733#if 1
Steve Naroffa9960332008-01-25 00:51:06 +0000734 unsigned newIndex = 0;
735 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000736#else
737 InitListChecker CheckInitList(this, InitList, DeclType);
738 return CheckInitList.HadError();
739#endif
Steve Narofff0090632007-09-02 02:04:30 +0000740}
741
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000742Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000743Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000744 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 IdentifierInfo *II = D.getIdentifier();
746
Chris Lattnere80a59c2007-07-25 00:24:17 +0000747 // All of these full declarators require an identifier. If it doesn't have
748 // one, the ParsedFreeStandingDeclSpec action should be used.
749 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000750 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000751 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000752 D.getDeclSpec().getSourceRange(), D.getSourceRange());
753 return 0;
754 }
755
Chris Lattner31e05722007-08-26 06:24:45 +0000756 // The scope passed in may not be a decl scope. Zip up the scope tree until
757 // we find one that is.
758 while ((S->getFlags() & Scope::DeclScope) == 0)
759 S = S->getParent();
760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000762 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000763 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000764 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000765
766 // In C++, the previous declaration we find might be a tag type
767 // (class or enum). In this case, the new declaration will hide the
768 // tag type.
769 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
770 PrevDecl = 0;
771
Chris Lattner41af0932007-11-14 06:34:38 +0000772 QualType R = GetTypeForDeclarator(D, S);
773 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
774
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000776 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000777 if (!NewTD) return 0;
778
779 // Handle attributes prior to checking for duplicates in MergeVarDecl
780 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
781 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000782 // Merge the decl with the existing one if appropriate. If the decl is
783 // in an outer scope, it isn't the same thing.
784 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
786 if (NewTD == 0) return 0;
787 }
788 New = NewTD;
789 if (S->getParent() == 0) {
790 // C99 6.7.7p2: If a typedef name specifies a variably modified type
791 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000792 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
793 // FIXME: Diagnostic needs to be fixed.
794 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000795 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 }
797 }
Chris Lattner41af0932007-11-14 06:34:38 +0000798 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000799 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 switch (D.getDeclSpec().getStorageClassSpec()) {
801 default: assert(0 && "Unknown storage class!");
802 case DeclSpec::SCS_auto:
803 case DeclSpec::SCS_register:
804 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
805 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000806 InvalidDecl = true;
807 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000808 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
809 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
810 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000811 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 }
813
Chris Lattnera98e58d2008-03-15 21:24:04 +0000814 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000815 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
816 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000817 II, R, SC, isInline,
818 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000819 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000820 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
821 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000822
823 // Copy the parameter declarations from the declarator D to
824 // the function declaration NewFD, if they are available.
825 if (D.getNumTypeObjects() > 0 &&
826 D.getTypeObject(0).Fun.hasPrototype) {
827 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
828
829 // Create Decl objects for each parameter, adding them to the
830 // FunctionDecl.
831 llvm::SmallVector<ParmVarDecl*, 16> Params;
832
833 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
834 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000835 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000836 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
837 FTI.ArgInfo[0].Param &&
838 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
839 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
840 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000841 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
842
Chris Lattnerdef026a2008-04-10 02:26:16 +0000843 // In C++, the empty parameter-type-list must be spelled "void"; a
844 // typedef of void is not permitted.
845 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000846 Param->getType() != Context.VoidTy) {
847 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
848 }
849
Chris Lattner04421082008-04-08 04:40:51 +0000850 } else {
851 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
852 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
853 }
854
855 NewFD->setParams(&Params[0], Params.size());
856 }
857
Steve Naroffffce4d52008-01-09 23:34:55 +0000858 // Merge the decl with the existing one if appropriate. Since C functions
859 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 if (PrevDecl) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000861 bool Redeclaration = false;
862 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000864 if (Redeclaration) {
865 // Note that the new declaration is a redeclaration of the
866 // older declaration. Then return the older declaration: the
867 // new one is only kept within the set of previous
868 // declarations for this function.
869 FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
870 OldFD->AddRedeclaration(NewFD);
871 return OldFD;
872 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
874 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000875
876 // In C++, check default arguments now that we have merged decls.
877 if (getLangOptions().CPlusPlus)
878 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000880 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000881 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
882 D.getIdentifier()->getName());
883 InvalidDecl = true;
884 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000885
886 VarDecl *NewVD;
887 VarDecl::StorageClass SC;
888 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000889 default: assert(0 && "Unknown storage class!");
890 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
891 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
892 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
893 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
894 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
895 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 }
897 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 // C99 6.9p2: The storage-class specifiers auto and register shall not
899 // appear in the declaration specifiers in an external declaration.
900 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
901 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
902 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000903 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000904 }
Steve Naroff248a7532008-04-15 22:42:06 +0000905 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
906 II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000907 } else {
Steve Naroff248a7532008-04-15 22:42:06 +0000908 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
909 II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000910 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 // Handle attributes prior to checking for duplicates in MergeVarDecl
912 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
913 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000914
915 // Emit an error if an address space was applied to decl with local storage.
916 // This includes arrays of objects with address space qualifiers, but not
917 // automatic variables that point to other address spaces.
918 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000919 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
920 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
921 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000922 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000923 // Merge the decl with the existing one if appropriate. If the decl is
924 // in an outer scope, it isn't the same thing.
925 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 NewVD = MergeVarDecl(NewVD, PrevDecl);
927 if (NewVD == 0) return 0;
928 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 New = NewVD;
930 }
931
932 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000933 if (II)
934 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000935 // If any semantic error occurred, mark the decl as invalid.
936 if (D.getInvalidType() || InvalidDecl)
937 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000938
939 return New;
940}
941
Steve Naroffd0091aa2008-01-10 22:15:12 +0000942bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
943 SourceLocation loc;
944 // FIXME: Remove the isReference check and handle assignment to a reference.
945 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
946 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
947 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
948 return true;
949 }
950 return false;
951}
952
Steve Naroffbb204692007-09-12 14:07:44 +0000953void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000954 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000955 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000956 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000957
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000958 // If there is no declaration, there was an error parsing it. Just ignore
959 // the initializer.
960 if (RealDecl == 0) {
961 delete Init;
962 return;
963 }
Steve Naroffbb204692007-09-12 14:07:44 +0000964
Steve Naroff410e3e22007-09-12 20:13:48 +0000965 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
966 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000967 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
968 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000969 RealDecl->setInvalidDecl();
970 return;
971 }
Steve Naroffbb204692007-09-12 14:07:44 +0000972 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000973 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000974 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +0000975 if (VDecl->isBlockVarDecl()) {
976 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +0000977 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000978 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +0000979 VDecl->setInvalidDecl();
980 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000981 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +0000982 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000983 if (SC == VarDecl::Static) // C99 6.7.8p4.
984 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000985 }
Steve Naroff248a7532008-04-15 22:42:06 +0000986 } else if (VDecl->isFileVarDecl()) {
987 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000988 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +0000989 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000990 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +0000991 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000992
993 // C99 6.7.8p4. All file scoped initializers need to be constant.
994 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000995 }
996 // If the type changed, it means we had an incomplete type that was
997 // completed by the initializer. For example:
998 // int ary[] = { 1, 3, 5 };
999 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001000 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001001 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001002 Init->setType(DclT);
1003 }
Steve Naroffbb204692007-09-12 14:07:44 +00001004
1005 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001006 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001007 return;
1008}
1009
Reid Spencer5f016e22007-07-11 17:01:13 +00001010/// The declarators are chained together backwards, reverse the list.
1011Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1012 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001013 Decl *GroupDecl = static_cast<Decl*>(group);
1014 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001015 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001016
1017 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1018 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001019 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001020 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001021 else { // reverse the list.
1022 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001023 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001024 Group->setNextDeclarator(NewGroup);
1025 NewGroup = Group;
1026 Group = Next;
1027 }
1028 }
1029 // Perform semantic analysis that depends on having fully processed both
1030 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001031 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001032 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1033 if (!IDecl)
1034 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001035 QualType T = IDecl->getType();
1036
1037 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1038 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001039 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1040 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001041 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001042 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1043 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001044 }
1045 }
1046 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1047 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001048 if (IDecl->isBlockVarDecl() &&
1049 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001050 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001051 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1052 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001053 IDecl->setInvalidDecl();
1054 }
1055 }
1056 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1057 // object that has file scope without an initializer, and without a
1058 // storage-class specifier or with the storage-class specifier "static",
1059 // constitutes a tentative definition. Note: A tentative definition with
1060 // external linkage is valid (C99 6.2.2p5).
Steve Naroff248a7532008-04-15 22:42:06 +00001061 if (IDecl && !IDecl->getInit() &&
1062 (IDecl->getStorageClass() == VarDecl::Static ||
1063 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001064 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001065 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1066 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001067 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001068 // C99 6.9.2p3: If the declaration of an identifier for an object is
1069 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1070 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001071 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1072 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001073 IDecl->setInvalidDecl();
1074 }
1075 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 }
1077 return NewGroup;
1078}
Steve Naroffe1223f72007-08-28 03:03:08 +00001079
Chris Lattner04421082008-04-08 04:40:51 +00001080/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1081/// to introduce parameters into function prototype scope.
1082Sema::DeclTy *
1083Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1084 DeclSpec &DS = D.getDeclSpec();
1085
1086 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1087 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1088 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1089 Diag(DS.getStorageClassSpecLoc(),
1090 diag::err_invalid_storage_class_in_func_decl);
1091 DS.ClearStorageClassSpecs();
1092 }
1093 if (DS.isThreadSpecified()) {
1094 Diag(DS.getThreadSpecLoc(),
1095 diag::err_invalid_storage_class_in_func_decl);
1096 DS.ClearStorageClassSpecs();
1097 }
1098
1099
1100 // In this context, we *do not* check D.getInvalidType(). If the declarator
1101 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1102 // though it will not reflect the user specified type.
1103 QualType parmDeclType = GetTypeForDeclarator(D, S);
1104
1105 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1106
Reid Spencer5f016e22007-07-11 17:01:13 +00001107 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1108 // Can this happen for params? We already checked that they don't conflict
1109 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001110 IdentifierInfo *II = D.getIdentifier();
1111 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1112 if (S->isDeclScope(PrevDecl)) {
1113 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1114 dyn_cast<NamedDecl>(PrevDecl)->getName());
1115
1116 // Recover by removing the name
1117 II = 0;
1118 D.SetIdentifier(0, D.getIdentifierLoc());
1119 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001121
1122 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1123 // Doing the promotion here has a win and a loss. The win is the type for
1124 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1125 // code generator). The loss is the orginal type isn't preserved. For example:
1126 //
1127 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1128 // int blockvardecl[5];
1129 // sizeof(parmvardecl); // size == 4
1130 // sizeof(blockvardecl); // size == 20
1131 // }
1132 //
1133 // For expressions, all implicit conversions are captured using the
1134 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1135 //
1136 // FIXME: If a source translation tool needs to see the original type, then
1137 // we need to consider storing both types (in ParmVarDecl)...
1138 //
Chris Lattnere6327742008-04-02 05:18:44 +00001139 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001140 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001141 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001142 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001143 parmDeclType = Context.getPointerType(parmDeclType);
1144
Chris Lattner04421082008-04-08 04:40:51 +00001145 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1146 D.getIdentifierLoc(), II,
1147 parmDeclType, VarDecl::None,
1148 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001149
Chris Lattner04421082008-04-08 04:40:51 +00001150 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001151 New->setInvalidDecl();
1152
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001153 if (II)
1154 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001155
Chris Lattner04421082008-04-08 04:40:51 +00001156 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001157 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001158
Reid Spencer5f016e22007-07-11 17:01:13 +00001159}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001160
Chris Lattnerb652cea2007-10-09 17:14:05 +00001161Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 assert(CurFunctionDecl == 0 && "Function parsing confused");
1163 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1164 "Not a function declarator!");
1165 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1168 // for a K&R function.
1169 if (!FTI.hasPrototype) {
1170 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001171 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001172 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1173 FTI.ArgInfo[i].Ident->getName());
1174 // Implicitly declare the argument as type 'int' for lack of a better
1175 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001176 DeclSpec DS;
1177 const char* PrevSpec; // unused
1178 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1179 PrevSpec);
1180 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1181 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1182 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 }
1184 }
Chris Lattner52804082008-02-17 19:31:09 +00001185
Reid Spencer5f016e22007-07-11 17:01:13 +00001186 // Since this is a function definition, act as though we have information
1187 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001188 if (FTI.NumArgs)
1189 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001190 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001191 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 }
1193
1194 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001195
1196 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001197 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001198 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001199 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001200 const FunctionDecl *Definition;
1201 if (FD->getBody(Definition)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001202 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1203 D.getIdentifier()->getName());
Douglas Gregorf0097952008-04-21 02:02:58 +00001204 Diag(Definition->getLocation(), diag::err_previous_definition);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001205 }
1206 }
Steve Narofffabbc342008-02-12 01:09:36 +00001207 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001208 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001210 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001211
1212 // Check the validity of our function parameters
1213 CheckParmsForFunctionDef(FD);
1214
1215 // Introduce our parameters into the function scope
1216 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1217 ParmVarDecl *Param = FD->getParamDecl(p);
1218 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001219 if (Param->getIdentifier())
1220 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001221 }
Chris Lattner04421082008-04-08 04:40:51 +00001222
Reid Spencer5f016e22007-07-11 17:01:13 +00001223 return FD;
1224}
1225
Steve Naroffd6d054d2007-11-11 23:20:51 +00001226Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1227 Decl *dcl = static_cast<Decl *>(D);
1228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1229 FD->setBody((Stmt*)Body);
1230 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001231 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001232 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001233 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001234 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001235 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001236 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001237 // Verify and clean out per-function state.
1238
1239 // Check goto/label use.
1240 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1241 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1242 // Verify that we have no forward references left. If so, there was a goto
1243 // or address of a label taken, but no definition of it. Label fwd
1244 // definitions are indicated with a null substmt.
1245 if (I->second->getSubStmt() == 0) {
1246 LabelStmt *L = I->second;
1247 // Emit error.
1248 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1249
1250 // At this point, we have gotos that use the bogus label. Stitch it into
1251 // the function body so that they aren't leaked and that the AST is well
1252 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001253 if (Body) {
1254 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1255 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1256 } else {
1257 // The whole function wasn't parsed correctly, just delete this.
1258 delete L;
1259 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 }
1261 }
1262 LabelMap.clear();
1263
Steve Naroffd6d054d2007-11-11 23:20:51 +00001264 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001265}
1266
Reid Spencer5f016e22007-07-11 17:01:13 +00001267/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1268/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001269ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1270 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001271 if (getLangOptions().C99) // Extension in C99.
1272 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1273 else // Legal in C90, but warn about it.
1274 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1275
1276 // FIXME: handle stuff like:
1277 // void foo() { extern float X(); }
1278 // void bar() { X(); } <-- implicit decl for X in another scope.
1279
1280 // Set a Declarator for the implicit definition: int foo();
1281 const char *Dummy;
1282 DeclSpec DS;
1283 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1284 Error = Error; // Silence warning.
1285 assert(!Error && "Error setting up implicit decl!");
1286 Declarator D(DS, Declarator::BlockContext);
1287 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1288 D.SetIdentifier(&II, Loc);
1289
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001290 // Insert this function into translation-unit scope.
1291
1292 DeclContext *PrevDC = CurContext;
1293 CurContext = Context.getTranslationUnitDecl();
1294
Steve Naroffe2ef8152008-04-04 14:32:09 +00001295 FunctionDecl *FD =
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001296 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001297 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001298
1299 CurContext = PrevDC;
1300
Steve Naroffe2ef8152008-04-04 14:32:09 +00001301 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001302}
1303
1304
Chris Lattner41af0932007-11-14 06:34:38 +00001305TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001306 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001307 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001308 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001309
1310 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001311 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1312 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001313 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001314 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001315 if (D.getInvalidType())
1316 NewTD->setInvalidDecl();
1317 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001318}
1319
Steve Naroff08d92e42007-09-15 18:49:24 +00001320/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001321/// former case, Name will be non-null. In the later case, Name will be null.
1322/// TagType indicates what kind of tag this is. TK indicates whether this is a
1323/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001324Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 SourceLocation KWLoc, IdentifierInfo *Name,
1326 SourceLocation NameLoc, AttributeList *Attr) {
1327 // If this is a use of an existing tag, it must have a name.
1328 assert((Name != 0 || TK == TK_Definition) &&
1329 "Nameless record must be a definition!");
1330
1331 Decl::Kind Kind;
1332 switch (TagType) {
1333 default: assert(0 && "Unknown tag type!");
1334 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1335 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner99dc9142008-04-13 18:59:07 +00001336 case DeclSpec::TST_class: Kind = Decl::Class; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1338 }
1339
1340 // If this is a named struct, check to see if there was a previous forward
1341 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001342 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1343 if (ScopedDecl *PrevDecl =
1344 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001345
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001346 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1347 "unexpected Decl type");
1348 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1349 // If this is a use of a previous tag, or if the tag is already declared in
1350 // the same scope (so that the definition/declaration completes or
1351 // rementions the tag), reuse the decl.
1352 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1353 // Make sure that this wasn't declared as an enum and now used as a struct
1354 // or something similar.
1355 if (PrevDecl->getKind() != Kind) {
1356 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1357 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1358 }
1359
1360 // If this is a use or a forward declaration, we're good.
1361 if (TK != TK_Definition)
1362 return PrevDecl;
Reid Spencer5f016e22007-07-11 17:01:13 +00001363
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001364 // Diagnose attempts to redefine a tag.
1365 if (PrevTagDecl->isDefinition()) {
1366 Diag(NameLoc, diag::err_redefinition, Name->getName());
1367 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1368 // If this is a redefinition, recover by making this struct be
1369 // anonymous, which will make any later references get the previous
1370 // definition.
1371 Name = 0;
1372 } else {
1373 // Okay, this is definition of a previously declared or referenced tag.
1374 // Move the location of the decl to be the definition site.
1375 PrevDecl->setLocation(NameLoc);
1376 return PrevDecl;
1377 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001379 // If we get here, this is a definition of a new struct type in a nested
1380 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1381 // type.
1382 } else {
1383 // The tag name clashes with a namespace name, issue an error and recover
1384 // by making this tag be anonymous.
1385 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1386 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1387 Name = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 }
1390
1391 // If there is an identifier, use the location of the identifier as the
1392 // location of the decl, otherwise use the location of the struct/union
1393 // keyword.
1394 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1395
1396 // Otherwise, if this is the first time we've seen this tag, create the decl.
1397 TagDecl *New;
1398 switch (Kind) {
1399 default: assert(0 && "Unknown tag kind!");
1400 case Decl::Enum:
1401 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1402 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001403 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // If this is an undefined enum, warn.
1405 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1406 break;
1407 case Decl::Union:
1408 case Decl::Struct:
1409 case Decl::Class:
1410 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1411 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001412 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 break;
1414 }
1415
1416 // If this has an identifier, add it to the scope stack.
1417 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001418 // The scope passed in may not be a decl scope. Zip up the scope tree until
1419 // we find one that is.
1420 while ((S->getFlags() & Scope::DeclScope) == 0)
1421 S = S->getParent();
1422
1423 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001424 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001426
Anders Carlssonad148062008-02-16 00:29:18 +00001427 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 return New;
1429}
1430
Steve Naroff08d92e42007-09-15 18:49:24 +00001431/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001432/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001433Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001434 SourceLocation DeclStart,
1435 Declarator &D, ExprTy *BitfieldWidth) {
1436 IdentifierInfo *II = D.getIdentifier();
1437 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 SourceLocation Loc = DeclStart;
1439 if (II) Loc = D.getIdentifierLoc();
1440
1441 // FIXME: Unnamed fields can be handled in various different ways, for
1442 // example, unnamed unions inject all members into the struct namespace!
1443
1444
1445 if (BitWidth) {
1446 // TODO: Validate.
1447 //printf("WARNING: BITFIELDS IGNORED!\n");
1448
1449 // 6.7.2.1p3
1450 // 6.7.2.1p4
1451
1452 } else {
1453 // Not a bitfield.
1454
1455 // validate II.
1456
1457 }
1458
1459 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001460 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1461 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1464 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001465 if (T->isVariablyModifiedType()) {
1466 // FIXME: This diagnostic needs work
1467 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001468 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001469 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // FIXME: Chain fielddecls together.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001471 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001472
Anders Carlssonad148062008-02-16 00:29:18 +00001473 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1474 D.getAttributes());
1475
Steve Naroff5912a352007-08-28 20:14:24 +00001476 if (D.getInvalidType() || InvalidDecl)
1477 NewFD->setInvalidDecl();
1478 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001479}
1480
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001481/// TranslateIvarVisibility - Translate visibility from a token ID to an
1482/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001483static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001484TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001485 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001486 case tok::objc_private: return ObjCIvarDecl::Private;
1487 case tok::objc_public: return ObjCIvarDecl::Public;
1488 case tok::objc_protected: return ObjCIvarDecl::Protected;
1489 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001490 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001491 }
1492}
1493
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001494/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1495/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001496Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001497 SourceLocation DeclStart,
1498 Declarator &D, ExprTy *BitfieldWidth,
1499 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001500 IdentifierInfo *II = D.getIdentifier();
1501 Expr *BitWidth = (Expr*)BitfieldWidth;
1502 SourceLocation Loc = DeclStart;
1503 if (II) Loc = D.getIdentifierLoc();
1504
1505 // FIXME: Unnamed fields can be handled in various different ways, for
1506 // example, unnamed unions inject all members into the struct namespace!
1507
1508
1509 if (BitWidth) {
1510 // TODO: Validate.
1511 //printf("WARNING: BITFIELDS IGNORED!\n");
1512
1513 // 6.7.2.1p3
1514 // 6.7.2.1p4
1515
1516 } else {
1517 // Not a bitfield.
1518
1519 // validate II.
1520
1521 }
1522
1523 QualType T = GetTypeForDeclarator(D, S);
1524 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1525 bool InvalidDecl = false;
1526
1527 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1528 // than a variably modified type.
1529 if (T->isVariablyModifiedType()) {
1530 // FIXME: This diagnostic needs work
1531 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1532 InvalidDecl = true;
1533 }
1534
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001535 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001536
1537 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1538 D.getAttributes());
1539
1540 if (D.getInvalidType() || InvalidDecl)
1541 NewID->setInvalidDecl();
1542 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001543 if (Visibility != tok::objc_not_keyword)
1544 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001545 return NewID;
1546}
1547
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001548void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001549 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001550 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001551 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001552 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1553 assert(EnclosingDecl && "missing record or interface decl");
1554 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1555
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001556 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 // Diagnose code like:
1558 // struct S { struct S {} X; };
1559 // We discover this when we complete the outer S. Reject and ignore the
1560 // outer S.
1561 Diag(Record->getLocation(), diag::err_nested_redefinition,
1562 Record->getKindName());
1563 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001564 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 return;
1566 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001567 // Verify that all the fields are okay.
1568 unsigned NumNamedMembers = 0;
1569 llvm::SmallVector<FieldDecl*, 32> RecFields;
1570 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001571
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001573
Steve Naroff74216642007-09-14 22:20:54 +00001574 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1575 assert(FD && "missing field decl");
1576
1577 // Remember all fields.
1578 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579
1580 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001581 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001584 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001585 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 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 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1592 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001593 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001594 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001595 FD->setInvalidDecl();
1596 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001597 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001598 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001599 if (i != NumFields-1 || // ... that the last member ...
1600 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001601 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001603 FD->setInvalidDecl();
1604 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 continue;
1606 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001607 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1609 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001610 FD->setInvalidDecl();
1611 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 continue;
1613 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001615 if (Record)
1616 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1619 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001620 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1622 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001623 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 Record->setHasFlexibleArrayMember(true);
1625 } else {
1626 // If this is a struct/class and this is not the last element, reject
1627 // it. Note that GCC supports variable sized arrays in the middle of
1628 // structures.
1629 if (i != NumFields-1) {
1630 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1631 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001632 FD->setInvalidDecl();
1633 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 continue;
1635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 // We support flexible arrays at the end of structs in other structs
1637 // as an extension.
1638 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1639 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001640 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001641 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001642 }
1643 }
1644 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001645 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001646 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001647 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1648 FD->getName());
1649 FD->setInvalidDecl();
1650 EnclosingDecl->setInvalidDecl();
1651 continue;
1652 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 // Keep track of the number of named members.
1654 if (IdentifierInfo *II = FD->getIdentifier()) {
1655 // Detect duplicate member names.
1656 if (!FieldIDs.insert(II)) {
1657 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1658 // Find the previous decl.
1659 SourceLocation PrevLoc;
1660 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1661 assert(i != e && "Didn't find previous def!");
1662 if (RecFields[i]->getIdentifier() == II) {
1663 PrevLoc = RecFields[i]->getLocation();
1664 break;
1665 }
1666 }
1667 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001668 FD->setInvalidDecl();
1669 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 continue;
1671 }
1672 ++NumNamedMembers;
1673 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 }
1675
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001677 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001678 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001679 Consumer.HandleTagDeclDefinition(Record);
1680 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001681 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1682 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1683 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1684 else if (ObjCImplementationDecl *IMPDecl =
1685 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001686 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1687 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001688 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001689 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001690 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001691}
1692
Steve Naroff08d92e42007-09-15 18:49:24 +00001693Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 DeclTy *lastEnumConst,
1695 SourceLocation IdLoc, IdentifierInfo *Id,
1696 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001697 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 EnumConstantDecl *LastEnumConst =
1699 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1700 Expr *Val = static_cast<Expr*>(val);
1701
Chris Lattner31e05722007-08-26 06:24:45 +00001702 // The scope passed in may not be a decl scope. Zip up the scope tree until
1703 // we find one that is.
1704 while ((S->getFlags() & Scope::DeclScope) == 0)
1705 S = S->getParent();
1706
Reid Spencer5f016e22007-07-11 17:01:13 +00001707 // Verify that there isn't already something declared with this name in this
1708 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001709 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001710 if (S->isDeclScope(PrevDecl)) {
1711 if (isa<EnumConstantDecl>(PrevDecl))
1712 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1713 else
1714 Diag(IdLoc, diag::err_redefinition, Id->getName());
1715 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001716 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001717 return 0;
1718 }
1719 }
1720
1721 llvm::APSInt EnumVal(32);
1722 QualType EltTy;
1723 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001724 // Make sure to promote the operand type to int.
1725 UsualUnaryConversions(Val);
1726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1728 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001729 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1731 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001732 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001733 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001734 } else {
1735 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001737 }
1738
1739 if (!Val) {
1740 if (LastEnumConst) {
1741 // Assign the last value + 1.
1742 EnumVal = LastEnumConst->getInitVal();
1743 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001744
1745 // Check for overflow on increment.
1746 if (EnumVal < LastEnumConst->getInitVal())
1747 Diag(IdLoc, diag::warn_enum_value_overflow);
1748
Chris Lattnerb7416f92007-08-27 17:37:24 +00001749 EltTy = LastEnumConst->getType();
1750 } else {
1751 // First value, set to zero.
1752 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001753 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 }
1756
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001757 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001758 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1759 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001760 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001761
1762 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001763 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 return New;
1765}
1766
Steve Naroff08d92e42007-09-15 18:49:24 +00001767void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001768 DeclTy **Elements, unsigned NumElements) {
1769 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1770 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1771
Chris Lattnere37f0be2007-08-28 05:10:31 +00001772 // TODO: If the result value doesn't fit in an int, it must be a long or long
1773 // long value. ISO C does not support this, but GCC does as an extension,
1774 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001775 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001776
Chris Lattnerac609682007-08-28 06:15:15 +00001777 // Verify that all the values are okay, compute the size of the values, and
1778 // reverse the list.
1779 unsigned NumNegativeBits = 0;
1780 unsigned NumPositiveBits = 0;
1781
1782 // Keep track of whether all elements have type int.
1783 bool AllElementsInt = true;
1784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 EnumConstantDecl *EltList = 0;
1786 for (unsigned i = 0; i != NumElements; ++i) {
1787 EnumConstantDecl *ECD =
1788 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1789 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001790
1791 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001792 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001793 assert(InitVal.getBitWidth() >= IntWidth &&
1794 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001795 if (InitVal.getBitWidth() > IntWidth) {
1796 llvm::APSInt V(InitVal);
1797 V.trunc(IntWidth);
1798 V.extend(InitVal.getBitWidth());
1799 if (V != InitVal)
1800 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1801 InitVal.toString());
1802 }
Chris Lattnerac609682007-08-28 06:15:15 +00001803
1804 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001805 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001806 NumPositiveBits = std::max(NumPositiveBits,
1807 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001808 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001809 NumNegativeBits = std::max(NumNegativeBits,
1810 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001811
Chris Lattnerac609682007-08-28 06:15:15 +00001812 // Keep track of whether every enum element has type int (very commmon).
1813 if (AllElementsInt)
1814 AllElementsInt = ECD->getType() == Context.IntTy;
1815
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 ECD->setNextDeclarator(EltList);
1817 EltList = ECD;
1818 }
1819
Chris Lattnerac609682007-08-28 06:15:15 +00001820 // Figure out the type that should be used for this enum.
1821 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1822 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001823 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001824
1825 if (NumNegativeBits) {
1826 // If there is a negative value, figure out the smallest integer type (of
1827 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001828 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001829 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001830 BestWidth = IntWidth;
1831 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001832 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001833
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001834 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001835 BestType = Context.LongTy;
1836 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001837 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001838
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001839 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001840 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1841 BestType = Context.LongLongTy;
1842 }
1843 }
1844 } else {
1845 // If there is no negative value, figure out which of uint, ulong, ulonglong
1846 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001847 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001848 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001849 BestWidth = IntWidth;
1850 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001851 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001852 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001853 } else {
1854 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001855 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001856 "How could an initializer get larger than ULL?");
1857 BestType = Context.UnsignedLongLongTy;
1858 }
1859 }
1860
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001861 // Loop over all of the enumerator constants, changing their types to match
1862 // the type of the enum if needed.
1863 for (unsigned i = 0; i != NumElements; ++i) {
1864 EnumConstantDecl *ECD =
1865 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1866 if (!ECD) continue; // Already issued a diagnostic.
1867
1868 // Standard C says the enumerators have int type, but we allow, as an
1869 // extension, the enumerators to be larger than int size. If each
1870 // enumerator value fits in an int, type it as an int, otherwise type it the
1871 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1872 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001873 if (ECD->getType() == Context.IntTy) {
1874 // Make sure the init value is signed.
1875 llvm::APSInt IV = ECD->getInitVal();
1876 IV.setIsSigned(true);
1877 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001878 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001879 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001880
1881 // Determine whether the value fits into an int.
1882 llvm::APSInt InitVal = ECD->getInitVal();
1883 bool FitsInInt;
1884 if (InitVal.isUnsigned() || !InitVal.isNegative())
1885 FitsInInt = InitVal.getActiveBits() < IntWidth;
1886 else
1887 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1888
1889 // If it fits into an integer type, force it. Otherwise force it to match
1890 // the enum decl type.
1891 QualType NewTy;
1892 unsigned NewWidth;
1893 bool NewSign;
1894 if (FitsInInt) {
1895 NewTy = Context.IntTy;
1896 NewWidth = IntWidth;
1897 NewSign = true;
1898 } else if (ECD->getType() == BestType) {
1899 // Already the right type!
1900 continue;
1901 } else {
1902 NewTy = BestType;
1903 NewWidth = BestWidth;
1904 NewSign = BestType->isSignedIntegerType();
1905 }
1906
1907 // Adjust the APSInt value.
1908 InitVal.extOrTrunc(NewWidth);
1909 InitVal.setIsSigned(NewSign);
1910 ECD->setInitVal(InitVal);
1911
1912 // Adjust the Expr initializer and type.
1913 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1914 ECD->setType(NewTy);
1915 }
Chris Lattnerac609682007-08-28 06:15:15 +00001916
Chris Lattnere00b18c2007-08-28 18:24:31 +00001917 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001918 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919}
1920
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001921Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1922 ExprTy *expr) {
1923 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1924
Chris Lattner8e25d862008-03-16 00:16:02 +00001925 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001926}
1927
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001928Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001929 SourceLocation LBrace,
1930 SourceLocation RBrace,
1931 const char *Lang,
1932 unsigned StrSize,
1933 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001934 LinkageSpecDecl::LanguageIDs Language;
1935 Decl *dcl = static_cast<Decl *>(D);
1936 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1937 Language = LinkageSpecDecl::lang_c;
1938 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1939 Language = LinkageSpecDecl::lang_cxx;
1940 else {
1941 Diag(Loc, diag::err_bad_language);
1942 return 0;
1943 }
1944
1945 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001946 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001947}
1948
Chris Lattner74788ba2008-02-21 00:48:22 +00001949void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001950
Chris Lattner74788ba2008-02-21 00:48:22 +00001951 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001952 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001954 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 if (!newType.isNull()) // install the new vector type into the decl
1956 vDecl->setType(newType);
1957 }
1958 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1959 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001960 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 if (!newType.isNull()) // install the new vector type into the decl
1962 tDecl->setUnderlyingType(newType);
1963 }
Chris Lattner212839c2008-02-20 23:17:35 +00001964 break;
Nate Begeman213541a2008-04-18 23:10:10 +00001965 case AttributeList::AT_ext_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001966 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Nate Begeman213541a2008-04-18 23:10:10 +00001967 HandleExtVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001968 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001969 Diag(Attr->getLoc(),
Nate Begeman213541a2008-04-18 23:10:10 +00001970 diag::err_typecheck_ext_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001971 break;
1972 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001973 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1974 QualType newType = HandleAddressSpaceTypeAttribute(
1975 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001976 Attr);
1977 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001978 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1979 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001980 Attr);
1981 // install the new addr spaced type into the decl
1982 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001983 }
Chris Lattner212839c2008-02-20 23:17:35 +00001984 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001985 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001986 HandleDeprecatedAttribute(New, Attr);
1987 break;
1988 case AttributeList::AT_visibility:
1989 HandleVisibilityAttribute(New, Attr);
1990 break;
1991 case AttributeList::AT_weak:
1992 HandleWeakAttribute(New, Attr);
1993 break;
1994 case AttributeList::AT_dllimport:
1995 HandleDLLImportAttribute(New, Attr);
1996 break;
1997 case AttributeList::AT_dllexport:
1998 HandleDLLExportAttribute(New, Attr);
1999 break;
2000 case AttributeList::AT_nothrow:
2001 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00002002 break;
Nate Begeman440b4562008-03-07 20:04:22 +00002003 case AttributeList::AT_stdcall:
2004 HandleStdCallAttribute(New, Attr);
2005 break;
2006 case AttributeList::AT_fastcall:
2007 HandleFastCallAttribute(New, Attr);
2008 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002009 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00002010 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002011 break;
2012 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00002013 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00002014 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00002015 case AttributeList::AT_annotate:
2016 HandleAnnotateAttribute(New, Attr);
2017 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00002018 case AttributeList::AT_noreturn:
2019 HandleNoReturnAttribute(New, Attr);
2020 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00002021 case AttributeList::AT_format:
2022 HandleFormatAttribute(New, Attr);
2023 break;
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002024 case AttributeList::AT_transparent_union:
2025 HandleTransparentUnionAttribute(New, Attr);
2026 break;
Chris Lattner212839c2008-02-20 23:17:35 +00002027 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00002028#if 0
2029 // TODO: when we have the full set of attributes, warn about unknown ones.
2030 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
2031 Attr->getName()->getName());
2032#endif
Chris Lattner212839c2008-02-20 23:17:35 +00002033 break;
2034 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002035}
2036
2037void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2038 AttributeList *declarator_postfix) {
2039 while (declspec_prefix) {
2040 HandleDeclAttribute(New, declspec_prefix);
2041 declspec_prefix = declspec_prefix->getNext();
2042 }
2043 while (declarator_postfix) {
2044 HandleDeclAttribute(New, declarator_postfix);
2045 declarator_postfix = declarator_postfix->getNext();
2046 }
2047}
2048
Nate Begeman213541a2008-04-18 23:10:10 +00002049void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
Steve Naroffbea0b342007-07-29 16:33:31 +00002050 AttributeList *rawAttr) {
2051 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002052 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002053 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002054 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002055 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002056 return;
Steve Naroff73322922007-07-18 18:00:27 +00002057 }
2058 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2059 llvm::APSInt vecSize(32);
2060 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002061 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Nate Begeman213541a2008-04-18 23:10:10 +00002062 "ext_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002063 return;
Steve Naroff73322922007-07-18 18:00:27 +00002064 }
2065 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2066 // in conjunction with complex types (pointers, arrays, functions, etc.).
2067 Type *canonType = curType.getCanonicalType().getTypePtr();
2068 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002069 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002070 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002071 return;
Steve Naroff73322922007-07-18 18:00:27 +00002072 }
2073 // unlike gcc's vector_size attribute, the size is specified as the
2074 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002075 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002076
2077 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002078 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002079 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002080 return;
Steve Naroff73322922007-07-18 18:00:27 +00002081 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002082 // Instantiate/Install the vector type, the number of elements is > 0.
Nate Begeman213541a2008-04-18 23:10:10 +00002083 tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
Steve Naroffbea0b342007-07-29 16:33:31 +00002084 // Remember this typedef decl, we will need it later for diagnostics.
Nate Begeman213541a2008-04-18 23:10:10 +00002085 ExtVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002086}
2087
Reid Spencer5f016e22007-07-11 17:01:13 +00002088QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002089 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 // check the attribute arugments.
2091 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002092 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002093 std::string("1"));
2094 return QualType();
2095 }
2096 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2097 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002098 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002099 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002100 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 return QualType();
2102 }
2103 // navigate to the base type - we need to provide for vector pointers,
2104 // vector arrays, and functions returning vectors.
2105 Type *canonType = curType.getCanonicalType().getTypePtr();
2106
Steve Naroff73322922007-07-18 18:00:27 +00002107 if (canonType->isPointerType() || canonType->isArrayType() ||
2108 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002109 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002110 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2111 do {
2112 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2113 canonType = PT->getPointeeType().getTypePtr();
2114 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2115 canonType = AT->getElementType().getTypePtr();
2116 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2117 canonType = FT->getResultType().getTypePtr();
2118 } while (canonType->isPointerType() || canonType->isArrayType() ||
2119 canonType->isFunctionType());
2120 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 }
2122 // the base type must be integer or float.
2123 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002124 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 curType.getCanonicalType().getAsString());
2126 return QualType();
2127 }
Chris Lattner98be4942008-03-05 18:54:05 +00002128 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002130 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002131
2132 // the vector size needs to be an integral multiple of the type size.
2133 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002134 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 sizeExpr->getSourceRange());
2136 return QualType();
2137 }
2138 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002139 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 sizeExpr->getSourceRange());
2141 return QualType();
2142 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002143 // Instantiate the vector type, the number of elements is > 0, and not
2144 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002145 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002146}
2147
Chris Lattner2070d802008-02-20 23:25:22 +00002148void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002149 // check the attribute arguments.
2150 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002151 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002152 std::string("0"));
2153 return;
2154 }
2155
2156 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2157 TD->addAttr(new PackedAttr);
2158 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2159 // If the alignment is less than or equal to 8 bits, the packed attribute
2160 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002161 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002162 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002163 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002164 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002165 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002166 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002167 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002168 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2169 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002170}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002171
Ted Kremenekaecb3832008-02-27 20:43:06 +00002172void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2173 // check the attribute arguments.
2174 if (rawAttr->getNumArgs() != 0) {
2175 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2176 std::string("0"));
2177 return;
2178 }
2179
Ted Kremenek3465fb32008-03-03 16:52:27 +00002180 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2181
2182 if (!Fn) {
2183 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2184 "noreturn", "function");
2185 return;
2186 }
2187
Ted Kremenekaecb3832008-02-27 20:43:06 +00002188 d->addAttr(new NoReturnAttr());
2189}
2190
Chris Lattnerddee4232008-03-03 03:28:21 +00002191void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2192 // check the attribute arguments.
2193 if (rawAttr->getNumArgs() != 0) {
2194 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2195 std::string("0"));
2196 return;
2197 }
2198
2199 d->addAttr(new DeprecatedAttr());
2200}
2201
2202void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2203 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002204 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002205 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2206 std::string("1"));
2207 return;
2208 }
2209
Chris Lattner7b937ae2008-03-04 18:08:48 +00002210 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2211 Arg = Arg->IgnoreParenCasts();
2212 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2213
2214 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002215 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002216 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002217 return;
2218 }
2219
Chris Lattner7b937ae2008-03-04 18:08:48 +00002220 const char *TypeStr = Str->getStrData();
2221 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002222 llvm::GlobalValue::VisibilityTypes type;
2223
Chris Lattner7b937ae2008-03-04 18:08:48 +00002224 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002225 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002226 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002227 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002228 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002229 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002230 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002231 type = llvm::GlobalValue::ProtectedVisibility;
2232 else {
2233 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002234 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002235 return;
2236 }
2237
2238 d->addAttr(new VisibilityAttr(type));
2239}
2240
2241void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2242 // check the attribute arguments.
2243 if (rawAttr->getNumArgs() != 0) {
2244 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2245 std::string("0"));
2246 return;
2247 }
2248
2249 d->addAttr(new WeakAttr());
2250}
2251
2252void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2253 // check the attribute arguments.
2254 if (rawAttr->getNumArgs() != 0) {
2255 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2256 std::string("0"));
2257 return;
2258 }
2259
2260 d->addAttr(new DLLImportAttr());
2261}
2262
2263void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2264 // check the attribute arguments.
2265 if (rawAttr->getNumArgs() != 0) {
2266 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2267 std::string("0"));
2268 return;
2269 }
2270
2271 d->addAttr(new DLLExportAttr());
2272}
2273
Nate Begeman440b4562008-03-07 20:04:22 +00002274void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2275 // check the attribute arguments.
2276 if (rawAttr->getNumArgs() != 0) {
2277 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2278 std::string("0"));
2279 return;
2280 }
2281
2282 d->addAttr(new StdCallAttr());
2283}
2284
2285void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2286 // check the attribute arguments.
2287 if (rawAttr->getNumArgs() != 0) {
2288 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2289 std::string("0"));
2290 return;
2291 }
2292
2293 d->addAttr(new FastCallAttr());
2294}
2295
Chris Lattnerddee4232008-03-03 03:28:21 +00002296void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2297 // check the attribute arguments.
2298 if (rawAttr->getNumArgs() != 0) {
2299 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2300 std::string("0"));
2301 return;
2302 }
2303
2304 d->addAttr(new NoThrowAttr());
2305}
2306
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002307static const FunctionTypeProto *getFunctionProto(Decl *d) {
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002308 QualType Ty;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002309
Nuno Lopes59b6d5a2008-04-18 22:43:39 +00002310 if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
2311 Ty = decl->getType();
2312 else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
2313 Ty = decl->getType();
2314 else
2315 return 0;
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002316
2317 if (Ty->isFunctionPointerType()) {
2318 const PointerType *PtrTy = Ty->getAsPointerType();
2319 Ty = PtrTy->getPointeeType();
2320 }
2321
2322 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2323 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2324
2325 return 0;
2326}
2327
2328
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002329/// Handle __attribute__((format(type,idx,firstarg))) attributes
2330/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002331void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2332
2333 if (!rawAttr->getParameterName()) {
2334 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2335 "format", std::string("1"));
2336 return;
2337 }
2338
2339 if (rawAttr->getNumArgs() != 2) {
2340 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2341 std::string("3"));
2342 return;
2343 }
2344
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002345 // GCC ignores the format attribute on K&R style function
2346 // prototypes, so we ignore it as well
2347 const FunctionTypeProto *proto = getFunctionProto(d);
2348
2349 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002350 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2351 "format", "function");
2352 return;
2353 }
2354
2355 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002356 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002357 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002358 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002359 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002360
2361 const char *Format = rawAttr->getParameterName()->getName();
2362 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2363
2364 // Normalize the argument, __foo__ becomes foo.
2365 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2366 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2367 Format += 2;
2368 FormatLen -= 4;
2369 }
2370
2371 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2372 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2373 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2374 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2375 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2376 "format", rawAttr->getParameterName()->getName());
2377 return;
2378 }
2379
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002380 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002381 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002382 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002383 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2384 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2385 "format", std::string("2"), IdxExpr->getSourceRange());
2386 return;
2387 }
2388
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002389 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002390 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2391 "format", std::string("2"), IdxExpr->getSourceRange());
2392 return;
2393 }
2394
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002395 // make sure the format string is really a string
2396 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2397 if (!Ty->isPointerType() ||
2398 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2399 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2400 IdxExpr->getSourceRange());
2401 return;
2402 }
2403
2404
2405 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002406 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002407 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002408 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2409 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2410 "format", std::string("3"), FirstArgExpr->getSourceRange());
2411 return;
2412 }
2413
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002414 // check if the function is variadic if the 3rd argument non-zero
2415 if (FirstArg != 0) {
2416 if (proto->isVariadic()) {
2417 ++NumArgs; // +1 for ...
2418 } else {
2419 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2420 return;
2421 }
2422 }
2423
2424 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2425 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002426 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002427 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002428 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2429 FirstArgExpr->getSourceRange());
2430 return;
2431 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002432 // if 0 it disables parameter checking (to use with e.g. va_list)
2433 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002434 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2435 "format", std::string("3"), FirstArgExpr->getSourceRange());
2436 return;
2437 }
2438
2439 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2440 Idx.getZExtValue(), FirstArg.getZExtValue()));
2441}
2442
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002443void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
2444 // check the attribute arguments.
2445 if (rawAttr->getNumArgs() != 0) {
2446 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2447 std::string("0"));
2448 return;
2449 }
2450
2451 TypeDecl *decl = dyn_cast<TypeDecl>(d);
2452
2453 if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
2454 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2455 "transparent_union", "union");
2456 return;
2457 }
2458
Chris Lattner22624942008-04-30 16:04:01 +00002459 //QualType QTy = Context.getTypeDeclType(decl);
2460 //const RecordType *Ty = QTy->getAsUnionType();
Nuno Lopes27ae6c62008-04-25 09:32:00 +00002461
2462// FIXME
2463// Ty->addAttr(new TransparentUnionAttr());
2464}
2465
Nate Begemanc398f0b2008-02-21 19:30:49 +00002466void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2467 // check the attribute arguments.
2468 if (rawAttr->getNumArgs() != 1) {
2469 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2470 std::string("1"));
2471 return;
2472 }
2473 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2474 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002475
Nate Begemanc398f0b2008-02-21 19:30:49 +00002476 // Make sure that there is a string literal as the annotation's single
2477 // argument.
2478 if (!SE) {
2479 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2480 return;
2481 }
2482 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2483 SE->getByteLength())));
2484}
2485
Anders Carlsson78aaae92007-12-19 07:19:40 +00002486void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2487{
2488 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002489 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002490 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002491 std::string("1"));
2492 return;
2493 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002494
Anders Carlsson042c4e72008-02-16 19:51:27 +00002495 unsigned Align = 0;
2496
2497 if (rawAttr->getNumArgs() == 0) {
2498 // FIXME: This should be the target specific maximum alignment.
2499 // (For now we just use 128 bits which is the maximum on X86.
2500 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002501 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002502 } else {
2503 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2504 llvm::APSInt alignment(32);
2505 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002506 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002507 "aligned", alignmentExpr->getSourceRange());
2508 return;
2509 }
2510
2511 Align = alignment.getZExtValue() * 8;
2512 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002513
Anders Carlsson042c4e72008-02-16 19:51:27 +00002514 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002515}