blob: 169a5f77fb159f866ecbe9b61762af3b1aea1dba [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.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001429 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00001430
Anders Carlssonad148062008-02-16 00:29:18 +00001431 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1432 D.getAttributes());
1433
Steve Naroff5912a352007-08-28 20:14:24 +00001434 if (D.getInvalidType() || InvalidDecl)
1435 NewFD->setInvalidDecl();
1436 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001437}
1438
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001439/// TranslateIvarVisibility - Translate visibility from a token ID to an
1440/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001441static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001442TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001443 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001444 case tok::objc_private: return ObjCIvarDecl::Private;
1445 case tok::objc_public: return ObjCIvarDecl::Public;
1446 case tok::objc_protected: return ObjCIvarDecl::Protected;
1447 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001448 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001449 }
1450}
1451
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001452/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1453/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001454Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001455 SourceLocation DeclStart,
1456 Declarator &D, ExprTy *BitfieldWidth,
1457 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001458 IdentifierInfo *II = D.getIdentifier();
1459 Expr *BitWidth = (Expr*)BitfieldWidth;
1460 SourceLocation Loc = DeclStart;
1461 if (II) Loc = D.getIdentifierLoc();
1462
1463 // FIXME: Unnamed fields can be handled in various different ways, for
1464 // example, unnamed unions inject all members into the struct namespace!
1465
1466
1467 if (BitWidth) {
1468 // TODO: Validate.
1469 //printf("WARNING: BITFIELDS IGNORED!\n");
1470
1471 // 6.7.2.1p3
1472 // 6.7.2.1p4
1473
1474 } else {
1475 // Not a bitfield.
1476
1477 // validate II.
1478
1479 }
1480
1481 QualType T = GetTypeForDeclarator(D, S);
1482 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1483 bool InvalidDecl = false;
1484
1485 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1486 // than a variably modified type.
1487 if (T->isVariablyModifiedType()) {
1488 // FIXME: This diagnostic needs work
1489 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1490 InvalidDecl = true;
1491 }
1492
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001493 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001494
1495 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1496 D.getAttributes());
1497
1498 if (D.getInvalidType() || InvalidDecl)
1499 NewID->setInvalidDecl();
1500 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00001501 if (Visibility != tok::objc_not_keyword)
1502 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001503 return NewID;
1504}
1505
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001506void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001507 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001508 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001509 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00001510 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1511 assert(EnclosingDecl && "missing record or interface decl");
1512 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1513
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001514 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001515 // Diagnose code like:
1516 // struct S { struct S {} X; };
1517 // We discover this when we complete the outer S. Reject and ignore the
1518 // outer S.
1519 Diag(Record->getLocation(), diag::err_nested_redefinition,
1520 Record->getKindName());
1521 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001522 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 return;
1524 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Verify that all the fields are okay.
1526 unsigned NumNamedMembers = 0;
1527 llvm::SmallVector<FieldDecl*, 32> RecFields;
1528 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001529
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001531
Steve Naroff74216642007-09-14 22:20:54 +00001532 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1533 assert(FD && "missing field decl");
1534
1535 // Remember all fields.
1536 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001537
1538 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001539 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00001540
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001542 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001543 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001544 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001545 FD->setInvalidDecl();
1546 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 continue;
1548 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1550 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001551 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001552 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001553 FD->setInvalidDecl();
1554 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001555 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001556 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 if (i != NumFields-1 || // ... that the last member ...
1558 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001559 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001561 FD->setInvalidDecl();
1562 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001563 continue;
1564 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001565 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1567 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001568 FD->setInvalidDecl();
1569 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 continue;
1571 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001573 if (Record)
1574 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1577 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001578 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1580 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001581 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 Record->setHasFlexibleArrayMember(true);
1583 } else {
1584 // If this is a struct/class and this is not the last element, reject
1585 // it. Note that GCC supports variable sized arrays in the middle of
1586 // structures.
1587 if (i != NumFields-1) {
1588 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1589 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001590 FD->setInvalidDecl();
1591 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001592 continue;
1593 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // We support flexible arrays at the end of structs in other structs
1595 // as an extension.
1596 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1597 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001598 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001599 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 }
1601 }
1602 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001603 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001604 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001605 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1606 FD->getName());
1607 FD->setInvalidDecl();
1608 EnclosingDecl->setInvalidDecl();
1609 continue;
1610 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // Keep track of the number of named members.
1612 if (IdentifierInfo *II = FD->getIdentifier()) {
1613 // Detect duplicate member names.
1614 if (!FieldIDs.insert(II)) {
1615 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1616 // Find the previous decl.
1617 SourceLocation PrevLoc;
1618 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1619 assert(i != e && "Didn't find previous def!");
1620 if (RecFields[i]->getIdentifier() == II) {
1621 PrevLoc = RecFields[i]->getLocation();
1622 break;
1623 }
1624 }
1625 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001626 FD->setInvalidDecl();
1627 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 continue;
1629 }
1630 ++NumNamedMembers;
1631 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 }
1633
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001635 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001636 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001637 Consumer.HandleTagDeclDefinition(Record);
1638 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001639 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1640 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1641 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1642 else if (ObjCImplementationDecl *IMPDecl =
1643 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001644 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1645 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001646 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001647 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001648 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001649}
1650
Steve Naroff08d92e42007-09-15 18:49:24 +00001651Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 DeclTy *lastEnumConst,
1653 SourceLocation IdLoc, IdentifierInfo *Id,
1654 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001655 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 EnumConstantDecl *LastEnumConst =
1657 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1658 Expr *Val = static_cast<Expr*>(val);
1659
Chris Lattner31e05722007-08-26 06:24:45 +00001660 // The scope passed in may not be a decl scope. Zip up the scope tree until
1661 // we find one that is.
1662 while ((S->getFlags() & Scope::DeclScope) == 0)
1663 S = S->getParent();
1664
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 // Verify that there isn't already something declared with this name in this
1666 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001667 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 if (S->isDeclScope(PrevDecl)) {
1669 if (isa<EnumConstantDecl>(PrevDecl))
1670 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1671 else
1672 Diag(IdLoc, diag::err_redefinition, Id->getName());
1673 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001674 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001675 return 0;
1676 }
1677 }
1678
1679 llvm::APSInt EnumVal(32);
1680 QualType EltTy;
1681 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001682 // Make sure to promote the operand type to int.
1683 UsualUnaryConversions(Val);
1684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1686 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001687 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1689 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001690 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001691 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001692 } else {
1693 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001695 }
1696
1697 if (!Val) {
1698 if (LastEnumConst) {
1699 // Assign the last value + 1.
1700 EnumVal = LastEnumConst->getInitVal();
1701 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001702
1703 // Check for overflow on increment.
1704 if (EnumVal < LastEnumConst->getInitVal())
1705 Diag(IdLoc, diag::warn_enum_value_overflow);
1706
Chris Lattnerb7416f92007-08-27 17:37:24 +00001707 EltTy = LastEnumConst->getType();
1708 } else {
1709 // First value, set to zero.
1710 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001711 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001712 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001713 }
1714
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001715 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001716 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1717 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001718 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001719
1720 // Register this decl in the current scope stack.
Chris Lattner7f925cc2008-04-11 07:00:53 +00001721 IdResolver.AddDecl(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 S->AddDecl(New);
1723 return New;
1724}
1725
Steve Naroff08d92e42007-09-15 18:49:24 +00001726void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 DeclTy **Elements, unsigned NumElements) {
1728 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1729 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1730
Chris Lattnere37f0be2007-08-28 05:10:31 +00001731 // TODO: If the result value doesn't fit in an int, it must be a long or long
1732 // long value. ISO C does not support this, but GCC does as an extension,
1733 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001734 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001735
Chris Lattnerac609682007-08-28 06:15:15 +00001736 // Verify that all the values are okay, compute the size of the values, and
1737 // reverse the list.
1738 unsigned NumNegativeBits = 0;
1739 unsigned NumPositiveBits = 0;
1740
1741 // Keep track of whether all elements have type int.
1742 bool AllElementsInt = true;
1743
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 EnumConstantDecl *EltList = 0;
1745 for (unsigned i = 0; i != NumElements; ++i) {
1746 EnumConstantDecl *ECD =
1747 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1748 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001749
1750 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001751 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001752 assert(InitVal.getBitWidth() >= IntWidth &&
1753 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001754 if (InitVal.getBitWidth() > IntWidth) {
1755 llvm::APSInt V(InitVal);
1756 V.trunc(IntWidth);
1757 V.extend(InitVal.getBitWidth());
1758 if (V != InitVal)
1759 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1760 InitVal.toString());
1761 }
Chris Lattnerac609682007-08-28 06:15:15 +00001762
1763 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001764 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001765 NumPositiveBits = std::max(NumPositiveBits,
1766 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001767 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001768 NumNegativeBits = std::max(NumNegativeBits,
1769 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001770
Chris Lattnerac609682007-08-28 06:15:15 +00001771 // Keep track of whether every enum element has type int (very commmon).
1772 if (AllElementsInt)
1773 AllElementsInt = ECD->getType() == Context.IntTy;
1774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 ECD->setNextDeclarator(EltList);
1776 EltList = ECD;
1777 }
1778
Chris Lattnerac609682007-08-28 06:15:15 +00001779 // Figure out the type that should be used for this enum.
1780 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1781 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001782 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001783
1784 if (NumNegativeBits) {
1785 // If there is a negative value, figure out the smallest integer type (of
1786 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001787 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001788 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001789 BestWidth = IntWidth;
1790 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001791 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001792
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001793 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001794 BestType = Context.LongTy;
1795 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001796 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001797
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001798 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001799 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1800 BestType = Context.LongLongTy;
1801 }
1802 }
1803 } else {
1804 // If there is no negative value, figure out which of uint, ulong, ulonglong
1805 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001806 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001807 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001808 BestWidth = IntWidth;
1809 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001810 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001811 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001812 } else {
1813 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001814 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001815 "How could an initializer get larger than ULL?");
1816 BestType = Context.UnsignedLongLongTy;
1817 }
1818 }
1819
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001820 // Loop over all of the enumerator constants, changing their types to match
1821 // the type of the enum if needed.
1822 for (unsigned i = 0; i != NumElements; ++i) {
1823 EnumConstantDecl *ECD =
1824 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1825 if (!ECD) continue; // Already issued a diagnostic.
1826
1827 // Standard C says the enumerators have int type, but we allow, as an
1828 // extension, the enumerators to be larger than int size. If each
1829 // enumerator value fits in an int, type it as an int, otherwise type it the
1830 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1831 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001832 if (ECD->getType() == Context.IntTy) {
1833 // Make sure the init value is signed.
1834 llvm::APSInt IV = ECD->getInitVal();
1835 IV.setIsSigned(true);
1836 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001837 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001838 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001839
1840 // Determine whether the value fits into an int.
1841 llvm::APSInt InitVal = ECD->getInitVal();
1842 bool FitsInInt;
1843 if (InitVal.isUnsigned() || !InitVal.isNegative())
1844 FitsInInt = InitVal.getActiveBits() < IntWidth;
1845 else
1846 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1847
1848 // If it fits into an integer type, force it. Otherwise force it to match
1849 // the enum decl type.
1850 QualType NewTy;
1851 unsigned NewWidth;
1852 bool NewSign;
1853 if (FitsInInt) {
1854 NewTy = Context.IntTy;
1855 NewWidth = IntWidth;
1856 NewSign = true;
1857 } else if (ECD->getType() == BestType) {
1858 // Already the right type!
1859 continue;
1860 } else {
1861 NewTy = BestType;
1862 NewWidth = BestWidth;
1863 NewSign = BestType->isSignedIntegerType();
1864 }
1865
1866 // Adjust the APSInt value.
1867 InitVal.extOrTrunc(NewWidth);
1868 InitVal.setIsSigned(NewSign);
1869 ECD->setInitVal(InitVal);
1870
1871 // Adjust the Expr initializer and type.
1872 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1873 ECD->setType(NewTy);
1874 }
Chris Lattnerac609682007-08-28 06:15:15 +00001875
Chris Lattnere00b18c2007-08-28 18:24:31 +00001876 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001877 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001878}
1879
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001880Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1881 ExprTy *expr) {
1882 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1883
Chris Lattner8e25d862008-03-16 00:16:02 +00001884 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001885}
1886
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001887Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001888 SourceLocation LBrace,
1889 SourceLocation RBrace,
1890 const char *Lang,
1891 unsigned StrSize,
1892 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001893 LinkageSpecDecl::LanguageIDs Language;
1894 Decl *dcl = static_cast<Decl *>(D);
1895 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1896 Language = LinkageSpecDecl::lang_c;
1897 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1898 Language = LinkageSpecDecl::lang_cxx;
1899 else {
1900 Diag(Loc, diag::err_bad_language);
1901 return 0;
1902 }
1903
1904 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001905 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001906}
1907
Chris Lattner74788ba2008-02-21 00:48:22 +00001908void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001909
Chris Lattner74788ba2008-02-21 00:48:22 +00001910 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001911 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001913 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001914 if (!newType.isNull()) // install the new vector type into the decl
1915 vDecl->setType(newType);
1916 }
1917 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1918 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001919 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 if (!newType.isNull()) // install the new vector type into the decl
1921 tDecl->setUnderlyingType(newType);
1922 }
Chris Lattner212839c2008-02-20 23:17:35 +00001923 break;
1924 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001925 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001926 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001927 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001928 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001929 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001930 break;
1931 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001932 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1933 QualType newType = HandleAddressSpaceTypeAttribute(
1934 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001935 Attr);
1936 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001937 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1938 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001939 Attr);
1940 // install the new addr spaced type into the decl
1941 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001942 }
Chris Lattner212839c2008-02-20 23:17:35 +00001943 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001944 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001945 HandleDeprecatedAttribute(New, Attr);
1946 break;
1947 case AttributeList::AT_visibility:
1948 HandleVisibilityAttribute(New, Attr);
1949 break;
1950 case AttributeList::AT_weak:
1951 HandleWeakAttribute(New, Attr);
1952 break;
1953 case AttributeList::AT_dllimport:
1954 HandleDLLImportAttribute(New, Attr);
1955 break;
1956 case AttributeList::AT_dllexport:
1957 HandleDLLExportAttribute(New, Attr);
1958 break;
1959 case AttributeList::AT_nothrow:
1960 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001961 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001962 case AttributeList::AT_stdcall:
1963 HandleStdCallAttribute(New, Attr);
1964 break;
1965 case AttributeList::AT_fastcall:
1966 HandleFastCallAttribute(New, Attr);
1967 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001968 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001969 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001970 break;
1971 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001972 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001973 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001974 case AttributeList::AT_annotate:
1975 HandleAnnotateAttribute(New, Attr);
1976 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001977 case AttributeList::AT_noreturn:
1978 HandleNoReturnAttribute(New, Attr);
1979 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001980 case AttributeList::AT_format:
1981 HandleFormatAttribute(New, Attr);
1982 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001983 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001984#if 0
1985 // TODO: when we have the full set of attributes, warn about unknown ones.
1986 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1987 Attr->getName()->getName());
1988#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001989 break;
1990 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001991}
1992
1993void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1994 AttributeList *declarator_postfix) {
1995 while (declspec_prefix) {
1996 HandleDeclAttribute(New, declspec_prefix);
1997 declspec_prefix = declspec_prefix->getNext();
1998 }
1999 while (declarator_postfix) {
2000 HandleDeclAttribute(New, declarator_postfix);
2001 declarator_postfix = declarator_postfix->getNext();
2002 }
2003}
2004
Steve Naroffbea0b342007-07-29 16:33:31 +00002005void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2006 AttributeList *rawAttr) {
2007 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00002008 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00002009 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002010 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00002011 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002012 return;
Steve Naroff73322922007-07-18 18:00:27 +00002013 }
2014 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2015 llvm::APSInt vecSize(32);
2016 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002017 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002018 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002019 return;
Steve Naroff73322922007-07-18 18:00:27 +00002020 }
2021 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2022 // in conjunction with complex types (pointers, arrays, functions, etc.).
2023 Type *canonType = curType.getCanonicalType().getTypePtr();
2024 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002025 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00002026 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002027 return;
Steve Naroff73322922007-07-18 18:00:27 +00002028 }
2029 // unlike gcc's vector_size attribute, the size is specified as the
2030 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002031 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002032
2033 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002034 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00002035 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002036 return;
Steve Naroff73322922007-07-18 18:00:27 +00002037 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002038 // Instantiate/Install the vector type, the number of elements is > 0.
2039 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2040 // Remember this typedef decl, we will need it later for diagnostics.
2041 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002042}
2043
Reid Spencer5f016e22007-07-11 17:01:13 +00002044QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002045 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 // check the attribute arugments.
2047 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002048 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 std::string("1"));
2050 return QualType();
2051 }
2052 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2053 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002054 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002055 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002056 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 return QualType();
2058 }
2059 // navigate to the base type - we need to provide for vector pointers,
2060 // vector arrays, and functions returning vectors.
2061 Type *canonType = curType.getCanonicalType().getTypePtr();
2062
Steve Naroff73322922007-07-18 18:00:27 +00002063 if (canonType->isPointerType() || canonType->isArrayType() ||
2064 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00002065 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00002066 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2067 do {
2068 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2069 canonType = PT->getPointeeType().getTypePtr();
2070 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2071 canonType = AT->getElementType().getTypePtr();
2072 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2073 canonType = FT->getResultType().getTypePtr();
2074 } while (canonType->isPointerType() || canonType->isArrayType() ||
2075 canonType->isFunctionType());
2076 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002077 }
2078 // the base type must be integer or float.
2079 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00002080 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 curType.getCanonicalType().getAsString());
2082 return QualType();
2083 }
Chris Lattner98be4942008-03-05 18:54:05 +00002084 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00002085 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002086 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002087
2088 // the vector size needs to be an integral multiple of the type size.
2089 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00002090 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 sizeExpr->getSourceRange());
2092 return QualType();
2093 }
2094 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002095 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 sizeExpr->getSourceRange());
2097 return QualType();
2098 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00002099 // Instantiate the vector type, the number of elements is > 0, and not
2100 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00002101 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002102}
2103
Chris Lattner2070d802008-02-20 23:25:22 +00002104void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00002105 // check the attribute arguments.
2106 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00002107 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002108 std::string("0"));
2109 return;
2110 }
2111
2112 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2113 TD->addAttr(new PackedAttr);
2114 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2115 // If the alignment is less than or equal to 8 bits, the packed attribute
2116 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002117 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002118 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002119 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002120 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002121 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002122 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002123 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002124 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2125 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002126}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002127
Ted Kremenekaecb3832008-02-27 20:43:06 +00002128void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2129 // check the attribute arguments.
2130 if (rawAttr->getNumArgs() != 0) {
2131 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2132 std::string("0"));
2133 return;
2134 }
2135
Ted Kremenek3465fb32008-03-03 16:52:27 +00002136 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2137
2138 if (!Fn) {
2139 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2140 "noreturn", "function");
2141 return;
2142 }
2143
Ted Kremenekaecb3832008-02-27 20:43:06 +00002144 d->addAttr(new NoReturnAttr());
2145}
2146
Chris Lattnerddee4232008-03-03 03:28:21 +00002147void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2148 // check the attribute arguments.
2149 if (rawAttr->getNumArgs() != 0) {
2150 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2151 std::string("0"));
2152 return;
2153 }
2154
2155 d->addAttr(new DeprecatedAttr());
2156}
2157
2158void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2159 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002160 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002161 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2162 std::string("1"));
2163 return;
2164 }
2165
Chris Lattner7b937ae2008-03-04 18:08:48 +00002166 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2167 Arg = Arg->IgnoreParenCasts();
2168 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2169
2170 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002171 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002172 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002173 return;
2174 }
2175
Chris Lattner7b937ae2008-03-04 18:08:48 +00002176 const char *TypeStr = Str->getStrData();
2177 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002178 llvm::GlobalValue::VisibilityTypes type;
2179
Chris Lattner7b937ae2008-03-04 18:08:48 +00002180 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002181 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002182 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002183 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002184 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002185 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002186 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002187 type = llvm::GlobalValue::ProtectedVisibility;
2188 else {
2189 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002190 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002191 return;
2192 }
2193
2194 d->addAttr(new VisibilityAttr(type));
2195}
2196
2197void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2198 // check the attribute arguments.
2199 if (rawAttr->getNumArgs() != 0) {
2200 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2201 std::string("0"));
2202 return;
2203 }
2204
2205 d->addAttr(new WeakAttr());
2206}
2207
2208void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2209 // check the attribute arguments.
2210 if (rawAttr->getNumArgs() != 0) {
2211 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2212 std::string("0"));
2213 return;
2214 }
2215
2216 d->addAttr(new DLLImportAttr());
2217}
2218
2219void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2220 // check the attribute arguments.
2221 if (rawAttr->getNumArgs() != 0) {
2222 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2223 std::string("0"));
2224 return;
2225 }
2226
2227 d->addAttr(new DLLExportAttr());
2228}
2229
Nate Begeman440b4562008-03-07 20:04:22 +00002230void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2231 // check the attribute arguments.
2232 if (rawAttr->getNumArgs() != 0) {
2233 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2234 std::string("0"));
2235 return;
2236 }
2237
2238 d->addAttr(new StdCallAttr());
2239}
2240
2241void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2242 // check the attribute arguments.
2243 if (rawAttr->getNumArgs() != 0) {
2244 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2245 std::string("0"));
2246 return;
2247 }
2248
2249 d->addAttr(new FastCallAttr());
2250}
2251
Chris Lattnerddee4232008-03-03 03:28:21 +00002252void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2253 // check the attribute arguments.
2254 if (rawAttr->getNumArgs() != 0) {
2255 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2256 std::string("0"));
2257 return;
2258 }
2259
2260 d->addAttr(new NoThrowAttr());
2261}
2262
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002263static const FunctionTypeProto *getFunctionProto(Decl *d) {
2264 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2265 if (!decl) return 0;
2266
2267 QualType Ty = decl->getType();
2268
2269 if (Ty->isFunctionPointerType()) {
2270 const PointerType *PtrTy = Ty->getAsPointerType();
2271 Ty = PtrTy->getPointeeType();
2272 }
2273
2274 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2275 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2276
2277 return 0;
2278}
2279
2280
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002281/// Handle __attribute__((format(type,idx,firstarg))) attributes
2282/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002283void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2284
2285 if (!rawAttr->getParameterName()) {
2286 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2287 "format", std::string("1"));
2288 return;
2289 }
2290
2291 if (rawAttr->getNumArgs() != 2) {
2292 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2293 std::string("3"));
2294 return;
2295 }
2296
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002297 // GCC ignores the format attribute on K&R style function
2298 // prototypes, so we ignore it as well
2299 const FunctionTypeProto *proto = getFunctionProto(d);
2300
2301 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002302 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2303 "format", "function");
2304 return;
2305 }
2306
2307 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002308 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002309 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002310 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002311 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002312
2313 const char *Format = rawAttr->getParameterName()->getName();
2314 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2315
2316 // Normalize the argument, __foo__ becomes foo.
2317 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2318 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2319 Format += 2;
2320 FormatLen -= 4;
2321 }
2322
2323 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2324 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2325 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2326 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2327 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2328 "format", rawAttr->getParameterName()->getName());
2329 return;
2330 }
2331
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002332 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002333 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002334 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002335 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2336 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2337 "format", std::string("2"), IdxExpr->getSourceRange());
2338 return;
2339 }
2340
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002341 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002342 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2343 "format", std::string("2"), IdxExpr->getSourceRange());
2344 return;
2345 }
2346
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002347 // make sure the format string is really a string
2348 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2349 if (!Ty->isPointerType() ||
2350 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2351 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2352 IdxExpr->getSourceRange());
2353 return;
2354 }
2355
2356
2357 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002358 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002359 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002360 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2361 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2362 "format", std::string("3"), FirstArgExpr->getSourceRange());
2363 return;
2364 }
2365
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002366 // check if the function is variadic if the 3rd argument non-zero
2367 if (FirstArg != 0) {
2368 if (proto->isVariadic()) {
2369 ++NumArgs; // +1 for ...
2370 } else {
2371 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2372 return;
2373 }
2374 }
2375
2376 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2377 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002378 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002379 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002380 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2381 FirstArgExpr->getSourceRange());
2382 return;
2383 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002384 // if 0 it disables parameter checking (to use with e.g. va_list)
2385 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002386 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2387 "format", std::string("3"), FirstArgExpr->getSourceRange());
2388 return;
2389 }
2390
2391 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2392 Idx.getZExtValue(), FirstArg.getZExtValue()));
2393}
2394
Nate Begemanc398f0b2008-02-21 19:30:49 +00002395void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2396 // check the attribute arguments.
2397 if (rawAttr->getNumArgs() != 1) {
2398 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2399 std::string("1"));
2400 return;
2401 }
2402 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2403 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002404
Nate Begemanc398f0b2008-02-21 19:30:49 +00002405 // Make sure that there is a string literal as the annotation's single
2406 // argument.
2407 if (!SE) {
2408 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2409 return;
2410 }
2411 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2412 SE->getByteLength())));
2413}
2414
Anders Carlsson78aaae92007-12-19 07:19:40 +00002415void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2416{
2417 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002418 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002419 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002420 std::string("1"));
2421 return;
2422 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002423
Anders Carlsson042c4e72008-02-16 19:51:27 +00002424 unsigned Align = 0;
2425
2426 if (rawAttr->getNumArgs() == 0) {
2427 // FIXME: This should be the target specific maximum alignment.
2428 // (For now we just use 128 bits which is the maximum on X86.
2429 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002430 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002431 } else {
2432 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2433 llvm::APSInt alignment(32);
2434 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002435 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002436 "aligned", alignmentExpr->getSourceRange());
2437 return;
2438 }
2439
2440 Align = alignment.getZExtValue() * 8;
2441 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002442
Anders Carlsson042c4e72008-02-16 19:51:27 +00002443 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002444}