blob: a7f8bad574c7fb369ad573bacdc634a89d0f2faa [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000040 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattnerb048c982008-04-06 04:47:34 +000043void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattner0ed844b2008-04-04 06:12:32 +000044 assert(CD->getParent() == CurContext &&
Chris Lattnerb048c982008-04-06 04:47:34 +000045 "The next DeclContext should be directly contained in the current one.");
Chris Lattner0ed844b2008-04-04 06:12:32 +000046 CurContext = CD;
47}
48
Chris Lattnerb048c982008-04-06 04:47:34 +000049void Sema::PopDeclContext() {
50 assert(CurContext && "DeclContext imbalance!");
Chris Lattner0ed844b2008-04-04 06:12:32 +000051 CurContext = CurContext->getParent();
52}
53
Steve Naroffb216c882007-10-09 22:01:59 +000054void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000055 if (S->decl_empty()) return;
56 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000060 Decl *TmpD = static_cast<Decl*>(*I);
61 assert(TmpD && "This decl didn't get pushed??");
62 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63 assert(D && "This decl isn't a ScopedDecl?");
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065 IdentifierInfo *II = D->getIdentifier();
66 if (!II) continue;
67
Chris Lattner7f925cc2008-04-11 07:00:53 +000068 // Unlink this decl from the identifier.
69 IdResolver.RemoveDecl(D);
70
Reid Spencer5f016e22007-07-11 17:01:13 +000071 // This will have to be revisited for C++: there we want to nest stuff in
72 // namespace decls etc. Even for C, we might want a top-level translation
73 // unit decl or something.
74 if (!CurFunctionDecl)
75 continue;
76
77 // Chain this decl to the containing function, it now owns the memory for
78 // the decl.
79 D->setNext(CurFunctionDecl->getDeclChain());
80 CurFunctionDecl->setDeclChain(D);
81 }
82}
83
Steve Naroffe8043c32008-04-01 23:04:06 +000084/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
85/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +000086ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +000087 // The third "scope" argument is 0 since we aren't enabling lazy built-in
88 // creation from this context.
89 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000090
Steve Naroffb327ce02008-04-02 14:35:35 +000091 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +000092}
93
Steve Naroffe8043c32008-04-01 23:04:06 +000094/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +000095/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +000096Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
97 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +000098 if (II == 0) return 0;
99 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000100
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 // Scan up the scope chain looking for a decl that matches this identifier
102 // that is in the appropriate namespace. This search should not take long, as
103 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000104 NamedDecl *ND = IdResolver.Lookup(II, NS);
105 if (ND) return ND;
106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 // If we didn't find a use of this identifier, and if the identifier
108 // corresponds to a compiler builtin, create the decl object for the builtin
109 // now, injecting it into translation unit scope, and return it.
110 if (NS == Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000111 if (enableLazyBuiltinCreation) {
112 // If this is a builtin on this (or all) targets, create the decl.
113 if (unsigned BuiltinID = II->getBuiltinID())
114 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
115 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000116 if (getLangOptions().ObjC1) {
117 // @interface and @compatibility_alias introduce typedef-like names.
118 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000119 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000120 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000121 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
122 if (IDI != ObjCInterfaceDecls.end())
123 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000124 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
125 if (I != ObjCAliasDecls.end())
126 return I->second->getClassInterface();
127 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 }
129 return 0;
130}
131
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000132void Sema::InitBuiltinVaListType()
133{
134 if (!Context.getBuiltinVaListType().isNull())
135 return;
136
137 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000138 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000139 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000140 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
141}
142
Reid Spencer5f016e22007-07-11 17:01:13 +0000143/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
144/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000145ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
146 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 Builtin::ID BID = (Builtin::ID)bid;
148
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000149 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000150 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000151 BID == Builtin::BI__builtin_va_end)
152 InitBuiltinVaListType();
153
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000154 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000155 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
156 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000157 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000158
Chris Lattner7f925cc2008-04-11 07:00:53 +0000159 // TUScope is the translation-unit scope to insert this function into.
160 TUScope->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +0000161
162 // Add this decl to the end of the identifier info.
Chris Lattner7f925cc2008-04-11 07:00:53 +0000163 IdResolver.AddGlobalDecl(New);
164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 return New;
166}
167
168/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
169/// and scope as a previous declaration 'Old'. Figure out how to resolve this
170/// situation, merging decls or emitting diagnostics as appropriate.
171///
Steve Naroffe8043c32008-04-01 23:04:06 +0000172TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 // Verify the old decl was also a typedef.
174 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
175 if (!Old) {
176 Diag(New->getLocation(), diag::err_redefinition_different_kind,
177 New->getName());
178 Diag(OldD->getLocation(), diag::err_previous_definition);
179 return New;
180 }
181
Steve Naroff8ee529b2007-10-31 18:42:27 +0000182 // Allow multiple definitions for ObjC built-in typedefs.
183 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000185 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000186
187 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
188 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
189 // *either* declaration is in a system header. The code below implements
190 // this adhoc compatibility rule. FIXME: The following code will not
191 // work properly when compiling ".i" files (containing preprocessed output).
192 SourceManager &SrcMgr = Context.getSourceManager();
193 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
194 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
195 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
196 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
197 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
198
Steve Naroffc5e2f342008-03-26 21:27:00 +0000199 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
200 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
201 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000202 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000203 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000204
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
206 // TODO: This is totally simplistic. It should handle merging functions
207 // together etc, merging extern int X; int X; ...
208 Diag(New->getLocation(), diag::err_redefinition, New->getName());
209 Diag(Old->getLocation(), diag::err_previous_definition);
210 return New;
211}
212
Chris Lattnerddee4232008-03-03 03:28:21 +0000213/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
214static bool DeclHasAttr(const Decl *decl, const Attr *target) {
215 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
216 if (attr->getKind() == target->getKind())
217 return true;
218
219 return false;
220}
221
222/// MergeAttributes - append attributes from the Old decl to the New one.
223static void MergeAttributes(Decl *New, Decl *Old) {
224 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
225
226// FIXME: fix this code to cleanup the Old attrs correctly
227 while (attr) {
228 tmp = attr;
229 attr = attr->getNext();
230
231 if (!DeclHasAttr(New, tmp)) {
232 New->addAttr(tmp);
233 } else {
234 tmp->setNext(0);
235 delete(tmp);
236 }
237 }
238}
239
Chris Lattner04421082008-04-08 04:40:51 +0000240/// MergeFunctionDecl - We just parsed a function 'New' from
241/// declarator D which has the same name and scope as a previous
242/// declaration 'Old'. Figure out how to resolve this situation,
243/// merging decls or emitting diagnostics as appropriate.
Reid Spencer5f016e22007-07-11 17:01:13 +0000244///
Steve Naroffe8043c32008-04-01 23:04:06 +0000245FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 // Verify the old decl was also a function.
247 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
248 if (!Old) {
249 Diag(New->getLocation(), diag::err_redefinition_different_kind,
250 New->getName());
251 Diag(OldD->getLocation(), diag::err_previous_definition);
252 return New;
253 }
Chris Lattner04421082008-04-08 04:40:51 +0000254
Chris Lattnerddee4232008-03-03 03:28:21 +0000255 MergeAttributes(New, Old);
256
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000257 QualType OldQType = Context.getCanonicalType(Old->getType());
258 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000259
Chris Lattner04421082008-04-08 04:40:51 +0000260 // C++ [dcl.fct]p3:
261 // All declarations for a function shall agree exactly in both the
262 // return type and the parameter-type-list.
263 if (getLangOptions().CPlusPlus && OldQType == NewQType)
264 return MergeCXXFunctionDecl(New, Old);
265
266 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000267 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000268 if (!getLangOptions().CPlusPlus &&
269 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000270 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000271 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000272
Steve Naroff837618c2008-01-16 15:01:34 +0000273 // A function that has already been declared has been redeclared or defined
274 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000275 diag::kind PrevDiag;
276 if (Old->getBody())
277 PrevDiag = diag::err_previous_definition;
278 else if (Old->isImplicit())
279 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000280 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000281 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000282
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
284 // TODO: This is totally simplistic. It should handle merging functions
285 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000286 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
287 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 return New;
289}
290
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000291/// equivalentArrayTypes - Used to determine whether two array types are
292/// equivalent.
293/// We need to check this explicitly as an incomplete array definition is
294/// considered a VariableArrayType, so will not match a complete array
295/// definition that would be otherwise equivalent.
296static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
297 const ArrayType *NewAT = NewQType->getAsArrayType();
298 const ArrayType *OldAT = OldQType->getAsArrayType();
299
300 if (!NewAT || !OldAT)
301 return false;
302
303 // If either (or both) array types in incomplete we need to strip off the
304 // outer VariableArrayType. Once the outer VAT is removed the remaining
305 // types must be identical if the array types are to be considered
306 // equivalent.
307 // eg. int[][1] and int[1][1] become
308 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
309 // removing the outermost VAT gives
310 // CAT(1, int) and CAT(1, int)
311 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000312 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000313 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
314 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000315 NewQType = NewAT->getElementType().getCanonicalType();
316 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000317 }
318
319 return NewQType == OldQType;
320}
321
Reid Spencer5f016e22007-07-11 17:01:13 +0000322/// MergeVarDecl - We just parsed a variable 'New' which has the same name
323/// and scope as a previous declaration 'Old'. Figure out how to resolve this
324/// situation, merging decls or emitting diagnostics as appropriate.
325///
326/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
327/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
328///
Steve Naroffe8043c32008-04-01 23:04:06 +0000329VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000330 // Verify the old decl was also a variable.
331 VarDecl *Old = dyn_cast<VarDecl>(OldD);
332 if (!Old) {
333 Diag(New->getLocation(), diag::err_redefinition_different_kind,
334 New->getName());
335 Diag(OldD->getLocation(), diag::err_previous_definition);
336 return New;
337 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000338
339 MergeAttributes(New, Old);
340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000342 QualType OldCType = Context.getCanonicalType(Old->getType());
343 QualType NewCType = Context.getCanonicalType(New->getType());
344 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 Diag(New->getLocation(), diag::err_redefinition, New->getName());
346 Diag(Old->getLocation(), diag::err_previous_definition);
347 return New;
348 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000349 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
350 if (New->getStorageClass() == VarDecl::Static &&
351 (Old->getStorageClass() == VarDecl::None ||
352 Old->getStorageClass() == VarDecl::Extern)) {
353 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
354 Diag(Old->getLocation(), diag::err_previous_definition);
355 return New;
356 }
357 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
358 if (New->getStorageClass() != VarDecl::Static &&
359 Old->getStorageClass() == VarDecl::Static) {
360 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
361 Diag(Old->getLocation(), diag::err_previous_definition);
362 return New;
363 }
364 // We've verified the types match, now handle "tentative" definitions.
365 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
366 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
367
368 if (OldFSDecl && NewFSDecl) {
369 // Handle C "tentative" external object definitions (C99 6.9.2).
370 bool OldIsTentative = false;
371 bool NewIsTentative = false;
372
373 if (!OldFSDecl->getInit() &&
374 (OldFSDecl->getStorageClass() == VarDecl::None ||
375 OldFSDecl->getStorageClass() == VarDecl::Static))
376 OldIsTentative = true;
377
378 // FIXME: this check doesn't work (since the initializer hasn't been
379 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
380 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
381 // thrown out the old decl.
382 if (!NewFSDecl->getInit() &&
383 (NewFSDecl->getStorageClass() == VarDecl::None ||
384 NewFSDecl->getStorageClass() == VarDecl::Static))
385 ; // change to NewIsTentative = true; once the code is moved.
386
387 if (NewIsTentative || OldIsTentative)
388 return New;
389 }
390 if (Old->getStorageClass() != VarDecl::Extern &&
391 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 Diag(New->getLocation(), diag::err_redefinition, New->getName());
393 Diag(Old->getLocation(), diag::err_previous_definition);
394 }
395 return New;
396}
397
Chris Lattner04421082008-04-08 04:40:51 +0000398/// CheckParmsForFunctionDef - Check that the parameters of the given
399/// function are appropriate for the definition of a function. This
400/// takes care of any checks that cannot be performed on the
401/// declaration itself, e.g., that the types of each of the function
402/// parameters are complete.
403bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
404 bool HasInvalidParm = false;
405 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
406 ParmVarDecl *Param = FD->getParamDecl(p);
407
408 // C99 6.7.5.3p4: the parameters in a parameter type list in a
409 // function declarator that is part of a function definition of
410 // that function shall not have incomplete type.
411 if (Param->getType()->isIncompleteType() &&
412 !Param->isInvalidDecl()) {
413 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
414 Param->getType().getAsString());
415 Param->setInvalidDecl();
416 HasInvalidParm = true;
417 }
418 }
419
420 return HasInvalidParm;
421}
422
423/// CreateImplicitParameter - Creates an implicit function parameter
424/// in the scope S and with the given type. This routine is used, for
425/// example, to create the implicit "self" parameter in an Objective-C
426/// method.
427ParmVarDecl *
428Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
429 SourceLocation IdLoc, QualType Type) {
430 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
431 VarDecl::None, 0, 0);
432 if (Id) {
Chris Lattner7f925cc2008-04-11 07:00:53 +0000433 IdResolver.AddDecl(New, S);
Chris Lattner04421082008-04-08 04:40:51 +0000434 S->AddDecl(New);
435 }
436
437 return New;
438}
439
Reid Spencer5f016e22007-07-11 17:01:13 +0000440/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
441/// no declarator (e.g. "struct foo;") is parsed.
442Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
443 // TODO: emit error on 'int;' or 'const enum foo;'.
444 // TODO: emit error on 'typedef int;'
445 // if (!DS.isMissingDeclaratorOk()) Diag(...);
446
Steve Naroff92199282007-11-17 21:37:36 +0000447 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000448}
449
Steve Naroffd0091aa2008-01-10 22:15:12 +0000450bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000451 // Get the type before calling CheckSingleAssignmentConstraints(), since
452 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000453 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000454
Chris Lattner5cf216b2008-01-04 18:04:52 +0000455 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
456 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
457 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000458}
459
Steve Naroff9e8925e2007-09-04 14:36:54 +0000460bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000461 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000462 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000463 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000464 return true; // types weren't compatible.
465
Steve Naroff9e8925e2007-09-04 14:36:54 +0000466 if (savExpr != expr) // The type was promoted, update initializer list.
467 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000468 return false;
469}
470
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000471bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000472 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000473 // C99 6.7.8p14. We have an array of character type with unknown size
474 // being initialized to a string literal.
475 llvm::APSInt ConstVal(32);
476 ConstVal = strLiteral->getByteLength() + 1;
477 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000478 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000479 ArrayType::Normal, 0);
480 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
481 // C99 6.7.8p14. We have an array of character type with known size.
482 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
483 Diag(strLiteral->getSourceRange().getBegin(),
484 diag::warn_initializer_string_for_char_array_too_long,
485 strLiteral->getSourceRange());
486 } else {
487 assert(0 && "HandleStringLiteralInit(): Invalid array type");
488 }
489 // Set type from "char *" to "constant array of char".
490 strLiteral->setType(DeclT);
491 // For now, we always return false (meaning success).
492 return false;
493}
494
495StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000496 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000497 if (AT && AT->getElementType()->isCharType()) {
498 return dyn_cast<StringLiteral>(Init);
499 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000500 return 0;
501}
502
Steve Naroffa9960332008-01-25 00:51:06 +0000503// CheckInitializerListTypes - Checks the types of elements of an initializer
504// list. This function is recursive: it calls itself to initialize subelements
505// of aggregate types. Note that the topLevel parameter essentially refers to
506// whether this expression "owns" the initializer list passed in, or if this
507// initialization is taking elements out of a parent initializer. Each
508// call to this function adds zero or more to startIndex, reports any errors,
509// and returns true if it found any inconsistent types.
510bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
511 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000512 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000513
514 if (DeclType->isScalarType()) {
515 // The simplest case: initializing a single scalar
516 if (topLevel) {
517 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
518 IList->getSourceRange());
519 }
520 if (startIndex < IList->getNumInits()) {
521 Expr* expr = IList->getInit(startIndex);
522 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
523 // FIXME: Should an error be reported here instead?
524 unsigned newIndex = 0;
525 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
526 } else {
527 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
528 }
529 ++startIndex;
530 }
531 // FIXME: Should an error be reported for empty initializer list + scalar?
532 } else if (DeclType->isVectorType()) {
533 if (startIndex < IList->getNumInits()) {
534 const VectorType *VT = DeclType->getAsVectorType();
535 int maxElements = VT->getNumElements();
536 QualType elementType = VT->getElementType();
537
538 for (int i = 0; i < maxElements; ++i) {
539 // Don't attempt to go past the end of the init list
540 if (startIndex >= IList->getNumInits())
541 break;
542 Expr* expr = IList->getInit(startIndex);
543 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
544 unsigned newIndex = 0;
545 hadError |= CheckInitializerListTypes(SubInitList, elementType,
546 true, newIndex);
547 ++startIndex;
548 } else {
549 hadError |= CheckInitializerListTypes(IList, elementType,
550 false, startIndex);
551 }
552 }
553 }
554 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
555 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000556 if (startIndex < IList->getNumInits() && !topLevel &&
557 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
558 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000559 // We found a compatible struct; per the standard, this initializes the
560 // struct. (The C standard technically says that this only applies for
561 // initializers for declarations with automatic scope; however, this
562 // construct is unambiguous anyway because a struct cannot contain
563 // a type compatible with itself. We'll output an error when we check
564 // if the initializer is constant.)
565 // FIXME: Is a call to CheckSingleInitializer required here?
566 ++startIndex;
567 } else {
568 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000569
Steve Naroff406db932008-02-11 21:52:37 +0000570 // If the record is invalid, some of it's members are invalid. To avoid
571 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000572 if (structDecl->isInvalidDecl())
573 return true;
574
Steve Naroffa9960332008-01-25 00:51:06 +0000575 // If structDecl is a forward declaration, this loop won't do anything;
576 // That's okay, because an error should get printed out elsewhere. It
577 // might be worthwhile to skip over the rest of the initializer, though.
578 int numMembers = structDecl->getNumMembers() -
579 structDecl->hasFlexibleArrayMember();
580 for (int i = 0; i < numMembers; i++) {
581 // Don't attempt to go past the end of the init list
582 if (startIndex >= IList->getNumInits())
583 break;
584 FieldDecl * curField = structDecl->getMember(i);
585 if (!curField->getIdentifier()) {
586 // Don't initialize unnamed fields, e.g. "int : 20;"
587 continue;
588 }
589 QualType fieldType = curField->getType();
590 Expr* expr = IList->getInit(startIndex);
591 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
592 unsigned newStart = 0;
593 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
594 true, newStart);
595 ++startIndex;
596 } else {
597 hadError |= CheckInitializerListTypes(IList, fieldType,
598 false, startIndex);
599 }
600 if (DeclType->isUnionType())
601 break;
602 }
603 // FIXME: Implement flexible array initialization GCC extension (it's a
604 // really messy extension to implement, unfortunately...the necessary
605 // information isn't actually even here!)
606 }
607 } else if (DeclType->isArrayType()) {
608 // Check for the special-case of initializing an array with a string.
609 if (startIndex < IList->getNumInits()) {
610 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
611 DeclType)) {
612 CheckStringLiteralInit(lit, DeclType);
613 ++startIndex;
614 if (topLevel && startIndex < IList->getNumInits()) {
615 // We have leftover initializers; warn
616 Diag(IList->getInit(startIndex)->getLocStart(),
617 diag::err_excess_initializers_in_char_array_initializer,
618 IList->getInit(startIndex)->getSourceRange());
619 }
620 return false;
621 }
622 }
623 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000624 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000625 // FIXME: use a proper constant
626 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000627 } else if (const VariableArrayType *VAT =
628 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000629 // Check for VLAs; in standard C it would be possible to check this
630 // earlier, but I don't know where clang accepts VLAs (gcc accepts
631 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000632 Diag(VAT->getSizeExpr()->getLocStart(),
633 diag::err_variable_object_no_init,
634 VAT->getSizeExpr()->getSourceRange());
635 hadError = true;
636 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000637 } else {
638 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
639 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
640 }
641 QualType elementType = DeclType->getAsArrayType()->getElementType();
642 int numElements = 0;
643 for (int i = 0; i < maxElements; ++i, ++numElements) {
644 // Don't attempt to go past the end of the init list
645 if (startIndex >= IList->getNumInits())
646 break;
647 Expr* expr = IList->getInit(startIndex);
648 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
649 unsigned newIndex = 0;
650 hadError |= CheckInitializerListTypes(SubInitList, elementType,
651 true, newIndex);
652 ++startIndex;
653 } else {
654 hadError |= CheckInitializerListTypes(IList, elementType,
655 false, startIndex);
656 }
657 }
Eli Friedman9db13972008-02-15 12:53:51 +0000658 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000659 // If this is an incomplete array type, the actual type needs to
660 // be calculated here
661 if (numElements == 0) {
662 // Sizing an array implicitly to zero is not allowed
663 // (It could in theory be allowed, but it doesn't really matter.)
664 Diag(IList->getLocStart(),
665 diag::err_at_least_one_initializer_needed_to_size_array);
666 hadError = true;
667 } else {
668 llvm::APSInt ConstVal(32);
669 ConstVal = numElements;
670 DeclType = Context.getConstantArrayType(elementType, ConstVal,
671 ArrayType::Normal, 0);
672 }
673 }
674 } else {
675 assert(0 && "Aggregate that isn't a function or array?!");
676 }
677 } else {
678 // In C, all types are either scalars or aggregates, but
679 // additional handling is needed here for C++ (and possibly others?).
680 assert(0 && "Unsupported initializer type");
681 }
682
683 // If this init list is a base list, we set the type; an initializer doesn't
684 // fundamentally have a type, but this makes the ASTs a bit easier to read
685 if (topLevel)
686 IList->setType(DeclType);
687
688 if (topLevel && startIndex < IList->getNumInits()) {
689 // We have leftover initializers; warn
690 Diag(IList->getInit(startIndex)->getLocStart(),
691 diag::warn_excess_initializers,
692 IList->getInit(startIndex)->getSourceRange());
693 }
694 return hadError;
695}
696
697bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000698 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
699 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000700 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000701 return Diag(VAT->getSizeExpr()->getLocStart(),
702 diag::err_variable_object_no_init,
703 VAT->getSizeExpr()->getSourceRange());
704
Steve Naroff2fdc3742007-12-10 22:44:33 +0000705 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
706 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000707 // FIXME: Handle wide strings
708 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
709 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000710
711 if (DeclType->isArrayType())
712 return Diag(Init->getLocStart(),
713 diag::err_array_init_list_required,
714 Init->getSourceRange());
715
Steve Naroffd0091aa2008-01-10 22:15:12 +0000716 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000717 }
Steve Naroffa9960332008-01-25 00:51:06 +0000718 unsigned newIndex = 0;
719 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000720}
721
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000722Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000723Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000724 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 IdentifierInfo *II = D.getIdentifier();
726
Chris Lattnere80a59c2007-07-25 00:24:17 +0000727 // All of these full declarators require an identifier. If it doesn't have
728 // one, the ParsedFreeStandingDeclSpec action should be used.
729 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000730 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000731 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000732 D.getDeclSpec().getSourceRange(), D.getSourceRange());
733 return 0;
734 }
735
Chris Lattner31e05722007-08-26 06:24:45 +0000736 // The scope passed in may not be a decl scope. Zip up the scope tree until
737 // we find one that is.
738 while ((S->getFlags() & Scope::DeclScope) == 0)
739 S = S->getParent();
740
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000742 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000743 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000744 bool InvalidDecl = false;
745
Chris Lattner41af0932007-11-14 06:34:38 +0000746 QualType R = GetTypeForDeclarator(D, S);
747 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
748
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000750 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 if (!NewTD) return 0;
752
753 // Handle attributes prior to checking for duplicates in MergeVarDecl
754 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
755 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000756 // Merge the decl with the existing one if appropriate. If the decl is
757 // in an outer scope, it isn't the same thing.
758 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
760 if (NewTD == 0) return 0;
761 }
762 New = NewTD;
763 if (S->getParent() == 0) {
764 // C99 6.7.7p2: If a typedef name specifies a variably modified type
765 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000766 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
767 // FIXME: Diagnostic needs to be fixed.
768 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000769 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 }
771 }
Chris Lattner41af0932007-11-14 06:34:38 +0000772 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000773 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 switch (D.getDeclSpec().getStorageClassSpec()) {
775 default: assert(0 && "Unknown storage class!");
776 case DeclSpec::SCS_auto:
777 case DeclSpec::SCS_register:
778 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
779 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000780 InvalidDecl = true;
781 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
783 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
784 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000785 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 }
787
Chris Lattnera98e58d2008-03-15 21:24:04 +0000788 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000789 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
790 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000791 II, R, SC, isInline,
792 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000793 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000794 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
795 D.getAttributes());
Chris Lattner04421082008-04-08 04:40:51 +0000796
797 // Copy the parameter declarations from the declarator D to
798 // the function declaration NewFD, if they are available.
799 if (D.getNumTypeObjects() > 0 &&
800 D.getTypeObject(0).Fun.hasPrototype) {
801 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
802
803 // Create Decl objects for each parameter, adding them to the
804 // FunctionDecl.
805 llvm::SmallVector<ParmVarDecl*, 16> Params;
806
807 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
808 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000809 // single void argument.
Chris Lattner04421082008-04-08 04:40:51 +0000810 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
811 FTI.ArgInfo[0].Param &&
812 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
813 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
814 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000815 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
816
Chris Lattnerdef026a2008-04-10 02:26:16 +0000817 // In C++, the empty parameter-type-list must be spelled "void"; a
818 // typedef of void is not permitted.
819 if (getLangOptions().CPlusPlus &&
Chris Lattner8123a952008-04-10 02:22:51 +0000820 Param->getType() != Context.VoidTy) {
821 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
822 }
823
Chris Lattner04421082008-04-08 04:40:51 +0000824 } else {
825 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
826 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
827 }
828
829 NewFD->setParams(&Params[0], Params.size());
830 }
831
Steve Naroffffce4d52008-01-09 23:34:55 +0000832 // Merge the decl with the existing one if appropriate. Since C functions
833 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 if (PrevDecl) {
835 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
836 if (NewFD == 0) return 0;
837 }
838 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000839
840 // In C++, check default arguments now that we have merged decls.
841 if (getLangOptions().CPlusPlus)
842 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000843 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000844 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000845 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
846 D.getIdentifier()->getName());
847 InvalidDecl = true;
848 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000849
850 VarDecl *NewVD;
851 VarDecl::StorageClass SC;
852 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000853 default: assert(0 && "Unknown storage class!");
854 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
855 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
856 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
857 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
858 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
859 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 }
861 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000862 // C99 6.9p2: The storage-class specifiers auto and register shall not
863 // appear in the declaration specifiers in an external declaration.
864 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
865 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
866 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000867 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000869 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
870 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000871 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000872 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000873 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
874 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000875 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000876 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000877 // Handle attributes prior to checking for duplicates in MergeVarDecl
878 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
879 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000880
881 // Emit an error if an address space was applied to decl with local storage.
882 // This includes arrays of objects with address space qualifiers, but not
883 // automatic variables that point to other address spaces.
884 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000885 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
886 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
887 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000888 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000889 // Merge the decl with the existing one if appropriate. If the decl is
890 // in an outer scope, it isn't the same thing.
891 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 NewVD = MergeVarDecl(NewVD, PrevDecl);
893 if (NewVD == 0) return 0;
894 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000895 New = NewVD;
896 }
897
898 // If this has an identifier, add it to the scope stack.
899 if (II) {
Chris Lattner7f925cc2008-04-11 07:00:53 +0000900 IdResolver.AddDecl(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 S->AddDecl(New);
902 }
Steve Naroff5912a352007-08-28 20:14:24 +0000903 // If any semantic error occurred, mark the decl as invalid.
904 if (D.getInvalidType() || InvalidDecl)
905 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000906
907 return New;
908}
909
Steve Naroffd0091aa2008-01-10 22:15:12 +0000910bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
911 SourceLocation loc;
912 // FIXME: Remove the isReference check and handle assignment to a reference.
913 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
914 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
915 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
916 return true;
917 }
918 return false;
919}
920
Steve Naroffbb204692007-09-12 14:07:44 +0000921void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000922 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000923 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000924 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000925
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000926 // If there is no declaration, there was an error parsing it. Just ignore
927 // the initializer.
928 if (RealDecl == 0) {
929 delete Init;
930 return;
931 }
Steve Naroffbb204692007-09-12 14:07:44 +0000932
Steve Naroff410e3e22007-09-12 20:13:48 +0000933 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
934 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000935 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
936 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000937 RealDecl->setInvalidDecl();
938 return;
939 }
Steve Naroffbb204692007-09-12 14:07:44 +0000940 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000941 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000942 QualType DclT = VDecl->getType(), SavT = DclT;
943 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000944 VarDecl::StorageClass SC = BVD->getStorageClass();
945 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000946 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000947 BVD->setInvalidDecl();
948 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000949 if (CheckInitializerTypes(Init, DclT))
950 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000951 if (SC == VarDecl::Static) // C99 6.7.8p4.
952 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000953 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000954 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000955 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000956 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000957 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000958 if (CheckInitializerTypes(Init, DclT))
959 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000960
961 // C99 6.7.8p4. All file scoped initializers need to be constant.
962 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000963 }
964 // If the type changed, it means we had an incomplete type that was
965 // completed by the initializer. For example:
966 // int ary[] = { 1, 3, 5 };
967 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000968 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000969 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000970 Init->setType(DclT);
971 }
Steve Naroffbb204692007-09-12 14:07:44 +0000972
973 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000974 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000975 return;
976}
977
Reid Spencer5f016e22007-07-11 17:01:13 +0000978/// The declarators are chained together backwards, reverse the list.
979Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
980 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000981 Decl *GroupDecl = static_cast<Decl*>(group);
982 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000983 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000984
985 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
986 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000987 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000989 else { // reverse the list.
990 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000991 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000992 Group->setNextDeclarator(NewGroup);
993 NewGroup = Group;
994 Group = Next;
995 }
996 }
997 // Perform semantic analysis that depends on having fully processed both
998 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000999 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001000 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1001 if (!IDecl)
1002 continue;
1003 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
1004 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
1005 QualType T = IDecl->getType();
1006
1007 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1008 // static storage duration, it shall not have a variable length array.
1009 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +00001010 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001011 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1012 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001013 }
1014 }
1015 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1016 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
1017 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001018 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001019 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1020 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001021 IDecl->setInvalidDecl();
1022 }
1023 }
1024 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1025 // object that has file scope without an initializer, and without a
1026 // storage-class specifier or with the storage-class specifier "static",
1027 // constitutes a tentative definition. Note: A tentative definition with
1028 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +00001029 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
1030 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001031 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001032 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1033 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001034 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001035 // C99 6.9.2p3: If the declaration of an identifier for an object is
1036 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1037 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001038 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1039 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001040 IDecl->setInvalidDecl();
1041 }
1042 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 }
1044 return NewGroup;
1045}
Steve Naroffe1223f72007-08-28 03:03:08 +00001046
Chris Lattner04421082008-04-08 04:40:51 +00001047/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1048/// to introduce parameters into function prototype scope.
1049Sema::DeclTy *
1050Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1051 DeclSpec &DS = D.getDeclSpec();
1052
1053 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1054 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1055 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1056 Diag(DS.getStorageClassSpecLoc(),
1057 diag::err_invalid_storage_class_in_func_decl);
1058 DS.ClearStorageClassSpecs();
1059 }
1060 if (DS.isThreadSpecified()) {
1061 Diag(DS.getThreadSpecLoc(),
1062 diag::err_invalid_storage_class_in_func_decl);
1063 DS.ClearStorageClassSpecs();
1064 }
1065
1066
1067 // In this context, we *do not* check D.getInvalidType(). If the declarator
1068 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1069 // though it will not reflect the user specified type.
1070 QualType parmDeclType = GetTypeForDeclarator(D, S);
1071
1072 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1073
Reid Spencer5f016e22007-07-11 17:01:13 +00001074 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1075 // Can this happen for params? We already checked that they don't conflict
1076 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001077 IdentifierInfo *II = D.getIdentifier();
1078 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1079 if (S->isDeclScope(PrevDecl)) {
1080 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1081 dyn_cast<NamedDecl>(PrevDecl)->getName());
1082
1083 // Recover by removing the name
1084 II = 0;
1085 D.SetIdentifier(0, D.getIdentifierLoc());
1086 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001087 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001088
1089 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1090 // Doing the promotion here has a win and a loss. The win is the type for
1091 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1092 // code generator). The loss is the orginal type isn't preserved. For example:
1093 //
1094 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1095 // int blockvardecl[5];
1096 // sizeof(parmvardecl); // size == 4
1097 // sizeof(blockvardecl); // size == 20
1098 // }
1099 //
1100 // For expressions, all implicit conversions are captured using the
1101 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1102 //
1103 // FIXME: If a source translation tool needs to see the original type, then
1104 // we need to consider storing both types (in ParmVarDecl)...
1105 //
Chris Lattnere6327742008-04-02 05:18:44 +00001106 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001107 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001108 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001109 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001110 parmDeclType = Context.getPointerType(parmDeclType);
1111
Chris Lattner04421082008-04-08 04:40:51 +00001112 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1113 D.getIdentifierLoc(), II,
1114 parmDeclType, VarDecl::None,
1115 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001116
Chris Lattner04421082008-04-08 04:40:51 +00001117 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001118 New->setInvalidDecl();
1119
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 if (II) {
Chris Lattner7f925cc2008-04-11 07:00:53 +00001121 IdResolver.AddDecl(New, S);
Chris Lattner04421082008-04-08 04:40:51 +00001122 S->AddDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00001123 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001124
Chris Lattner04421082008-04-08 04:40:51 +00001125 HandleDeclAttributes(New, D.getAttributes(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001126 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001127
Reid Spencer5f016e22007-07-11 17:01:13 +00001128}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001129
Chris Lattnerb652cea2007-10-09 17:14:05 +00001130Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 assert(CurFunctionDecl == 0 && "Function parsing confused");
1132 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1133 "Not a function declarator!");
1134 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001135
Reid Spencer5f016e22007-07-11 17:01:13 +00001136 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1137 // for a K&R function.
1138 if (!FTI.hasPrototype) {
1139 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001140 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001141 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1142 FTI.ArgInfo[i].Ident->getName());
1143 // Implicitly declare the argument as type 'int' for lack of a better
1144 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001145 DeclSpec DS;
1146 const char* PrevSpec; // unused
1147 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1148 PrevSpec);
1149 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1150 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1151 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 }
1153 }
Chris Lattner52804082008-02-17 19:31:09 +00001154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 // Since this is a function definition, act as though we have information
1156 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001157 if (FTI.NumArgs)
1158 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001159 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001160 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 }
1162
1163 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001164
1165 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001166 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001167 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001168 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1169 if (FD->getBody()) {
1170 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1171 D.getIdentifier()->getName());
1172 Diag(FD->getLocation(), diag::err_previous_definition);
1173 }
1174 }
Steve Narofffabbc342008-02-12 01:09:36 +00001175 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001176 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001177 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001178 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001179
1180 // Check the validity of our function parameters
1181 CheckParmsForFunctionDef(FD);
1182
1183 // Introduce our parameters into the function scope
1184 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1185 ParmVarDecl *Param = FD->getParamDecl(p);
1186 // If this has an identifier, add it to the scope stack.
Chris Lattner7f925cc2008-04-11 07:00:53 +00001187 if (Param->getIdentifier()) {
1188 IdResolver.AddDecl(Param, FnBodyScope);
Chris Lattner04421082008-04-08 04:40:51 +00001189 FnBodyScope->AddDecl(Param);
Steve Naroff66499922007-11-12 03:44:46 +00001190 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 }
Chris Lattner04421082008-04-08 04:40:51 +00001192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 return FD;
1194}
1195
Steve Naroffd6d054d2007-11-11 23:20:51 +00001196Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1197 Decl *dcl = static_cast<Decl *>(D);
1198 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1199 FD->setBody((Stmt*)Body);
1200 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001201 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001202 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001203 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001204 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001205 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001206 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001207 // Verify and clean out per-function state.
1208
1209 // Check goto/label use.
1210 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1211 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1212 // Verify that we have no forward references left. If so, there was a goto
1213 // or address of a label taken, but no definition of it. Label fwd
1214 // definitions are indicated with a null substmt.
1215 if (I->second->getSubStmt() == 0) {
1216 LabelStmt *L = I->second;
1217 // Emit error.
1218 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1219
1220 // At this point, we have gotos that use the bogus label. Stitch it into
1221 // the function body so that they aren't leaked and that the AST is well
1222 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001223 if (Body) {
1224 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1225 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1226 } else {
1227 // The whole function wasn't parsed correctly, just delete this.
1228 delete L;
1229 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001230 }
1231 }
1232 LabelMap.clear();
1233
Steve Naroffd6d054d2007-11-11 23:20:51 +00001234 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001235}
1236
Reid Spencer5f016e22007-07-11 17:01:13 +00001237/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1238/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001239ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1240 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 if (getLangOptions().C99) // Extension in C99.
1242 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1243 else // Legal in C90, but warn about it.
1244 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1245
1246 // FIXME: handle stuff like:
1247 // void foo() { extern float X(); }
1248 // void bar() { X(); } <-- implicit decl for X in another scope.
1249
1250 // Set a Declarator for the implicit definition: int foo();
1251 const char *Dummy;
1252 DeclSpec DS;
1253 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1254 Error = Error; // Silence warning.
1255 assert(!Error && "Error setting up implicit decl!");
1256 Declarator D(DS, Declarator::BlockContext);
1257 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1258 D.SetIdentifier(&II, Loc);
1259
1260 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001261 if (Scope *FnS = S->getFnParent())
1262 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 while (S->getParent())
1264 S = S->getParent();
1265
Steve Naroffe2ef8152008-04-04 14:32:09 +00001266 FunctionDecl *FD =
1267 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1268 FD->setImplicit();
1269 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001270}
1271
1272
Chris Lattner41af0932007-11-14 06:34:38 +00001273TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001274 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001275 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001276 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001277
1278 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001279 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1280 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001281 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001282 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001283 if (D.getInvalidType())
1284 NewTD->setInvalidDecl();
1285 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001286}
1287
Steve Naroff08d92e42007-09-15 18:49:24 +00001288/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001289/// former case, Name will be non-null. In the later case, Name will be null.
1290/// TagType indicates what kind of tag this is. TK indicates whether this is a
1291/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001292Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 SourceLocation KWLoc, IdentifierInfo *Name,
1294 SourceLocation NameLoc, AttributeList *Attr) {
1295 // If this is a use of an existing tag, it must have a name.
1296 assert((Name != 0 || TK == TK_Definition) &&
1297 "Nameless record must be a definition!");
1298
1299 Decl::Kind Kind;
1300 switch (TagType) {
1301 default: assert(0 && "Unknown tag type!");
1302 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1303 case DeclSpec::TST_union: Kind = Decl::Union; break;
1304//case DeclSpec::TST_class: Kind = Decl::Class; break;
1305 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1306 }
1307
1308 // If this is a named struct, check to see if there was a previous forward
1309 // declaration or definition.
1310 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001311 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001312
1313 // If this is a use of a previous tag, or if the tag is already declared in
1314 // the same scope (so that the definition/declaration completes or
1315 // rementions the tag), reuse the decl.
1316 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1317 // Make sure that this wasn't declared as an enum and now used as a struct
1318 // or something similar.
1319 if (PrevDecl->getKind() != Kind) {
1320 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1321 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1322 }
1323
1324 // If this is a use or a forward declaration, we're good.
1325 if (TK != TK_Definition)
1326 return PrevDecl;
1327
1328 // Diagnose attempts to redefine a tag.
1329 if (PrevDecl->isDefinition()) {
1330 Diag(NameLoc, diag::err_redefinition, Name->getName());
1331 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1332 // If this is a redefinition, recover by making this struct be
1333 // anonymous, which will make any later references get the previous
1334 // definition.
1335 Name = 0;
1336 } else {
1337 // Okay, this is definition of a previously declared or referenced tag.
1338 // Move the location of the decl to be the definition site.
1339 PrevDecl->setLocation(NameLoc);
1340 return PrevDecl;
1341 }
1342 }
1343 // If we get here, this is a definition of a new struct type in a nested
1344 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1345 // type.
1346 }
1347
1348 // If there is an identifier, use the location of the identifier as the
1349 // location of the decl, otherwise use the location of the struct/union
1350 // keyword.
1351 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1352
1353 // Otherwise, if this is the first time we've seen this tag, create the decl.
1354 TagDecl *New;
1355 switch (Kind) {
1356 default: assert(0 && "Unknown tag kind!");
1357 case Decl::Enum:
1358 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1359 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001360 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 // If this is an undefined enum, warn.
1362 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1363 break;
1364 case Decl::Union:
1365 case Decl::Struct:
1366 case Decl::Class:
1367 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1368 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001369 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 break;
1371 }
1372
1373 // If this has an identifier, add it to the scope stack.
1374 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001375 // The scope passed in may not be a decl scope. Zip up the scope tree until
1376 // we find one that is.
1377 while ((S->getFlags() & Scope::DeclScope) == 0)
1378 S = S->getParent();
1379
1380 // Add it to the decl chain.
Chris Lattner7f925cc2008-04-11 07:00:53 +00001381 IdResolver.AddDecl(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001382 S->AddDecl(New);
1383 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001384
Anders Carlssonad148062008-02-16 00:29:18 +00001385 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 return New;
1387}
1388
Steve Naroff08d92e42007-09-15 18:49:24 +00001389/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001390/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001391Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001392 SourceLocation DeclStart,
1393 Declarator &D, ExprTy *BitfieldWidth) {
1394 IdentifierInfo *II = D.getIdentifier();
1395 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001396 SourceLocation Loc = DeclStart;
1397 if (II) Loc = D.getIdentifierLoc();
1398
1399 // FIXME: Unnamed fields can be handled in various different ways, for
1400 // example, unnamed unions inject all members into the struct namespace!
1401
1402
1403 if (BitWidth) {
1404 // TODO: Validate.
1405 //printf("WARNING: BITFIELDS IGNORED!\n");
1406
1407 // 6.7.2.1p3
1408 // 6.7.2.1p4
1409
1410 } else {
1411 // Not a bitfield.
1412
1413 // validate II.
1414
1415 }
1416
1417 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001418 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1419 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001420
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1422 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001423 if (T->isVariablyModifiedType()) {
1424 // FIXME: This diagnostic needs work
1425 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001426 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001429 FieldDecl *NewFD;
1430
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001431 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Anders Carlssonad148062008-02-16 00:29:18 +00001432 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1433 D.getAttributes());
1434
Steve Naroff5912a352007-08-28 20:14:24 +00001435 if (D.getInvalidType() || InvalidDecl)
1436 NewFD->setInvalidDecl();
1437 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001438}
1439
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001440/// TranslateIvarVisibility - Translate visibility from a token ID to an
1441/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001442static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001443TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001444 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001445 case tok::objc_private: return ObjCIvarDecl::Private;
1446 case tok::objc_public: return ObjCIvarDecl::Public;
1447 case tok::objc_protected: return ObjCIvarDecl::Protected;
1448 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001449 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001450 }
1451}
1452
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001453/// ActOnIvar - Each field of a struct/union/class is passed into this in order
1454/// to create an IvarDecl object for it.
1455Sema::DeclTy *Sema::ActOnIvar(Scope *S,
1456 SourceLocation DeclStart,
1457 Declarator &D, ExprTy *BitfieldWidth,
1458 tok::ObjCKeywordKind visibility) {
1459 IdentifierInfo *II = D.getIdentifier();
1460 Expr *BitWidth = (Expr*)BitfieldWidth;
1461 SourceLocation Loc = DeclStart;
1462 if (II) Loc = D.getIdentifierLoc();
1463
1464 // FIXME: Unnamed fields can be handled in various different ways, for
1465 // example, unnamed unions inject all members into the struct namespace!
1466
1467
1468 if (BitWidth) {
1469 // TODO: Validate.
1470 //printf("WARNING: BITFIELDS IGNORED!\n");
1471
1472 // 6.7.2.1p3
1473 // 6.7.2.1p4
1474
1475 } else {
1476 // Not a bitfield.
1477
1478 // validate II.
1479
1480 }
1481
1482 QualType T = GetTypeForDeclarator(D, S);
1483 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1484 bool InvalidDecl = false;
1485
1486 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1487 // than a variably modified type.
1488 if (T->isVariablyModifiedType()) {
1489 // FIXME: This diagnostic needs work
1490 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1491 InvalidDecl = true;
1492 }
1493
1494 ObjCIvarDecl *NewID;
1495
1496 NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
1497
1498 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1499 D.getAttributes());
1500
1501 if (D.getInvalidType() || InvalidDecl)
1502 NewID->setInvalidDecl();
1503 // If we have visibility info, make sure the AST is set accordingly.
1504 if (visibility != tok::objc_not_keyword)
1505 NewID ->setAccessControl(TranslateIvarVisibility(visibility));
1506 return NewID;
1507}
1508
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001509void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001510 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001511 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001512 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001513 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1514 assert(EnclosingDecl && "missing record or interface decl");
1515 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1516
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001517 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 // Diagnose code like:
1519 // struct S { struct S {} X; };
1520 // We discover this when we complete the outer S. Reject and ignore the
1521 // outer S.
1522 Diag(Record->getLocation(), diag::err_nested_redefinition,
1523 Record->getKindName());
1524 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001525 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 return;
1527 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 // Verify that all the fields are okay.
1529 unsigned NumNamedMembers = 0;
1530 llvm::SmallVector<FieldDecl*, 32> RecFields;
1531 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001532
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001534
Steve Naroff74216642007-09-14 22:20:54 +00001535 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1536 assert(FD && "missing field decl");
1537
1538 // Remember all fields.
1539 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001540
1541 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001542 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001543
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001545 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001546 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001548 FD->setInvalidDecl();
1549 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 continue;
1551 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1553 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001554 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001555 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001556 FD->setInvalidDecl();
1557 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001558 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001559 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 if (i != NumFields-1 || // ... that the last member ...
1561 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001562 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001564 FD->setInvalidDecl();
1565 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 continue;
1567 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001568 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1570 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001571 FD->setInvalidDecl();
1572 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 continue;
1574 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001576 if (Record)
1577 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1580 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001581 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1583 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001584 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 Record->setHasFlexibleArrayMember(true);
1586 } else {
1587 // If this is a struct/class and this is not the last element, reject
1588 // it. Note that GCC supports variable sized arrays in the middle of
1589 // structures.
1590 if (i != NumFields-1) {
1591 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1592 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001593 FD->setInvalidDecl();
1594 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001595 continue;
1596 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // We support flexible arrays at the end of structs in other structs
1598 // as an extension.
1599 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1600 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001601 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001602 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 }
1604 }
1605 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001606 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001608 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1609 FD->getName());
1610 FD->setInvalidDecl();
1611 EnclosingDecl->setInvalidDecl();
1612 continue;
1613 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001614 // Keep track of the number of named members.
1615 if (IdentifierInfo *II = FD->getIdentifier()) {
1616 // Detect duplicate member names.
1617 if (!FieldIDs.insert(II)) {
1618 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1619 // Find the previous decl.
1620 SourceLocation PrevLoc;
1621 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1622 assert(i != e && "Didn't find previous def!");
1623 if (RecFields[i]->getIdentifier() == II) {
1624 PrevLoc = RecFields[i]->getLocation();
1625 break;
1626 }
1627 }
1628 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001629 FD->setInvalidDecl();
1630 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001631 continue;
1632 }
1633 ++NumNamedMembers;
1634 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 }
1636
Reid Spencer5f016e22007-07-11 17:01:13 +00001637 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001638 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001639 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001640 Consumer.HandleTagDeclDefinition(Record);
1641 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001642 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1643 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1644 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1645 else if (ObjCImplementationDecl *IMPDecl =
1646 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1648 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001649 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001650 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001651 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001652}
1653
Steve Naroff08d92e42007-09-15 18:49:24 +00001654Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001655 DeclTy *lastEnumConst,
1656 SourceLocation IdLoc, IdentifierInfo *Id,
1657 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001658 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 EnumConstantDecl *LastEnumConst =
1660 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1661 Expr *Val = static_cast<Expr*>(val);
1662
Chris Lattner31e05722007-08-26 06:24:45 +00001663 // The scope passed in may not be a decl scope. Zip up the scope tree until
1664 // we find one that is.
1665 while ((S->getFlags() & Scope::DeclScope) == 0)
1666 S = S->getParent();
1667
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 // Verify that there isn't already something declared with this name in this
1669 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001670 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 if (S->isDeclScope(PrevDecl)) {
1672 if (isa<EnumConstantDecl>(PrevDecl))
1673 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1674 else
1675 Diag(IdLoc, diag::err_redefinition, Id->getName());
1676 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001677 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001678 return 0;
1679 }
1680 }
1681
1682 llvm::APSInt EnumVal(32);
1683 QualType EltTy;
1684 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001685 // Make sure to promote the operand type to int.
1686 UsualUnaryConversions(Val);
1687
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1689 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001690 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1692 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001693 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001694 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001695 } else {
1696 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001698 }
1699
1700 if (!Val) {
1701 if (LastEnumConst) {
1702 // Assign the last value + 1.
1703 EnumVal = LastEnumConst->getInitVal();
1704 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001705
1706 // Check for overflow on increment.
1707 if (EnumVal < LastEnumConst->getInitVal())
1708 Diag(IdLoc, diag::warn_enum_value_overflow);
1709
Chris Lattnerb7416f92007-08-27 17:37:24 +00001710 EltTy = LastEnumConst->getType();
1711 } else {
1712 // First value, set to zero.
1713 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001714 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001715 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 }
1717
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001718 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001719 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1720 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001721 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722
1723 // Register this decl in the current scope stack.
Chris Lattner7f925cc2008-04-11 07:00:53 +00001724 IdResolver.AddDecl(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001725 S->AddDecl(New);
1726 return New;
1727}
1728
Steve Naroff08d92e42007-09-15 18:49:24 +00001729void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001730 DeclTy **Elements, unsigned NumElements) {
1731 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1732 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1733
Chris Lattnere37f0be2007-08-28 05:10:31 +00001734 // TODO: If the result value doesn't fit in an int, it must be a long or long
1735 // long value. ISO C does not support this, but GCC does as an extension,
1736 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001737 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001738
Chris Lattnerac609682007-08-28 06:15:15 +00001739 // Verify that all the values are okay, compute the size of the values, and
1740 // reverse the list.
1741 unsigned NumNegativeBits = 0;
1742 unsigned NumPositiveBits = 0;
1743
1744 // Keep track of whether all elements have type int.
1745 bool AllElementsInt = true;
1746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 EnumConstantDecl *EltList = 0;
1748 for (unsigned i = 0; i != NumElements; ++i) {
1749 EnumConstantDecl *ECD =
1750 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1751 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001752
1753 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001754 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001755 assert(InitVal.getBitWidth() >= IntWidth &&
1756 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001757 if (InitVal.getBitWidth() > IntWidth) {
1758 llvm::APSInt V(InitVal);
1759 V.trunc(IntWidth);
1760 V.extend(InitVal.getBitWidth());
1761 if (V != InitVal)
1762 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1763 InitVal.toString());
1764 }
Chris Lattnerac609682007-08-28 06:15:15 +00001765
1766 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001767 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001768 NumPositiveBits = std::max(NumPositiveBits,
1769 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001770 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001771 NumNegativeBits = std::max(NumNegativeBits,
1772 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001773
Chris Lattnerac609682007-08-28 06:15:15 +00001774 // Keep track of whether every enum element has type int (very commmon).
1775 if (AllElementsInt)
1776 AllElementsInt = ECD->getType() == Context.IntTy;
1777
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 ECD->setNextDeclarator(EltList);
1779 EltList = ECD;
1780 }
1781
Chris Lattnerac609682007-08-28 06:15:15 +00001782 // Figure out the type that should be used for this enum.
1783 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1784 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001785 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001786
1787 if (NumNegativeBits) {
1788 // If there is a negative value, figure out the smallest integer type (of
1789 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001790 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001791 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001792 BestWidth = IntWidth;
1793 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001794 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001795
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001796 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001797 BestType = Context.LongTy;
1798 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001799 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001800
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001801 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001802 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1803 BestType = Context.LongLongTy;
1804 }
1805 }
1806 } else {
1807 // If there is no negative value, figure out which of uint, ulong, ulonglong
1808 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001809 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001810 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001811 BestWidth = IntWidth;
1812 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001813 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001814 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001815 } else {
1816 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001817 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001818 "How could an initializer get larger than ULL?");
1819 BestType = Context.UnsignedLongLongTy;
1820 }
1821 }
1822
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001823 // Loop over all of the enumerator constants, changing their types to match
1824 // the type of the enum if needed.
1825 for (unsigned i = 0; i != NumElements; ++i) {
1826 EnumConstantDecl *ECD =
1827 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1828 if (!ECD) continue; // Already issued a diagnostic.
1829
1830 // Standard C says the enumerators have int type, but we allow, as an
1831 // extension, the enumerators to be larger than int size. If each
1832 // enumerator value fits in an int, type it as an int, otherwise type it the
1833 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1834 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001835 if (ECD->getType() == Context.IntTy) {
1836 // Make sure the init value is signed.
1837 llvm::APSInt IV = ECD->getInitVal();
1838 IV.setIsSigned(true);
1839 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001840 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001841 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001842
1843 // Determine whether the value fits into an int.
1844 llvm::APSInt InitVal = ECD->getInitVal();
1845 bool FitsInInt;
1846 if (InitVal.isUnsigned() || !InitVal.isNegative())
1847 FitsInInt = InitVal.getActiveBits() < IntWidth;
1848 else
1849 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1850
1851 // If it fits into an integer type, force it. Otherwise force it to match
1852 // the enum decl type.
1853 QualType NewTy;
1854 unsigned NewWidth;
1855 bool NewSign;
1856 if (FitsInInt) {
1857 NewTy = Context.IntTy;
1858 NewWidth = IntWidth;
1859 NewSign = true;
1860 } else if (ECD->getType() == BestType) {
1861 // Already the right type!
1862 continue;
1863 } else {
1864 NewTy = BestType;
1865 NewWidth = BestWidth;
1866 NewSign = BestType->isSignedIntegerType();
1867 }
1868
1869 // Adjust the APSInt value.
1870 InitVal.extOrTrunc(NewWidth);
1871 InitVal.setIsSigned(NewSign);
1872 ECD->setInitVal(InitVal);
1873
1874 // Adjust the Expr initializer and type.
1875 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1876 ECD->setType(NewTy);
1877 }
Chris Lattnerac609682007-08-28 06:15:15 +00001878
Chris Lattnere00b18c2007-08-28 18:24:31 +00001879 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001880 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001881}
1882
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001883Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1884 ExprTy *expr) {
1885 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1886
Chris Lattner8e25d862008-03-16 00:16:02 +00001887 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001888}
1889
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001890Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001891 SourceLocation LBrace,
1892 SourceLocation RBrace,
1893 const char *Lang,
1894 unsigned StrSize,
1895 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001896 LinkageSpecDecl::LanguageIDs Language;
1897 Decl *dcl = static_cast<Decl *>(D);
1898 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1899 Language = LinkageSpecDecl::lang_c;
1900 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1901 Language = LinkageSpecDecl::lang_cxx;
1902 else {
1903 Diag(Loc, diag::err_bad_language);
1904 return 0;
1905 }
1906
1907 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001908 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001909}
1910
Chris Lattner74788ba2008-02-21 00:48:22 +00001911void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001912
Chris Lattner74788ba2008-02-21 00:48:22 +00001913 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001914 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001916 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 if (!newType.isNull()) // install the new vector type into the decl
1918 vDecl->setType(newType);
1919 }
1920 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1921 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001922 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 if (!newType.isNull()) // install the new vector type into the decl
1924 tDecl->setUnderlyingType(newType);
1925 }
Chris Lattner212839c2008-02-20 23:17:35 +00001926 break;
1927 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001928 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001929 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001930 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001931 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001932 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001933 break;
1934 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001935 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1936 QualType newType = HandleAddressSpaceTypeAttribute(
1937 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001938 Attr);
1939 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001940 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1941 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001942 Attr);
1943 // install the new addr spaced type into the decl
1944 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001945 }
Chris Lattner212839c2008-02-20 23:17:35 +00001946 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001947 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001948 HandleDeprecatedAttribute(New, Attr);
1949 break;
1950 case AttributeList::AT_visibility:
1951 HandleVisibilityAttribute(New, Attr);
1952 break;
1953 case AttributeList::AT_weak:
1954 HandleWeakAttribute(New, Attr);
1955 break;
1956 case AttributeList::AT_dllimport:
1957 HandleDLLImportAttribute(New, Attr);
1958 break;
1959 case AttributeList::AT_dllexport:
1960 HandleDLLExportAttribute(New, Attr);
1961 break;
1962 case AttributeList::AT_nothrow:
1963 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001964 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001965 case AttributeList::AT_stdcall:
1966 HandleStdCallAttribute(New, Attr);
1967 break;
1968 case AttributeList::AT_fastcall:
1969 HandleFastCallAttribute(New, Attr);
1970 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001971 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001972 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001973 break;
1974 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001975 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001976 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001977 case AttributeList::AT_annotate:
1978 HandleAnnotateAttribute(New, Attr);
1979 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001980 case AttributeList::AT_noreturn:
1981 HandleNoReturnAttribute(New, Attr);
1982 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001983 case AttributeList::AT_format:
1984 HandleFormatAttribute(New, Attr);
1985 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001986 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001987#if 0
1988 // TODO: when we have the full set of attributes, warn about unknown ones.
1989 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1990 Attr->getName()->getName());
1991#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001992 break;
1993 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001994}
1995
1996void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1997 AttributeList *declarator_postfix) {
1998 while (declspec_prefix) {
1999 HandleDeclAttribute(New, declspec_prefix);
2000 declspec_prefix = declspec_prefix->getNext();
2001 }
2002 while (declarator_postfix) {
2003 HandleDeclAttribute(New, declarator_postfix);
2004 declarator_postfix = declarator_postfix->getNext();
2005 }
2006}
2007
Steve Naroffbea0b342007-07-29 16:33:31 +00002008void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2009 AttributeList *rawAttr) {
2010 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002011 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002012 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002013 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002014 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002015 return;
Steve Naroff73322922007-07-18 18:00:27 +00002016 }
2017 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2018 llvm::APSInt vecSize(32);
2019 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002020 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002021 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002022 return;
Steve Naroff73322922007-07-18 18:00:27 +00002023 }
2024 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2025 // in conjunction with complex types (pointers, arrays, functions, etc.).
2026 Type *canonType = curType.getCanonicalType().getTypePtr();
2027 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002028 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002029 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002030 return;
Steve Naroff73322922007-07-18 18:00:27 +00002031 }
2032 // unlike gcc's vector_size attribute, the size is specified as the
2033 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002034 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002035
2036 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002037 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002038 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002039 return;
Steve Naroff73322922007-07-18 18:00:27 +00002040 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002041 // Instantiate/Install the vector type, the number of elements is > 0.
2042 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2043 // Remember this typedef decl, we will need it later for diagnostics.
2044 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002045}
2046
Reid Spencer5f016e22007-07-11 17:01:13 +00002047QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002048 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 // check the attribute arugments.
2050 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002051 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002052 std::string("1"));
2053 return QualType();
2054 }
2055 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2056 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002057 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002058 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002059 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 return QualType();
2061 }
2062 // navigate to the base type - we need to provide for vector pointers,
2063 // vector arrays, and functions returning vectors.
2064 Type *canonType = curType.getCanonicalType().getTypePtr();
2065
Steve Naroff73322922007-07-18 18:00:27 +00002066 if (canonType->isPointerType() || canonType->isArrayType() ||
2067 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002068 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002069 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2070 do {
2071 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2072 canonType = PT->getPointeeType().getTypePtr();
2073 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2074 canonType = AT->getElementType().getTypePtr();
2075 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2076 canonType = FT->getResultType().getTypePtr();
2077 } while (canonType->isPointerType() || canonType->isArrayType() ||
2078 canonType->isFunctionType());
2079 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 }
2081 // the base type must be integer or float.
2082 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002083 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002084 curType.getCanonicalType().getAsString());
2085 return QualType();
2086 }
Chris Lattner98be4942008-03-05 18:54:05 +00002087 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002088 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002089 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002090
2091 // the vector size needs to be an integral multiple of the type size.
2092 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002093 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002094 sizeExpr->getSourceRange());
2095 return QualType();
2096 }
2097 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002098 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002099 sizeExpr->getSourceRange());
2100 return QualType();
2101 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002102 // Instantiate the vector type, the number of elements is > 0, and not
2103 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002104 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002105}
2106
Chris Lattner2070d802008-02-20 23:25:22 +00002107void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002108 // check the attribute arguments.
2109 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002110 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002111 std::string("0"));
2112 return;
2113 }
2114
2115 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2116 TD->addAttr(new PackedAttr);
2117 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2118 // If the alignment is less than or equal to 8 bits, the packed attribute
2119 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002120 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002121 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002122 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002123 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002124 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002125 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002126 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002127 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2128 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002129}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002130
Ted Kremenekaecb3832008-02-27 20:43:06 +00002131void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2132 // check the attribute arguments.
2133 if (rawAttr->getNumArgs() != 0) {
2134 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2135 std::string("0"));
2136 return;
2137 }
2138
Ted Kremenek3465fb32008-03-03 16:52:27 +00002139 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2140
2141 if (!Fn) {
2142 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2143 "noreturn", "function");
2144 return;
2145 }
2146
Ted Kremenekaecb3832008-02-27 20:43:06 +00002147 d->addAttr(new NoReturnAttr());
2148}
2149
Chris Lattnerddee4232008-03-03 03:28:21 +00002150void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2151 // check the attribute arguments.
2152 if (rawAttr->getNumArgs() != 0) {
2153 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2154 std::string("0"));
2155 return;
2156 }
2157
2158 d->addAttr(new DeprecatedAttr());
2159}
2160
2161void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2162 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002163 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002164 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2165 std::string("1"));
2166 return;
2167 }
2168
Chris Lattner7b937ae2008-03-04 18:08:48 +00002169 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2170 Arg = Arg->IgnoreParenCasts();
2171 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2172
2173 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002174 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002175 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002176 return;
2177 }
2178
Chris Lattner7b937ae2008-03-04 18:08:48 +00002179 const char *TypeStr = Str->getStrData();
2180 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002181 llvm::GlobalValue::VisibilityTypes type;
2182
Chris Lattner7b937ae2008-03-04 18:08:48 +00002183 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002184 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002185 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002186 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002187 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002188 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002189 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002190 type = llvm::GlobalValue::ProtectedVisibility;
2191 else {
2192 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002193 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002194 return;
2195 }
2196
2197 d->addAttr(new VisibilityAttr(type));
2198}
2199
2200void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2201 // check the attribute arguments.
2202 if (rawAttr->getNumArgs() != 0) {
2203 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2204 std::string("0"));
2205 return;
2206 }
2207
2208 d->addAttr(new WeakAttr());
2209}
2210
2211void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2212 // check the attribute arguments.
2213 if (rawAttr->getNumArgs() != 0) {
2214 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2215 std::string("0"));
2216 return;
2217 }
2218
2219 d->addAttr(new DLLImportAttr());
2220}
2221
2222void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2223 // check the attribute arguments.
2224 if (rawAttr->getNumArgs() != 0) {
2225 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2226 std::string("0"));
2227 return;
2228 }
2229
2230 d->addAttr(new DLLExportAttr());
2231}
2232
Nate Begeman440b4562008-03-07 20:04:22 +00002233void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2234 // check the attribute arguments.
2235 if (rawAttr->getNumArgs() != 0) {
2236 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2237 std::string("0"));
2238 return;
2239 }
2240
2241 d->addAttr(new StdCallAttr());
2242}
2243
2244void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2245 // check the attribute arguments.
2246 if (rawAttr->getNumArgs() != 0) {
2247 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2248 std::string("0"));
2249 return;
2250 }
2251
2252 d->addAttr(new FastCallAttr());
2253}
2254
Chris Lattnerddee4232008-03-03 03:28:21 +00002255void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2256 // check the attribute arguments.
2257 if (rawAttr->getNumArgs() != 0) {
2258 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2259 std::string("0"));
2260 return;
2261 }
2262
2263 d->addAttr(new NoThrowAttr());
2264}
2265
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002266static const FunctionTypeProto *getFunctionProto(Decl *d) {
2267 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2268 if (!decl) return 0;
2269
2270 QualType Ty = decl->getType();
2271
2272 if (Ty->isFunctionPointerType()) {
2273 const PointerType *PtrTy = Ty->getAsPointerType();
2274 Ty = PtrTy->getPointeeType();
2275 }
2276
2277 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2278 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2279
2280 return 0;
2281}
2282
2283
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002284/// Handle __attribute__((format(type,idx,firstarg))) attributes
2285/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002286void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2287
2288 if (!rawAttr->getParameterName()) {
2289 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2290 "format", std::string("1"));
2291 return;
2292 }
2293
2294 if (rawAttr->getNumArgs() != 2) {
2295 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2296 std::string("3"));
2297 return;
2298 }
2299
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002300 // GCC ignores the format attribute on K&R style function
2301 // prototypes, so we ignore it as well
2302 const FunctionTypeProto *proto = getFunctionProto(d);
2303
2304 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002305 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2306 "format", "function");
2307 return;
2308 }
2309
2310 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002311 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002312 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002313 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002314 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002315
2316 const char *Format = rawAttr->getParameterName()->getName();
2317 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2318
2319 // Normalize the argument, __foo__ becomes foo.
2320 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2321 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2322 Format += 2;
2323 FormatLen -= 4;
2324 }
2325
2326 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2327 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2328 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2329 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2330 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2331 "format", rawAttr->getParameterName()->getName());
2332 return;
2333 }
2334
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002335 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002336 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002337 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002338 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2339 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2340 "format", std::string("2"), IdxExpr->getSourceRange());
2341 return;
2342 }
2343
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002344 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002345 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2346 "format", std::string("2"), IdxExpr->getSourceRange());
2347 return;
2348 }
2349
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002350 // make sure the format string is really a string
2351 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2352 if (!Ty->isPointerType() ||
2353 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2354 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2355 IdxExpr->getSourceRange());
2356 return;
2357 }
2358
2359
2360 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002361 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002362 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002363 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2364 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2365 "format", std::string("3"), FirstArgExpr->getSourceRange());
2366 return;
2367 }
2368
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002369 // check if the function is variadic if the 3rd argument non-zero
2370 if (FirstArg != 0) {
2371 if (proto->isVariadic()) {
2372 ++NumArgs; // +1 for ...
2373 } else {
2374 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2375 return;
2376 }
2377 }
2378
2379 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2380 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002381 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002382 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002383 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2384 FirstArgExpr->getSourceRange());
2385 return;
2386 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002387 // if 0 it disables parameter checking (to use with e.g. va_list)
2388 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002389 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2390 "format", std::string("3"), FirstArgExpr->getSourceRange());
2391 return;
2392 }
2393
2394 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2395 Idx.getZExtValue(), FirstArg.getZExtValue()));
2396}
2397
Nate Begemanc398f0b2008-02-21 19:30:49 +00002398void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2399 // check the attribute arguments.
2400 if (rawAttr->getNumArgs() != 1) {
2401 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2402 std::string("1"));
2403 return;
2404 }
2405 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2406 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002407
Nate Begemanc398f0b2008-02-21 19:30:49 +00002408 // Make sure that there is a string literal as the annotation's single
2409 // argument.
2410 if (!SE) {
2411 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2412 return;
2413 }
2414 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2415 SE->getByteLength())));
2416}
2417
Anders Carlsson78aaae92007-12-19 07:19:40 +00002418void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2419{
2420 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002421 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002422 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002423 std::string("1"));
2424 return;
2425 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002426
Anders Carlsson042c4e72008-02-16 19:51:27 +00002427 unsigned Align = 0;
2428
2429 if (rawAttr->getNumArgs() == 0) {
2430 // FIXME: This should be the target specific maximum alignment.
2431 // (For now we just use 128 bits which is the maximum on X86.
2432 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002433 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002434 } else {
2435 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2436 llvm::APSInt alignment(32);
2437 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002438 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002439 "aligned", alignmentExpr->getSourceRange());
2440 return;
2441 }
2442
2443 Align = alignment.getZExtValue() * 8;
2444 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002445
Anders Carlsson042c4e72008-02-16 19:51:27 +00002446 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002447}