blob: 6d41fce555225c00e8380466851ffd99ab3728fe [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
Anders Carlsson3f70c542008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Chris Lattner4b009652007-07-25 00:24:17 +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"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000033using namespace clang;
34
Steve Naroff6384a012008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
Douglas Gregor1d661552008-04-13 21:07:44 +000038 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
39 isa<ObjCInterfaceDecl>(IIDecl) ||
40 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000041 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000042 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
Chris Lattnerf3874bc2008-04-06 04:47:34 +000045void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattnereee57c02008-04-04 06:12:32 +000046 assert(CD->getParent() == CurContext &&
Chris Lattnerf3874bc2008-04-06 04:47:34 +000047 "The next DeclContext should be directly contained in the current one.");
Chris Lattnereee57c02008-04-04 06:12:32 +000048 CurContext = CD;
49}
50
Chris Lattnerf3874bc2008-04-06 04:47:34 +000051void Sema::PopDeclContext() {
52 assert(CurContext && "DeclContext imbalance!");
Chris Lattnereee57c02008-04-04 06:12:32 +000053 CurContext = CurContext->getParent();
54}
55
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000056/// Add this decl to the scope shadowed decl chains.
57void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
58 IdResolver.AddDecl(D, S);
59 S->AddDecl(D);
60}
61
Steve Naroff9637a9b2007-10-09 22:01:59 +000062void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000063 if (S->decl_empty()) return;
64 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
65
Chris Lattner4b009652007-07-25 00:24:17 +000066 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
67 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000068 Decl *TmpD = static_cast<Decl*>(*I);
69 assert(TmpD && "This decl didn't get pushed??");
70 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
71 assert(D && "This decl isn't a ScopedDecl?");
72
Chris Lattner4b009652007-07-25 00:24:17 +000073 IdentifierInfo *II = D->getIdentifier();
74 if (!II) continue;
75
Chris Lattner2a1e2ed2008-04-11 07:00:53 +000076 // Unlink this decl from the identifier.
77 IdResolver.RemoveDecl(D);
78
Chris Lattner4b009652007-07-25 00:24:17 +000079 // This will have to be revisited for C++: there we want to nest stuff in
80 // namespace decls etc. Even for C, we might want a top-level translation
81 // unit decl or something.
82 if (!CurFunctionDecl)
83 continue;
84
85 // Chain this decl to the containing function, it now owns the memory for
86 // the decl.
87 D->setNext(CurFunctionDecl->getDeclChain());
88 CurFunctionDecl->setDeclChain(D);
89 }
90}
91
Steve Naroffe57c21a2008-04-01 23:04:06 +000092/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
93/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +000094ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +000095 // The third "scope" argument is 0 since we aren't enabling lazy built-in
96 // creation from this context.
97 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000098
Steve Naroff6384a012008-04-02 14:35:35 +000099 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000100}
101
Steve Naroffe57c21a2008-04-01 23:04:06 +0000102/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000103/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000104Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
105 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000106 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000107 unsigned NS = NSI;
108 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
109 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000110
Chris Lattner4b009652007-07-25 00:24:17 +0000111 // Scan up the scope chain looking for a decl that matches this identifier
112 // that is in the appropriate namespace. This search should not take long, as
113 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000114 NamedDecl *ND = IdResolver.Lookup(II, NS);
115 if (ND) return ND;
116
Chris Lattner4b009652007-07-25 00:24:17 +0000117 // If we didn't find a use of this identifier, and if the identifier
118 // corresponds to a compiler builtin, create the decl object for the builtin
119 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000120 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000121 if (enableLazyBuiltinCreation) {
122 // If this is a builtin on this (or all) targets, create the decl.
123 if (unsigned BuiltinID = II->getBuiltinID())
124 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
125 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000126 if (getLangOptions().ObjC1) {
127 // @interface and @compatibility_alias introduce typedef-like names.
128 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000129 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000130 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000131 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
132 if (IDI != ObjCInterfaceDecls.end())
133 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000134 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
135 if (I != ObjCAliasDecls.end())
136 return I->second->getClassInterface();
137 }
Chris Lattner4b009652007-07-25 00:24:17 +0000138 }
139 return 0;
140}
141
Anders Carlsson36760332007-10-15 20:28:48 +0000142void Sema::InitBuiltinVaListType()
143{
144 if (!Context.getBuiltinVaListType().isNull())
145 return;
146
147 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000148 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000149 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000150 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
151}
152
Chris Lattner4b009652007-07-25 00:24:17 +0000153/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
154/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000155ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
156 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000157 Builtin::ID BID = (Builtin::ID)bid;
158
Anders Carlsson36760332007-10-15 20:28:48 +0000159 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000160 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000161 BID == Builtin::BI__builtin_va_end)
162 InitBuiltinVaListType();
163
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000164 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattnereee57c02008-04-04 06:12:32 +0000165 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
166 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000167 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000168
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000169 // TUScope is the translation-unit scope to insert this function into.
170 TUScope->AddDecl(New);
Chris Lattner4b009652007-07-25 00:24:17 +0000171
172 // Add this decl to the end of the identifier info.
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000173 IdResolver.AddGlobalDecl(New);
174
Chris Lattner4b009652007-07-25 00:24:17 +0000175 return New;
176}
177
178/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
179/// and scope as a previous declaration 'Old'. Figure out how to resolve this
180/// situation, merging decls or emitting diagnostics as appropriate.
181///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000182TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000183 // Verify the old decl was also a typedef.
184 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
185 if (!Old) {
186 Diag(New->getLocation(), diag::err_redefinition_different_kind,
187 New->getName());
188 Diag(OldD->getLocation(), diag::err_previous_definition);
189 return New;
190 }
191
Steve Naroffae84af82007-10-31 18:42:27 +0000192 // Allow multiple definitions for ObjC built-in typedefs.
193 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000194 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000195 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000196
197 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
198 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
199 // *either* declaration is in a system header. The code below implements
200 // this adhoc compatibility rule. FIXME: The following code will not
201 // work properly when compiling ".i" files (containing preprocessed output).
202 SourceManager &SrcMgr = Context.getSourceManager();
203 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
204 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
205 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
206 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
207 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
208
Steve Naroff1997d2c2008-03-26 21:27:00 +0000209 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
210 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
211 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroff73a07032008-02-07 03:50:06 +0000212 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000213 return New;
Steve Naroff1997d2c2008-03-26 21:27:00 +0000214
Chris Lattner4b009652007-07-25 00:24:17 +0000215 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
216 // TODO: This is totally simplistic. It should handle merging functions
217 // together etc, merging extern int X; int X; ...
218 Diag(New->getLocation(), diag::err_redefinition, New->getName());
219 Diag(Old->getLocation(), diag::err_previous_definition);
220 return New;
221}
222
Chris Lattner402b3372008-03-03 03:28:21 +0000223/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
224static bool DeclHasAttr(const Decl *decl, const Attr *target) {
225 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
226 if (attr->getKind() == target->getKind())
227 return true;
228
229 return false;
230}
231
232/// MergeAttributes - append attributes from the Old decl to the New one.
233static void MergeAttributes(Decl *New, Decl *Old) {
234 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
235
236// FIXME: fix this code to cleanup the Old attrs correctly
237 while (attr) {
238 tmp = attr;
239 attr = attr->getNext();
240
241 if (!DeclHasAttr(New, tmp)) {
242 New->addAttr(tmp);
243 } else {
244 tmp->setNext(0);
245 delete(tmp);
246 }
247 }
248}
249
Chris Lattner3e254fb2008-04-08 04:40:51 +0000250/// MergeFunctionDecl - We just parsed a function 'New' from
251/// declarator D which has the same name and scope as a previous
252/// declaration 'Old'. Figure out how to resolve this situation,
253/// merging decls or emitting diagnostics as appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000254///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000255FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000256 // Verify the old decl was also a function.
257 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
258 if (!Old) {
259 Diag(New->getLocation(), diag::err_redefinition_different_kind,
260 New->getName());
261 Diag(OldD->getLocation(), diag::err_previous_definition);
262 return New;
263 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000264
Chris Lattner402b3372008-03-03 03:28:21 +0000265 MergeAttributes(New, Old);
266
Chris Lattner42a21742008-04-06 23:10:54 +0000267 QualType OldQType = Context.getCanonicalType(Old->getType());
268 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000269
Chris Lattner3e254fb2008-04-08 04:40:51 +0000270 // C++ [dcl.fct]p3:
271 // All declarations for a function shall agree exactly in both the
272 // return type and the parameter-type-list.
273 if (getLangOptions().CPlusPlus && OldQType == NewQType)
274 return MergeCXXFunctionDecl(New, Old);
275
276 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000277 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000278 if (!getLangOptions().CPlusPlus &&
279 Context.functionTypesAreCompatible(OldQType, NewQType)) {
Steve Naroff1d5bd642008-01-14 20:51:29 +0000280 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000281 }
Chris Lattner1470b072007-11-06 06:07:26 +0000282
Steve Naroff6c9e7922008-01-16 15:01:34 +0000283 // A function that has already been declared has been redeclared or defined
284 // with a different type- show appropriate diagnostic
Steve Naroff9104f3c2008-04-04 14:32:09 +0000285 diag::kind PrevDiag;
286 if (Old->getBody())
287 PrevDiag = diag::err_previous_definition;
288 else if (Old->isImplicit())
289 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000290 else
Steve Naroff9104f3c2008-04-04 14:32:09 +0000291 PrevDiag = diag::err_previous_declaration;
Steve Naroff6c9e7922008-01-16 15:01:34 +0000292
Chris Lattner4b009652007-07-25 00:24:17 +0000293 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
294 // TODO: This is totally simplistic. It should handle merging functions
295 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000296 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
297 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000298 return New;
299}
300
Chris Lattnerf9167d12007-11-06 04:28:31 +0000301/// equivalentArrayTypes - Used to determine whether two array types are
302/// equivalent.
303/// We need to check this explicitly as an incomplete array definition is
304/// considered a VariableArrayType, so will not match a complete array
305/// definition that would be otherwise equivalent.
306static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
307 const ArrayType *NewAT = NewQType->getAsArrayType();
308 const ArrayType *OldAT = OldQType->getAsArrayType();
309
310 if (!NewAT || !OldAT)
311 return false;
312
313 // If either (or both) array types in incomplete we need to strip off the
314 // outer VariableArrayType. Once the outer VAT is removed the remaining
315 // types must be identical if the array types are to be considered
316 // equivalent.
317 // eg. int[][1] and int[1][1] become
318 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
319 // removing the outermost VAT gives
320 // CAT(1, int) and CAT(1, int)
321 // which are equal, therefore the array types are equivalent.
Eli Friedmane0079792008-02-15 12:53:51 +0000322 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerf9167d12007-11-06 04:28:31 +0000323 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
324 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000325 NewQType = NewAT->getElementType().getCanonicalType();
326 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000327 }
328
329 return NewQType == OldQType;
330}
331
Chris Lattner4b009652007-07-25 00:24:17 +0000332/// MergeVarDecl - We just parsed a variable 'New' which has the same name
333/// and scope as a previous declaration 'Old'. Figure out how to resolve this
334/// situation, merging decls or emitting diagnostics as appropriate.
335///
336/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
337/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
338///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000339VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000340 // Verify the old decl was also a variable.
341 VarDecl *Old = dyn_cast<VarDecl>(OldD);
342 if (!Old) {
343 Diag(New->getLocation(), diag::err_redefinition_different_kind,
344 New->getName());
345 Diag(OldD->getLocation(), diag::err_previous_definition);
346 return New;
347 }
Chris Lattner402b3372008-03-03 03:28:21 +0000348
349 MergeAttributes(New, Old);
350
Chris Lattner4b009652007-07-25 00:24:17 +0000351 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000352 QualType OldCType = Context.getCanonicalType(Old->getType());
353 QualType NewCType = Context.getCanonicalType(New->getType());
354 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000355 Diag(New->getLocation(), diag::err_redefinition, New->getName());
356 Diag(Old->getLocation(), diag::err_previous_definition);
357 return New;
358 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000359 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
360 if (New->getStorageClass() == VarDecl::Static &&
361 (Old->getStorageClass() == VarDecl::None ||
362 Old->getStorageClass() == VarDecl::Extern)) {
363 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
364 Diag(Old->getLocation(), diag::err_previous_definition);
365 return New;
366 }
367 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
368 if (New->getStorageClass() != VarDecl::Static &&
369 Old->getStorageClass() == VarDecl::Static) {
370 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
371 Diag(Old->getLocation(), diag::err_previous_definition);
372 return New;
373 }
374 // We've verified the types match, now handle "tentative" definitions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000375 if (Old->isFileVarDecl() && New->isFileVarDecl()) {
Steve Naroffb00247f2008-01-30 00:44:01 +0000376 // Handle C "tentative" external object definitions (C99 6.9.2).
377 bool OldIsTentative = false;
378 bool NewIsTentative = false;
379
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000380 if (!Old->getInit() &&
381 (Old->getStorageClass() == VarDecl::None ||
382 Old->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000383 OldIsTentative = true;
384
385 // FIXME: this check doesn't work (since the initializer hasn't been
386 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
387 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
388 // thrown out the old decl.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000389 if (!New->getInit() &&
390 (New->getStorageClass() == VarDecl::None ||
391 New->getStorageClass() == VarDecl::Static))
Steve Naroffb00247f2008-01-30 00:44:01 +0000392 ; // change to NewIsTentative = true; once the code is moved.
393
394 if (NewIsTentative || OldIsTentative)
395 return New;
396 }
397 if (Old->getStorageClass() != VarDecl::Extern &&
398 New->getStorageClass() != VarDecl::Extern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000399 Diag(New->getLocation(), diag::err_redefinition, New->getName());
400 Diag(Old->getLocation(), diag::err_previous_definition);
401 }
402 return New;
403}
404
Chris Lattner3e254fb2008-04-08 04:40:51 +0000405/// CheckParmsForFunctionDef - Check that the parameters of the given
406/// function are appropriate for the definition of a function. This
407/// takes care of any checks that cannot be performed on the
408/// declaration itself, e.g., that the types of each of the function
409/// parameters are complete.
410bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
411 bool HasInvalidParm = false;
412 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
413 ParmVarDecl *Param = FD->getParamDecl(p);
414
415 // C99 6.7.5.3p4: the parameters in a parameter type list in a
416 // function declarator that is part of a function definition of
417 // that function shall not have incomplete type.
418 if (Param->getType()->isIncompleteType() &&
419 !Param->isInvalidDecl()) {
420 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
421 Param->getType().getAsString());
422 Param->setInvalidDecl();
423 HasInvalidParm = true;
424 }
425 }
426
427 return HasInvalidParm;
428}
429
430/// CreateImplicitParameter - Creates an implicit function parameter
431/// in the scope S and with the given type. This routine is used, for
432/// example, to create the implicit "self" parameter in an Objective-C
433/// method.
434ParmVarDecl *
435Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
436 SourceLocation IdLoc, QualType Type) {
437 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
438 VarDecl::None, 0, 0);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000439 if (Id)
440 PushOnScopeChains(New, S);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000441
442 return New;
443}
444
Chris Lattner4b009652007-07-25 00:24:17 +0000445/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
446/// no declarator (e.g. "struct foo;") is parsed.
447Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
448 // TODO: emit error on 'int;' or 'const enum foo;'.
449 // TODO: emit error on 'typedef int;'
450 // if (!DS.isMissingDeclaratorOk()) Diag(...);
451
Steve Naroffedafc0b2007-11-17 21:37:36 +0000452 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000453}
454
Steve Narofff0b23542008-01-10 22:15:12 +0000455bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000456 // Get the type before calling CheckSingleAssignmentConstraints(), since
457 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000458 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000459
Chris Lattner005ed752008-01-04 18:04:52 +0000460 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
461 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
462 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000463}
464
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000465bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000466 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000467 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000468 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000469 return true; // types weren't compatible.
470
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000471 if (savExpr != expr) // The type was promoted, update initializer list.
472 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000473 return false;
474}
475
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000476bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedman8ff07782008-02-15 18:16:39 +0000477 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000478 // C99 6.7.8p14. We have an array of character type with unknown size
479 // being initialized to a string literal.
480 llvm::APSInt ConstVal(32);
481 ConstVal = strLiteral->getByteLength() + 1;
482 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000483 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000484 ArrayType::Normal, 0);
485 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
486 // C99 6.7.8p14. We have an array of character type with known size.
487 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
488 Diag(strLiteral->getSourceRange().getBegin(),
489 diag::warn_initializer_string_for_char_array_too_long,
490 strLiteral->getSourceRange());
491 } else {
492 assert(0 && "HandleStringLiteralInit(): Invalid array type");
493 }
494 // Set type from "char *" to "constant array of char".
495 strLiteral->setType(DeclT);
496 // For now, we always return false (meaning success).
497 return false;
498}
499
500StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000501 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000502 if (AT && AT->getElementType()->isCharType()) {
503 return dyn_cast<StringLiteral>(Init);
504 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000505 return 0;
506}
507
Steve Narofff3cb5142008-01-25 00:51:06 +0000508// CheckInitializerListTypes - Checks the types of elements of an initializer
509// list. This function is recursive: it calls itself to initialize subelements
510// of aggregate types. Note that the topLevel parameter essentially refers to
511// whether this expression "owns" the initializer list passed in, or if this
512// initialization is taking elements out of a parent initializer. Each
513// call to this function adds zero or more to startIndex, reports any errors,
514// and returns true if it found any inconsistent types.
515bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
516 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000517 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000518
519 if (DeclType->isScalarType()) {
520 // The simplest case: initializing a single scalar
521 if (topLevel) {
522 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
523 IList->getSourceRange());
524 }
525 if (startIndex < IList->getNumInits()) {
526 Expr* expr = IList->getInit(startIndex);
527 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
528 // FIXME: Should an error be reported here instead?
529 unsigned newIndex = 0;
530 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
531 } else {
532 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
533 }
534 ++startIndex;
535 }
536 // FIXME: Should an error be reported for empty initializer list + scalar?
537 } else if (DeclType->isVectorType()) {
538 if (startIndex < IList->getNumInits()) {
539 const VectorType *VT = DeclType->getAsVectorType();
540 int maxElements = VT->getNumElements();
541 QualType elementType = VT->getElementType();
542
543 for (int i = 0; i < maxElements; ++i) {
544 // Don't attempt to go past the end of the init list
545 if (startIndex >= IList->getNumInits())
546 break;
547 Expr* expr = IList->getInit(startIndex);
548 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
549 unsigned newIndex = 0;
550 hadError |= CheckInitializerListTypes(SubInitList, elementType,
551 true, newIndex);
552 ++startIndex;
553 } else {
554 hadError |= CheckInitializerListTypes(IList, elementType,
555 false, startIndex);
556 }
557 }
558 }
559 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
560 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000561 if (startIndex < IList->getNumInits() && !topLevel &&
562 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
563 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000564 // We found a compatible struct; per the standard, this initializes the
565 // struct. (The C standard technically says that this only applies for
566 // initializers for declarations with automatic scope; however, this
567 // construct is unambiguous anyway because a struct cannot contain
568 // a type compatible with itself. We'll output an error when we check
569 // if the initializer is constant.)
570 // FIXME: Is a call to CheckSingleInitializer required here?
571 ++startIndex;
572 } else {
573 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000574
Steve Naroff576df292008-02-11 21:52:37 +0000575 // If the record is invalid, some of it's members are invalid. To avoid
576 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffee467032008-02-11 00:06:17 +0000577 if (structDecl->isInvalidDecl())
578 return true;
579
Steve Narofff3cb5142008-01-25 00:51:06 +0000580 // If structDecl is a forward declaration, this loop won't do anything;
581 // That's okay, because an error should get printed out elsewhere. It
582 // might be worthwhile to skip over the rest of the initializer, though.
583 int numMembers = structDecl->getNumMembers() -
584 structDecl->hasFlexibleArrayMember();
585 for (int i = 0; i < numMembers; i++) {
586 // Don't attempt to go past the end of the init list
587 if (startIndex >= IList->getNumInits())
588 break;
589 FieldDecl * curField = structDecl->getMember(i);
590 if (!curField->getIdentifier()) {
591 // Don't initialize unnamed fields, e.g. "int : 20;"
592 continue;
593 }
594 QualType fieldType = curField->getType();
595 Expr* expr = IList->getInit(startIndex);
596 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
597 unsigned newStart = 0;
598 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
599 true, newStart);
600 ++startIndex;
601 } else {
602 hadError |= CheckInitializerListTypes(IList, fieldType,
603 false, startIndex);
604 }
605 if (DeclType->isUnionType())
606 break;
607 }
608 // FIXME: Implement flexible array initialization GCC extension (it's a
609 // really messy extension to implement, unfortunately...the necessary
610 // information isn't actually even here!)
611 }
612 } else if (DeclType->isArrayType()) {
613 // Check for the special-case of initializing an array with a string.
614 if (startIndex < IList->getNumInits()) {
615 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
616 DeclType)) {
617 CheckStringLiteralInit(lit, DeclType);
618 ++startIndex;
619 if (topLevel && startIndex < IList->getNumInits()) {
620 // We have leftover initializers; warn
621 Diag(IList->getInit(startIndex)->getLocStart(),
622 diag::err_excess_initializers_in_char_array_initializer,
623 IList->getInit(startIndex)->getSourceRange());
624 }
625 return false;
626 }
627 }
628 int maxElements;
Eli Friedman8ff07782008-02-15 18:16:39 +0000629 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000630 // FIXME: use a proper constant
631 maxElements = 0x7FFFFFFF;
Chris Lattnerb9716a62008-02-20 23:17:35 +0000632 } else if (const VariableArrayType *VAT =
633 DeclType->getAsVariableArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000634 // Check for VLAs; in standard C it would be possible to check this
635 // earlier, but I don't know where clang accepts VLAs (gcc accepts
636 // them in all sorts of strange places).
Eli Friedman8ff07782008-02-15 18:16:39 +0000637 Diag(VAT->getSizeExpr()->getLocStart(),
638 diag::err_variable_object_no_init,
639 VAT->getSizeExpr()->getSourceRange());
640 hadError = true;
641 maxElements = 0x7FFFFFFF;
Steve Narofff3cb5142008-01-25 00:51:06 +0000642 } else {
643 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
644 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
645 }
646 QualType elementType = DeclType->getAsArrayType()->getElementType();
647 int numElements = 0;
648 for (int i = 0; i < maxElements; ++i, ++numElements) {
649 // Don't attempt to go past the end of the init list
650 if (startIndex >= IList->getNumInits())
651 break;
652 Expr* expr = IList->getInit(startIndex);
653 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
654 unsigned newIndex = 0;
655 hadError |= CheckInitializerListTypes(SubInitList, elementType,
656 true, newIndex);
657 ++startIndex;
658 } else {
659 hadError |= CheckInitializerListTypes(IList, elementType,
660 false, startIndex);
661 }
662 }
Eli Friedmane0079792008-02-15 12:53:51 +0000663 if (DeclType->isIncompleteArrayType()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000664 // If this is an incomplete array type, the actual type needs to
665 // be calculated here
666 if (numElements == 0) {
667 // Sizing an array implicitly to zero is not allowed
668 // (It could in theory be allowed, but it doesn't really matter.)
669 Diag(IList->getLocStart(),
670 diag::err_at_least_one_initializer_needed_to_size_array);
671 hadError = true;
672 } else {
673 llvm::APSInt ConstVal(32);
674 ConstVal = numElements;
675 DeclType = Context.getConstantArrayType(elementType, ConstVal,
676 ArrayType::Normal, 0);
677 }
678 }
679 } else {
680 assert(0 && "Aggregate that isn't a function or array?!");
681 }
682 } else {
683 // In C, all types are either scalars or aggregates, but
684 // additional handling is needed here for C++ (and possibly others?).
685 assert(0 && "Unsupported initializer type");
686 }
687
688 // If this init list is a base list, we set the type; an initializer doesn't
689 // fundamentally have a type, but this makes the ASTs a bit easier to read
690 if (topLevel)
691 IList->setType(DeclType);
692
693 if (topLevel && startIndex < IList->getNumInits()) {
694 // We have leftover initializers; warn
695 Diag(IList->getInit(startIndex)->getLocStart(),
696 diag::warn_excess_initializers,
697 IList->getInit(startIndex)->getSourceRange());
698 }
699 return hadError;
700}
701
702bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000703 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
704 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedman8ff07782008-02-15 18:16:39 +0000705 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroff8e9337f2008-01-21 23:53:58 +0000706 return Diag(VAT->getSizeExpr()->getLocStart(),
707 diag::err_variable_object_no_init,
708 VAT->getSizeExpr()->getSourceRange());
709
Steve Naroffcb69fb72007-12-10 22:44:33 +0000710 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
711 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000712 // FIXME: Handle wide strings
713 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
714 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000715
716 if (DeclType->isArrayType())
717 return Diag(Init->getLocStart(),
718 diag::err_array_init_list_required,
719 Init->getSourceRange());
720
Steve Narofff0b23542008-01-10 22:15:12 +0000721 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000722 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000723 unsigned newIndex = 0;
724 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000725}
726
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000727Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000728Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000729 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000730 IdentifierInfo *II = D.getIdentifier();
731
732 // All of these full declarators require an identifier. If it doesn't have
733 // one, the ParsedFreeStandingDeclSpec action should be used.
734 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000735 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000736 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000737 D.getDeclSpec().getSourceRange(), D.getSourceRange());
738 return 0;
739 }
740
Chris Lattnera7549902007-08-26 06:24:45 +0000741 // The scope passed in may not be a decl scope. Zip up the scope tree until
742 // we find one that is.
743 while ((S->getFlags() & Scope::DeclScope) == 0)
744 S = S->getParent();
745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000747 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000748 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000749 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000750
751 // In C++, the previous declaration we find might be a tag type
752 // (class or enum). In this case, the new declaration will hide the
753 // tag type.
754 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
755 PrevDecl = 0;
756
Chris Lattner82bb4792007-11-14 06:34:38 +0000757 QualType R = GetTypeForDeclarator(D, S);
758 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
759
Chris Lattner4b009652007-07-25 00:24:17 +0000760 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000761 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000762 if (!NewTD) return 0;
763
764 // Handle attributes prior to checking for duplicates in MergeVarDecl
765 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
766 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000767 // Merge the decl with the existing one if appropriate. If the decl is
768 // in an outer scope, it isn't the same thing.
769 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000770 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
771 if (NewTD == 0) return 0;
772 }
773 New = NewTD;
774 if (S->getParent() == 0) {
775 // C99 6.7.7p2: If a typedef name specifies a variably modified type
776 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000777 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
778 // FIXME: Diagnostic needs to be fixed.
779 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000780 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000781 }
782 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000783 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000784 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000785 switch (D.getDeclSpec().getStorageClassSpec()) {
786 default: assert(0 && "Unknown storage class!");
787 case DeclSpec::SCS_auto:
788 case DeclSpec::SCS_register:
789 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
790 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000791 InvalidDecl = true;
792 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000793 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
794 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
795 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000796 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000797 }
798
Chris Lattner4c7802b2008-03-15 21:24:04 +0000799 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattnereee57c02008-04-04 06:12:32 +0000800 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
801 D.getIdentifierLoc(),
Chris Lattner4c7802b2008-03-15 21:24:04 +0000802 II, R, SC, isInline,
803 LastDeclarator);
Ted Kremenek117f1862008-02-27 22:18:07 +0000804 // Handle attributes.
Ted Kremenek117f1862008-02-27 22:18:07 +0000805 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
806 D.getAttributes());
Chris Lattner3e254fb2008-04-08 04:40:51 +0000807
808 // Copy the parameter declarations from the declarator D to
809 // the function declaration NewFD, if they are available.
810 if (D.getNumTypeObjects() > 0 &&
811 D.getTypeObject(0).Fun.hasPrototype) {
812 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
813
814 // Create Decl objects for each parameter, adding them to the
815 // FunctionDecl.
816 llvm::SmallVector<ParmVarDecl*, 16> Params;
817
818 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
819 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000820 // single void argument.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000821 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
822 FTI.ArgInfo[0].Param &&
823 !((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
824 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
825 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000826 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
827
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000828 // In C++, the empty parameter-type-list must be spelled "void"; a
829 // typedef of void is not permitted.
830 if (getLangOptions().CPlusPlus &&
Chris Lattner97316c02008-04-10 02:22:51 +0000831 Param->getType() != Context.VoidTy) {
832 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
833 }
834
Chris Lattner3e254fb2008-04-08 04:40:51 +0000835 } else {
836 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
837 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
838 }
839
840 NewFD->setParams(&Params[0], Params.size());
841 }
842
Steve Narofff8a09432008-01-09 23:34:55 +0000843 // Merge the decl with the existing one if appropriate. Since C functions
844 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000845 if (PrevDecl) {
846 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
847 if (NewFD == 0) return 0;
848 }
849 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000850
851 // In C++, check default arguments now that we have merged decls.
852 if (getLangOptions().CPlusPlus)
853 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000854 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000855 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000856 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
857 D.getIdentifier()->getName());
858 InvalidDecl = true;
859 }
Chris Lattner4b009652007-07-25 00:24:17 +0000860
861 VarDecl *NewVD;
862 VarDecl::StorageClass SC;
863 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +0000864 default: assert(0 && "Unknown storage class!");
865 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
866 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
867 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
868 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
869 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
870 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000871 }
872 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000873 // C99 6.9p2: The storage-class specifiers auto and register shall not
874 // appear in the declaration specifiers in an external declaration.
875 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
876 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
877 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000878 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000879 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000880 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
881 II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000882 } else {
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000883 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
884 II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000885 }
Chris Lattner4b009652007-07-25 00:24:17 +0000886 // Handle attributes prior to checking for duplicates in MergeVarDecl
887 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
888 D.getAttributes());
Nate Begemanea583262008-03-14 18:07:10 +0000889
890 // Emit an error if an address space was applied to decl with local storage.
891 // This includes arrays of objects with address space qualifiers, but not
892 // automatic variables that point to other address spaces.
893 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +0000894 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
895 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
896 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +0000897 }
Steve Narofff8a09432008-01-09 23:34:55 +0000898 // Merge the decl with the existing one if appropriate. If the decl is
899 // in an outer scope, it isn't the same thing.
900 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000901 NewVD = MergeVarDecl(NewVD, PrevDecl);
902 if (NewVD == 0) return 0;
903 }
Chris Lattner4b009652007-07-25 00:24:17 +0000904 New = NewVD;
905 }
906
907 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000908 if (II)
909 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000910 // If any semantic error occurred, mark the decl as invalid.
911 if (D.getInvalidType() || InvalidDecl)
912 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000913
914 return New;
915}
916
Steve Narofff0b23542008-01-10 22:15:12 +0000917bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
918 SourceLocation loc;
919 // FIXME: Remove the isReference check and handle assignment to a reference.
920 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
921 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
922 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
923 return true;
924 }
925 return false;
926}
927
Steve Naroff6a0e2092007-09-12 14:07:44 +0000928void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000929 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000930 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000931 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000932
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000933 // If there is no declaration, there was an error parsing it. Just ignore
934 // the initializer.
935 if (RealDecl == 0) {
936 delete Init;
937 return;
938 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000939
Steve Naroff420d0f52007-09-12 20:13:48 +0000940 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
941 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000942 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
943 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000944 RealDecl->setInvalidDecl();
945 return;
946 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000947 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000948 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000949 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000950 if (VDecl->isBlockVarDecl()) {
951 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000952 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000953 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000954 VDecl->setInvalidDecl();
955 } else if (!VDecl->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000956 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000957 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000958 if (SC == VarDecl::Static) // C99 6.7.8p4.
959 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000960 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000961 } else if (VDecl->isFileVarDecl()) {
962 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000963 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000964 if (!VDecl->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000965 if (CheckInitializerTypes(Init, DclT))
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000966 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000967
968 // C99 6.7.8p4. All file scoped initializers need to be constant.
969 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000970 }
971 // If the type changed, it means we had an incomplete type that was
972 // completed by the initializer. For example:
973 // int ary[] = { 1, 3, 5 };
974 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000975 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000976 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000977 Init->setType(DclT);
978 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000979
980 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000981 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000982 return;
983}
984
Chris Lattner4b009652007-07-25 00:24:17 +0000985/// The declarators are chained together backwards, reverse the list.
986Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
987 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000988 Decl *GroupDecl = static_cast<Decl*>(group);
989 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000990 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000991
992 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
993 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000994 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000995 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000996 else { // reverse the list.
997 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000998 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000999 Group->setNextDeclarator(NewGroup);
1000 NewGroup = Group;
1001 Group = Next;
1002 }
1003 }
1004 // Perform semantic analysis that depends on having fully processed both
1005 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001006 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001007 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1008 if (!IDecl)
1009 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001010 QualType T = IDecl->getType();
1011
1012 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1013 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001014 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1015 IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman70f414d2008-02-15 19:53:52 +00001016 if (T->getAsVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001017 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1018 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001019 }
1020 }
1021 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1022 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001023 if (IDecl->isBlockVarDecl() &&
1024 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001025 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001026 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1027 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001028 IDecl->setInvalidDecl();
1029 }
1030 }
1031 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1032 // object that has file scope without an initializer, and without a
1033 // storage-class specifier or with the storage-class specifier "static",
1034 // constitutes a tentative definition. Note: A tentative definition with
1035 // external linkage is valid (C99 6.2.2p5).
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001036 if (IDecl && !IDecl->getInit() &&
1037 (IDecl->getStorageClass() == VarDecl::Static ||
1038 IDecl->getStorageClass() == VarDecl::None)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001039 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001040 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1041 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001042 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001043 // C99 6.9.2p3: If the declaration of an identifier for an object is
1044 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1045 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001046 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1047 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001048 IDecl->setInvalidDecl();
1049 }
1050 }
Chris Lattner4b009652007-07-25 00:24:17 +00001051 }
1052 return NewGroup;
1053}
Steve Naroff91b03f72007-08-28 03:03:08 +00001054
Chris Lattner3e254fb2008-04-08 04:40:51 +00001055/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1056/// to introduce parameters into function prototype scope.
1057Sema::DeclTy *
1058Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
1059 DeclSpec &DS = D.getDeclSpec();
1060
1061 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
1062 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1063 DS.getStorageClassSpec() != DeclSpec::SCS_register) {
1064 Diag(DS.getStorageClassSpecLoc(),
1065 diag::err_invalid_storage_class_in_func_decl);
1066 DS.ClearStorageClassSpecs();
1067 }
1068 if (DS.isThreadSpecified()) {
1069 Diag(DS.getThreadSpecLoc(),
1070 diag::err_invalid_storage_class_in_func_decl);
1071 DS.ClearStorageClassSpecs();
1072 }
1073
1074
1075 // In this context, we *do not* check D.getInvalidType(). If the declarator
1076 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1077 // though it will not reflect the user specified type.
1078 QualType parmDeclType = GetTypeForDeclarator(D, S);
1079
1080 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1081
Chris Lattner4b009652007-07-25 00:24:17 +00001082 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1083 // Can this happen for params? We already checked that they don't conflict
1084 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001085 IdentifierInfo *II = D.getIdentifier();
1086 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1087 if (S->isDeclScope(PrevDecl)) {
1088 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1089 dyn_cast<NamedDecl>(PrevDecl)->getName());
1090
1091 // Recover by removing the name
1092 II = 0;
1093 D.SetIdentifier(0, D.getIdentifierLoc());
1094 }
Chris Lattner4b009652007-07-25 00:24:17 +00001095 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001096
1097 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1098 // Doing the promotion here has a win and a loss. The win is the type for
1099 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1100 // code generator). The loss is the orginal type isn't preserved. For example:
1101 //
1102 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1103 // int blockvardecl[5];
1104 // sizeof(parmvardecl); // size == 4
1105 // sizeof(blockvardecl); // size == 20
1106 // }
1107 //
1108 // For expressions, all implicit conversions are captured using the
1109 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1110 //
1111 // FIXME: If a source translation tool needs to see the original type, then
1112 // we need to consider storing both types (in ParmVarDecl)...
1113 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001114 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001115 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001116 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001117 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001118 parmDeclType = Context.getPointerType(parmDeclType);
1119
Chris Lattner3e254fb2008-04-08 04:40:51 +00001120 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1121 D.getIdentifierLoc(), II,
1122 parmDeclType, VarDecl::None,
1123 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001124
Chris Lattner3e254fb2008-04-08 04:40:51 +00001125 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001126 New->setInvalidDecl();
1127
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001128 if (II)
1129 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001130
Chris Lattner3e254fb2008-04-08 04:40:51 +00001131 HandleDeclAttributes(New, D.getAttributes(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001132 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001133
Chris Lattner4b009652007-07-25 00:24:17 +00001134}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001135
Chris Lattnerea148702007-10-09 17:14:05 +00001136Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001137 assert(CurFunctionDecl == 0 && "Function parsing confused");
1138 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1139 "Not a function declarator!");
1140 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001141
Chris Lattner4b009652007-07-25 00:24:17 +00001142 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1143 // for a K&R function.
1144 if (!FTI.hasPrototype) {
1145 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001146 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001147 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1148 FTI.ArgInfo[i].Ident->getName());
1149 // Implicitly declare the argument as type 'int' for lack of a better
1150 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001151 DeclSpec DS;
1152 const char* PrevSpec; // unused
1153 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1154 PrevSpec);
1155 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1156 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1157 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001158 }
1159 }
Chris Lattnerec9361f2008-02-17 19:31:09 +00001160
Chris Lattner4b009652007-07-25 00:24:17 +00001161 // Since this is a function definition, act as though we have information
1162 // about the arguments.
Chris Lattnerec9361f2008-02-17 19:31:09 +00001163 if (FTI.NumArgs)
1164 FTI.hasPrototype = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001165 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001166 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001167 }
1168
1169 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001170
1171 // See if this is a redefinition.
Steve Naroffe57c21a2008-04-01 23:04:06 +00001172 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroff6384a012008-04-02 14:35:35 +00001173 GlobalScope);
Steve Naroff1d5bd642008-01-14 20:51:29 +00001174 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1175 if (FD->getBody()) {
1176 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1177 D.getIdentifier()->getName());
1178 Diag(FD->getLocation(), diag::err_previous_definition);
1179 }
1180 }
Steve Naroff4a712442008-02-12 01:09:36 +00001181 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner2d2216b2008-02-16 01:20:36 +00001182 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattner4b009652007-07-25 00:24:17 +00001183 CurFunctionDecl = FD;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001184 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001185
1186 // Check the validity of our function parameters
1187 CheckParmsForFunctionDef(FD);
1188
1189 // Introduce our parameters into the function scope
1190 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1191 ParmVarDecl *Param = FD->getParamDecl(p);
1192 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001193 if (Param->getIdentifier())
1194 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001195 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 return FD;
1198}
1199
Steve Naroff99ee4302007-11-11 23:20:51 +00001200Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1201 Decl *dcl = static_cast<Decl *>(D);
1202 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1203 FD->setBody((Stmt*)Body);
1204 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001205 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001206 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001207 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001208 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001209 }
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001210 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001211 // Verify and clean out per-function state.
1212
1213 // Check goto/label use.
1214 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1215 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1216 // Verify that we have no forward references left. If so, there was a goto
1217 // or address of a label taken, but no definition of it. Label fwd
1218 // definitions are indicated with a null substmt.
1219 if (I->second->getSubStmt() == 0) {
1220 LabelStmt *L = I->second;
1221 // Emit error.
1222 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1223
1224 // At this point, we have gotos that use the bogus label. Stitch it into
1225 // the function body so that they aren't leaked and that the AST is well
1226 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001227 if (Body) {
1228 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1229 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1230 } else {
1231 // The whole function wasn't parsed correctly, just delete this.
1232 delete L;
1233 }
Chris Lattner4b009652007-07-25 00:24:17 +00001234 }
1235 }
1236 LabelMap.clear();
1237
Steve Naroff99ee4302007-11-11 23:20:51 +00001238 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001239}
1240
Chris Lattner4b009652007-07-25 00:24:17 +00001241/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1242/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001243ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1244 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001245 if (getLangOptions().C99) // Extension in C99.
1246 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1247 else // Legal in C90, but warn about it.
1248 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1249
1250 // FIXME: handle stuff like:
1251 // void foo() { extern float X(); }
1252 // void bar() { X(); } <-- implicit decl for X in another scope.
1253
1254 // Set a Declarator for the implicit definition: int foo();
1255 const char *Dummy;
1256 DeclSpec DS;
1257 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1258 Error = Error; // Silence warning.
1259 assert(!Error && "Error setting up implicit decl!");
1260 Declarator D(DS, Declarator::BlockContext);
1261 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1262 D.SetIdentifier(&II, Loc);
1263
1264 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001265 if (Scope *FnS = S->getFnParent())
1266 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001267 while (S->getParent())
1268 S = S->getParent();
1269
Steve Naroff9104f3c2008-04-04 14:32:09 +00001270 FunctionDecl *FD =
1271 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1272 FD->setImplicit();
1273 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00001274}
1275
1276
Chris Lattner82bb4792007-11-14 06:34:38 +00001277TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001278 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001279 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001280 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001281
1282 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00001283 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1284 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00001285 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00001286 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001287 if (D.getInvalidType())
1288 NewTD->setInvalidDecl();
1289 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001290}
1291
Steve Naroff0acc9c92007-09-15 18:49:24 +00001292/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001293/// former case, Name will be non-null. In the later case, Name will be null.
1294/// TagType indicates what kind of tag this is. TK indicates whether this is a
1295/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001296Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001297 SourceLocation KWLoc, IdentifierInfo *Name,
1298 SourceLocation NameLoc, AttributeList *Attr) {
1299 // If this is a use of an existing tag, it must have a name.
1300 assert((Name != 0 || TK == TK_Definition) &&
1301 "Nameless record must be a definition!");
1302
1303 Decl::Kind Kind;
1304 switch (TagType) {
1305 default: assert(0 && "Unknown tag type!");
1306 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1307 case DeclSpec::TST_union: Kind = Decl::Union; break;
Chris Lattner2e78db32008-04-13 18:59:07 +00001308 case DeclSpec::TST_class: Kind = Decl::Class; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001309 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1310 }
1311
1312 // If this is a named struct, check to see if there was a previous forward
1313 // declaration or definition.
1314 if (TagDecl *PrevDecl =
Steve Naroff6384a012008-04-02 14:35:35 +00001315 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Chris Lattner4b009652007-07-25 00:24:17 +00001316
1317 // If this is a use of a previous tag, or if the tag is already declared in
1318 // the same scope (so that the definition/declaration completes or
1319 // rementions the tag), reuse the decl.
1320 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1321 // Make sure that this wasn't declared as an enum and now used as a struct
1322 // or something similar.
1323 if (PrevDecl->getKind() != Kind) {
1324 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1325 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1326 }
1327
1328 // If this is a use or a forward declaration, we're good.
1329 if (TK != TK_Definition)
1330 return PrevDecl;
1331
1332 // Diagnose attempts to redefine a tag.
1333 if (PrevDecl->isDefinition()) {
1334 Diag(NameLoc, diag::err_redefinition, Name->getName());
1335 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1336 // If this is a redefinition, recover by making this struct be
1337 // anonymous, which will make any later references get the previous
1338 // definition.
1339 Name = 0;
1340 } else {
1341 // Okay, this is definition of a previously declared or referenced tag.
1342 // Move the location of the decl to be the definition site.
1343 PrevDecl->setLocation(NameLoc);
1344 return PrevDecl;
1345 }
1346 }
1347 // If we get here, this is a definition of a new struct type in a nested
1348 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1349 // type.
1350 }
1351
1352 // If there is an identifier, use the location of the identifier as the
1353 // location of the decl, otherwise use the location of the struct/union
1354 // keyword.
1355 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1356
1357 // Otherwise, if this is the first time we've seen this tag, create the decl.
1358 TagDecl *New;
1359 switch (Kind) {
1360 default: assert(0 && "Unknown tag kind!");
1361 case Decl::Enum:
1362 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1363 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001364 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001365 // If this is an undefined enum, warn.
1366 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1367 break;
1368 case Decl::Union:
1369 case Decl::Struct:
1370 case Decl::Class:
1371 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1372 // struct X { int A; } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00001373 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001374 break;
1375 }
1376
1377 // If this has an identifier, add it to the scope stack.
1378 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001379 // The scope passed in may not be a decl scope. Zip up the scope tree until
1380 // we find one that is.
1381 while ((S->getFlags() & Scope::DeclScope) == 0)
1382 S = S->getParent();
1383
1384 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001385 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001386 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001387
Anders Carlsson136cdc32008-02-16 00:29:18 +00001388 HandleDeclAttributes(New, Attr, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00001389 return New;
1390}
1391
Steve Naroff0acc9c92007-09-15 18:49:24 +00001392/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001393/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001394Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00001395 SourceLocation DeclStart,
1396 Declarator &D, ExprTy *BitfieldWidth) {
1397 IdentifierInfo *II = D.getIdentifier();
1398 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001399 SourceLocation Loc = DeclStart;
1400 if (II) Loc = D.getIdentifierLoc();
1401
1402 // FIXME: Unnamed fields can be handled in various different ways, for
1403 // example, unnamed unions inject all members into the struct namespace!
1404
1405
1406 if (BitWidth) {
1407 // TODO: Validate.
1408 //printf("WARNING: BITFIELDS IGNORED!\n");
1409
1410 // 6.7.2.1p3
1411 // 6.7.2.1p4
1412
1413 } else {
1414 // Not a bitfield.
1415
1416 // validate II.
1417
1418 }
1419
1420 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001421 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1422 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001423
Chris Lattner4b009652007-07-25 00:24:17 +00001424 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1425 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00001426 if (T->isVariablyModifiedType()) {
1427 // FIXME: This diagnostic needs work
1428 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroff5eb879b2007-08-31 17:20:07 +00001429 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001430 }
Chris Lattner4b009652007-07-25 00:24:17 +00001431 // FIXME: Chain fielddecls together.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001432 FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00001433
Anders Carlsson136cdc32008-02-16 00:29:18 +00001434 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1435 D.getAttributes());
1436
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001437 if (D.getInvalidType() || InvalidDecl)
1438 NewFD->setInvalidDecl();
1439 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001440}
1441
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001442/// TranslateIvarVisibility - Translate visibility from a token ID to an
1443/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001444static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001445TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001446 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001447 case tok::objc_private: return ObjCIvarDecl::Private;
1448 case tok::objc_public: return ObjCIvarDecl::Public;
1449 case tok::objc_protected: return ObjCIvarDecl::Protected;
1450 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001451 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001452 }
1453}
1454
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001455/// ActOnIvar - Each ivar field of an objective-c class is passed into this
1456/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001457Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001458 SourceLocation DeclStart,
1459 Declarator &D, ExprTy *BitfieldWidth,
1460 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001461 IdentifierInfo *II = D.getIdentifier();
1462 Expr *BitWidth = (Expr*)BitfieldWidth;
1463 SourceLocation Loc = DeclStart;
1464 if (II) Loc = D.getIdentifierLoc();
1465
1466 // FIXME: Unnamed fields can be handled in various different ways, for
1467 // example, unnamed unions inject all members into the struct namespace!
1468
1469
1470 if (BitWidth) {
1471 // TODO: Validate.
1472 //printf("WARNING: BITFIELDS IGNORED!\n");
1473
1474 // 6.7.2.1p3
1475 // 6.7.2.1p4
1476
1477 } else {
1478 // Not a bitfield.
1479
1480 // validate II.
1481
1482 }
1483
1484 QualType T = GetTypeForDeclarator(D, S);
1485 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1486 bool InvalidDecl = false;
1487
1488 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1489 // than a variably modified type.
1490 if (T->isVariablyModifiedType()) {
1491 // FIXME: This diagnostic needs work
1492 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
1493 InvalidDecl = true;
1494 }
1495
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001496 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001497
1498 HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
1499 D.getAttributes());
1500
1501 if (D.getInvalidType() || InvalidDecl)
1502 NewID->setInvalidDecl();
1503 // If we have visibility info, make sure the AST is set accordingly.
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00001504 if (Visibility != tok::objc_not_keyword)
1505 NewID->setAccessControl(TranslateIvarVisibility(Visibility));
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001506 return NewID;
1507}
1508
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001509void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001510 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001511 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian751c6172008-04-10 23:32:45 +00001512 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001513 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1514 assert(EnclosingDecl && "missing record or interface decl");
1515 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1516
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001517 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001518 // Diagnose code like:
1519 // struct S { struct S {} X; };
1520 // We discover this when we complete the outer S. Reject and ignore the
1521 // outer S.
1522 Diag(Record->getLocation(), diag::err_nested_redefinition,
1523 Record->getKindName());
1524 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001525 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001526 return;
1527 }
Chris Lattner4b009652007-07-25 00:24:17 +00001528 // Verify that all the fields are okay.
1529 unsigned NumNamedMembers = 0;
1530 llvm::SmallVector<FieldDecl*, 32> RecFields;
1531 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001532
Chris Lattner4b009652007-07-25 00:24:17 +00001533 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001534
Steve Naroff9bb759f2007-09-14 22:20:54 +00001535 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1536 assert(FD && "missing field decl");
1537
1538 // Remember all fields.
1539 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001540
1541 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001542 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00001543
Chris Lattner4b009652007-07-25 00:24:17 +00001544 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001545 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001546 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001547 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001548 FD->setInvalidDecl();
1549 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001550 continue;
1551 }
Chris Lattner4b009652007-07-25 00:24:17 +00001552 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1553 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001554 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001555 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001556 FD->setInvalidDecl();
1557 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001558 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001559 }
Chris Lattner4b009652007-07-25 00:24:17 +00001560 if (i != NumFields-1 || // ... that the last member ...
1561 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001562 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001563 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001564 FD->setInvalidDecl();
1565 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001566 continue;
1567 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001568 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001569 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1570 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001571 FD->setInvalidDecl();
1572 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001573 continue;
1574 }
Chris Lattner4b009652007-07-25 00:24:17 +00001575 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001576 if (Record)
1577 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001578 }
Chris Lattner4b009652007-07-25 00:24:17 +00001579 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1580 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001581 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1583 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001584 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001585 Record->setHasFlexibleArrayMember(true);
1586 } else {
1587 // If this is a struct/class and this is not the last element, reject
1588 // it. Note that GCC supports variable sized arrays in the middle of
1589 // structures.
1590 if (i != NumFields-1) {
1591 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1592 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001593 FD->setInvalidDecl();
1594 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001595 continue;
1596 }
Chris Lattner4b009652007-07-25 00:24:17 +00001597 // We support flexible arrays at the end of structs in other structs
1598 // as an extension.
1599 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1600 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001601 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001602 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001603 }
1604 }
1605 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001606 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001607 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001608 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1609 FD->getName());
1610 FD->setInvalidDecl();
1611 EnclosingDecl->setInvalidDecl();
1612 continue;
1613 }
Chris Lattner4b009652007-07-25 00:24:17 +00001614 // Keep track of the number of named members.
1615 if (IdentifierInfo *II = FD->getIdentifier()) {
1616 // Detect duplicate member names.
1617 if (!FieldIDs.insert(II)) {
1618 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1619 // Find the previous decl.
1620 SourceLocation PrevLoc;
1621 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1622 assert(i != e && "Didn't find previous def!");
1623 if (RecFields[i]->getIdentifier() == II) {
1624 PrevLoc = RecFields[i]->getLocation();
1625 break;
1626 }
1627 }
1628 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001629 FD->setInvalidDecl();
1630 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001631 continue;
1632 }
1633 ++NumNamedMembers;
1634 }
Chris Lattner4b009652007-07-25 00:24:17 +00001635 }
1636
Chris Lattner4b009652007-07-25 00:24:17 +00001637 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001638 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001639 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001640 Consumer.HandleTagDeclDefinition(Record);
1641 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001642 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1643 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1644 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1645 else if (ObjCImplementationDecl *IMPDecl =
1646 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001647 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1648 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001649 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001650 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001651 }
Chris Lattner4b009652007-07-25 00:24:17 +00001652}
1653
Steve Naroff0acc9c92007-09-15 18:49:24 +00001654Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001655 DeclTy *lastEnumConst,
1656 SourceLocation IdLoc, IdentifierInfo *Id,
1657 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00001658 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00001659 EnumConstantDecl *LastEnumConst =
1660 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1661 Expr *Val = static_cast<Expr*>(val);
1662
Chris Lattnera7549902007-08-26 06:24:45 +00001663 // The scope passed in may not be a decl scope. Zip up the scope tree until
1664 // we find one that is.
1665 while ((S->getFlags() & Scope::DeclScope) == 0)
1666 S = S->getParent();
1667
Chris Lattner4b009652007-07-25 00:24:17 +00001668 // Verify that there isn't already something declared with this name in this
1669 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00001670 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001671 if (S->isDeclScope(PrevDecl)) {
1672 if (isa<EnumConstantDecl>(PrevDecl))
1673 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1674 else
1675 Diag(IdLoc, diag::err_redefinition, Id->getName());
1676 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001677 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00001678 return 0;
1679 }
1680 }
1681
1682 llvm::APSInt EnumVal(32);
1683 QualType EltTy;
1684 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001685 // Make sure to promote the operand type to int.
1686 UsualUnaryConversions(Val);
1687
Chris Lattner4b009652007-07-25 00:24:17 +00001688 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1689 SourceLocation ExpLoc;
1690 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1691 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1692 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001693 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001694 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001695 } else {
1696 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001697 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001698 }
1699
1700 if (!Val) {
1701 if (LastEnumConst) {
1702 // Assign the last value + 1.
1703 EnumVal = LastEnumConst->getInitVal();
1704 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001705
1706 // Check for overflow on increment.
1707 if (EnumVal < LastEnumConst->getInitVal())
1708 Diag(IdLoc, diag::warn_enum_value_overflow);
1709
Chris Lattnere7f53a42007-08-27 17:37:24 +00001710 EltTy = LastEnumConst->getType();
1711 } else {
1712 // First value, set to zero.
1713 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001714 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001715 }
Chris Lattner4b009652007-07-25 00:24:17 +00001716 }
1717
Chris Lattnere4650482008-03-15 06:12:44 +00001718 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00001719 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1720 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00001721 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00001722
1723 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001724 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00001725 return New;
1726}
1727
Steve Naroff0acc9c92007-09-15 18:49:24 +00001728void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001729 DeclTy **Elements, unsigned NumElements) {
1730 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1731 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1732
Chris Lattner435c3fd2007-08-28 05:10:31 +00001733 // TODO: If the result value doesn't fit in an int, it must be a long or long
1734 // long value. ISO C does not support this, but GCC does as an extension,
1735 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001736 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00001737
Chris Lattner206754a2007-08-28 06:15:15 +00001738 // Verify that all the values are okay, compute the size of the values, and
1739 // reverse the list.
1740 unsigned NumNegativeBits = 0;
1741 unsigned NumPositiveBits = 0;
1742
1743 // Keep track of whether all elements have type int.
1744 bool AllElementsInt = true;
1745
Chris Lattner4b009652007-07-25 00:24:17 +00001746 EnumConstantDecl *EltList = 0;
1747 for (unsigned i = 0; i != NumElements; ++i) {
1748 EnumConstantDecl *ECD =
1749 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1750 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001751
1752 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001753 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001754 assert(InitVal.getBitWidth() >= IntWidth &&
1755 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00001756 if (InitVal.getBitWidth() > IntWidth) {
1757 llvm::APSInt V(InitVal);
1758 V.trunc(IntWidth);
1759 V.extend(InitVal.getBitWidth());
1760 if (V != InitVal)
1761 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1762 InitVal.toString());
1763 }
Chris Lattner206754a2007-08-28 06:15:15 +00001764
1765 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001766 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001767 NumPositiveBits = std::max(NumPositiveBits,
1768 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001769 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001770 NumNegativeBits = std::max(NumNegativeBits,
1771 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001772
Chris Lattner206754a2007-08-28 06:15:15 +00001773 // Keep track of whether every enum element has type int (very commmon).
1774 if (AllElementsInt)
1775 AllElementsInt = ECD->getType() == Context.IntTy;
1776
Chris Lattner4b009652007-07-25 00:24:17 +00001777 ECD->setNextDeclarator(EltList);
1778 EltList = ECD;
1779 }
1780
Chris Lattner206754a2007-08-28 06:15:15 +00001781 // Figure out the type that should be used for this enum.
1782 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1783 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001784 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001785
1786 if (NumNegativeBits) {
1787 // If there is a negative value, figure out the smallest integer type (of
1788 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001789 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001790 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001791 BestWidth = IntWidth;
1792 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001793 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001794
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001795 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001796 BestType = Context.LongTy;
1797 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001798 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001799
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001800 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001801 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1802 BestType = Context.LongLongTy;
1803 }
1804 }
1805 } else {
1806 // If there is no negative value, figure out which of uint, ulong, ulonglong
1807 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001808 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001809 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001810 BestWidth = IntWidth;
1811 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00001812 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00001813 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00001814 } else {
1815 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001816 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001817 "How could an initializer get larger than ULL?");
1818 BestType = Context.UnsignedLongLongTy;
1819 }
1820 }
1821
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001822 // Loop over all of the enumerator constants, changing their types to match
1823 // the type of the enum if needed.
1824 for (unsigned i = 0; i != NumElements; ++i) {
1825 EnumConstantDecl *ECD =
1826 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1827 if (!ECD) continue; // Already issued a diagnostic.
1828
1829 // Standard C says the enumerators have int type, but we allow, as an
1830 // extension, the enumerators to be larger than int size. If each
1831 // enumerator value fits in an int, type it as an int, otherwise type it the
1832 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1833 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001834 if (ECD->getType() == Context.IntTy) {
1835 // Make sure the init value is signed.
1836 llvm::APSInt IV = ECD->getInitVal();
1837 IV.setIsSigned(true);
1838 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001839 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00001840 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001841
1842 // Determine whether the value fits into an int.
1843 llvm::APSInt InitVal = ECD->getInitVal();
1844 bool FitsInInt;
1845 if (InitVal.isUnsigned() || !InitVal.isNegative())
1846 FitsInInt = InitVal.getActiveBits() < IntWidth;
1847 else
1848 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1849
1850 // If it fits into an integer type, force it. Otherwise force it to match
1851 // the enum decl type.
1852 QualType NewTy;
1853 unsigned NewWidth;
1854 bool NewSign;
1855 if (FitsInInt) {
1856 NewTy = Context.IntTy;
1857 NewWidth = IntWidth;
1858 NewSign = true;
1859 } else if (ECD->getType() == BestType) {
1860 // Already the right type!
1861 continue;
1862 } else {
1863 NewTy = BestType;
1864 NewWidth = BestWidth;
1865 NewSign = BestType->isSignedIntegerType();
1866 }
1867
1868 // Adjust the APSInt value.
1869 InitVal.extOrTrunc(NewWidth);
1870 InitVal.setIsSigned(NewSign);
1871 ECD->setInitVal(InitVal);
1872
1873 // Adjust the Expr initializer and type.
1874 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1875 ECD->setType(NewTy);
1876 }
Chris Lattner206754a2007-08-28 06:15:15 +00001877
Chris Lattner90a018d2007-08-28 18:24:31 +00001878 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001879 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001880}
1881
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001882Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1883 ExprTy *expr) {
1884 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1885
Chris Lattner81db64a2008-03-16 00:16:02 +00001886 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001887}
1888
Chris Lattner806a5f52008-01-12 07:05:38 +00001889Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00001890 SourceLocation LBrace,
1891 SourceLocation RBrace,
1892 const char *Lang,
1893 unsigned StrSize,
1894 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00001895 LinkageSpecDecl::LanguageIDs Language;
1896 Decl *dcl = static_cast<Decl *>(D);
1897 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1898 Language = LinkageSpecDecl::lang_c;
1899 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1900 Language = LinkageSpecDecl::lang_cxx;
1901 else {
1902 Diag(Loc, diag::err_bad_language);
1903 return 0;
1904 }
1905
1906 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00001907 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00001908}
1909
Chris Lattner49d15cb2008-02-21 00:48:22 +00001910void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001911
Chris Lattner49d15cb2008-02-21 00:48:22 +00001912 switch (Attr->getKind()) {
Chris Lattnerb9716a62008-02-20 23:17:35 +00001913 case AttributeList::AT_vector_size:
Chris Lattner4b009652007-07-25 00:24:17 +00001914 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner49d15cb2008-02-21 00:48:22 +00001915 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001916 if (!newType.isNull()) // install the new vector type into the decl
1917 vDecl->setType(newType);
1918 }
1919 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1920 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001921 Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00001922 if (!newType.isNull()) // install the new vector type into the decl
1923 tDecl->setUnderlyingType(newType);
1924 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001925 break;
1926 case AttributeList::AT_ocu_vector_type:
Steve Naroff82113e32007-07-29 16:33:31 +00001927 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner49d15cb2008-02-21 00:48:22 +00001928 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroff82113e32007-07-29 16:33:31 +00001929 else
Chris Lattner49d15cb2008-02-21 00:48:22 +00001930 Diag(Attr->getLoc(),
Chris Lattner4b009652007-07-25 00:24:17 +00001931 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001932 break;
1933 case AttributeList::AT_address_space:
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001934 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1935 QualType newType = HandleAddressSpaceTypeAttribute(
1936 tDecl->getUnderlyingType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001937 Attr);
1938 tDecl->setUnderlyingType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001939 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1940 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner49d15cb2008-02-21 00:48:22 +00001941 Attr);
1942 // install the new addr spaced type into the decl
1943 vDecl->setType(newType);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001944 }
Chris Lattnerb9716a62008-02-20 23:17:35 +00001945 break;
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001946 case AttributeList::AT_deprecated:
Chris Lattner402b3372008-03-03 03:28:21 +00001947 HandleDeprecatedAttribute(New, Attr);
1948 break;
1949 case AttributeList::AT_visibility:
1950 HandleVisibilityAttribute(New, Attr);
1951 break;
1952 case AttributeList::AT_weak:
1953 HandleWeakAttribute(New, Attr);
1954 break;
1955 case AttributeList::AT_dllimport:
1956 HandleDLLImportAttribute(New, Attr);
1957 break;
1958 case AttributeList::AT_dllexport:
1959 HandleDLLExportAttribute(New, Attr);
1960 break;
1961 case AttributeList::AT_nothrow:
1962 HandleNothrowAttribute(New, Attr);
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001963 break;
Nate Begemand75d28b2008-03-07 20:04:22 +00001964 case AttributeList::AT_stdcall:
1965 HandleStdCallAttribute(New, Attr);
1966 break;
1967 case AttributeList::AT_fastcall:
1968 HandleFastCallAttribute(New, Attr);
1969 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00001970 case AttributeList::AT_aligned:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001971 HandleAlignedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001972 break;
1973 case AttributeList::AT_packed:
Chris Lattner49d15cb2008-02-21 00:48:22 +00001974 HandlePackedAttribute(New, Attr);
Chris Lattnerb9716a62008-02-20 23:17:35 +00001975 break;
Nate Begeman754d3fc2008-02-21 19:30:49 +00001976 case AttributeList::AT_annotate:
1977 HandleAnnotateAttribute(New, Attr);
1978 break;
Ted Kremenek13bfae62008-02-27 20:43:06 +00001979 case AttributeList::AT_noreturn:
1980 HandleNoReturnAttribute(New, Attr);
1981 break;
Chris Lattner402b3372008-03-03 03:28:21 +00001982 case AttributeList::AT_format:
1983 HandleFormatAttribute(New, Attr);
1984 break;
Chris Lattnerb9716a62008-02-20 23:17:35 +00001985 default:
Chris Lattneree4c3bf2008-02-29 16:48:43 +00001986#if 0
1987 // TODO: when we have the full set of attributes, warn about unknown ones.
1988 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1989 Attr->getName()->getName());
1990#endif
Chris Lattnerb9716a62008-02-20 23:17:35 +00001991 break;
1992 }
Chris Lattner4b009652007-07-25 00:24:17 +00001993}
1994
1995void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1996 AttributeList *declarator_postfix) {
1997 while (declspec_prefix) {
1998 HandleDeclAttribute(New, declspec_prefix);
1999 declspec_prefix = declspec_prefix->getNext();
2000 }
2001 while (declarator_postfix) {
2002 HandleDeclAttribute(New, declarator_postfix);
2003 declarator_postfix = declarator_postfix->getNext();
2004 }
2005}
2006
Steve Naroff82113e32007-07-29 16:33:31 +00002007void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2008 AttributeList *rawAttr) {
2009 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00002010 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002011 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002012 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002013 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002014 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002015 }
2016 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2017 llvm::APSInt vecSize(32);
2018 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002019 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002020 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002021 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002022 }
2023 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2024 // in conjunction with complex types (pointers, arrays, functions, etc.).
2025 Type *canonType = curType.getCanonicalType().getTypePtr();
2026 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002027 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002028 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002029 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002030 }
2031 // unlike gcc's vector_size attribute, the size is specified as the
2032 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002033 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002034
2035 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002036 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002037 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002038 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002039 }
Steve Naroff82113e32007-07-29 16:33:31 +00002040 // Instantiate/Install the vector type, the number of elements is > 0.
2041 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2042 // Remember this typedef decl, we will need it later for diagnostics.
2043 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002044}
2045
2046QualType Sema::HandleVectorTypeAttribute(QualType curType,
2047 AttributeList *rawAttr) {
2048 // check the attribute arugments.
2049 if (rawAttr->getNumArgs() != 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002050 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Chris Lattner4b009652007-07-25 00:24:17 +00002051 std::string("1"));
2052 return QualType();
2053 }
2054 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2055 llvm::APSInt vecSize(32);
2056 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002057 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002058 "vector_size", sizeExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00002059 return QualType();
2060 }
2061 // navigate to the base type - we need to provide for vector pointers,
2062 // vector arrays, and functions returning vectors.
2063 Type *canonType = curType.getCanonicalType().getTypePtr();
2064
2065 if (canonType->isPointerType() || canonType->isArrayType() ||
2066 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00002067 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00002068 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2069 do {
2070 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2071 canonType = PT->getPointeeType().getTypePtr();
2072 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2073 canonType = AT->getElementType().getTypePtr();
2074 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2075 canonType = FT->getResultType().getTypePtr();
2076 } while (canonType->isPointerType() || canonType->isArrayType() ||
2077 canonType->isFunctionType());
2078 */
2079 }
2080 // the base type must be integer or float.
2081 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner9384f502008-02-20 23:25:22 +00002082 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Chris Lattner4b009652007-07-25 00:24:17 +00002083 curType.getCanonicalType().getAsString());
2084 return QualType();
2085 }
Chris Lattner8cd0e932008-03-05 18:54:05 +00002086 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Chris Lattner4b009652007-07-25 00:24:17 +00002087 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002088 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002089
2090 // the vector size needs to be an integral multiple of the type size.
2091 if (vectorSize % typeSize) {
Chris Lattner9384f502008-02-20 23:25:22 +00002092 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002093 sizeExpr->getSourceRange());
2094 return QualType();
2095 }
2096 if (vectorSize == 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002097 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Chris Lattner4b009652007-07-25 00:24:17 +00002098 sizeExpr->getSourceRange());
2099 return QualType();
2100 }
Nate Begeman754d3fc2008-02-21 19:30:49 +00002101 // Instantiate the vector type, the number of elements is > 0, and not
2102 // required to be a power of 2, unlike GCC.
Chris Lattner4b009652007-07-25 00:24:17 +00002103 return Context.getVectorType(curType, vectorSize/typeSize);
2104}
2105
Chris Lattner9384f502008-02-20 23:25:22 +00002106void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlsson136cdc32008-02-16 00:29:18 +00002107 // check the attribute arguments.
2108 if (rawAttr->getNumArgs() > 0) {
Chris Lattner9384f502008-02-20 23:25:22 +00002109 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson136cdc32008-02-16 00:29:18 +00002110 std::string("0"));
2111 return;
2112 }
2113
2114 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2115 TD->addAttr(new PackedAttr);
2116 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2117 // If the alignment is less than or equal to 8 bits, the packed attribute
2118 // has no effect.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002119 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner9384f502008-02-20 23:25:22 +00002120 Diag(rawAttr->getLoc(),
Anders Carlsson136cdc32008-02-16 00:29:18 +00002121 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner9384f502008-02-20 23:25:22 +00002122 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002123 else
Anders Carlssonca133d92008-02-16 00:39:40 +00002124 FD->addAttr(new PackedAttr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002125 } else
Chris Lattner9384f502008-02-20 23:25:22 +00002126 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2127 rawAttr->getName()->getName());
Anders Carlsson136cdc32008-02-16 00:29:18 +00002128}
Nate Begeman754d3fc2008-02-21 19:30:49 +00002129
Ted Kremenek13bfae62008-02-27 20:43:06 +00002130void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2131 // check the attribute arguments.
2132 if (rawAttr->getNumArgs() != 0) {
2133 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2134 std::string("0"));
2135 return;
2136 }
2137
Ted Kremenek40b95e52008-03-03 16:52:27 +00002138 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2139
2140 if (!Fn) {
2141 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2142 "noreturn", "function");
2143 return;
2144 }
2145
Ted Kremenek13bfae62008-02-27 20:43:06 +00002146 d->addAttr(new NoReturnAttr());
2147}
2148
Chris Lattner402b3372008-03-03 03:28:21 +00002149void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2150 // check the attribute arguments.
2151 if (rawAttr->getNumArgs() != 0) {
2152 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2153 std::string("0"));
2154 return;
2155 }
2156
2157 d->addAttr(new DeprecatedAttr());
2158}
2159
2160void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2161 // check the attribute arguments.
Chris Lattnere9d83be2008-03-04 18:08:48 +00002162 if (rawAttr->getNumArgs() != 1) {
Chris Lattner402b3372008-03-03 03:28:21 +00002163 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2164 std::string("1"));
2165 return;
2166 }
2167
Chris Lattnere9d83be2008-03-04 18:08:48 +00002168 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2169 Arg = Arg->IgnoreParenCasts();
2170 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2171
2172 if (Str == 0 || Str->isWide()) {
Chris Lattner402b3372008-03-03 03:28:21 +00002173 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002174 "visibility", std::string("1"));
Chris Lattner402b3372008-03-03 03:28:21 +00002175 return;
2176 }
2177
Chris Lattnere9d83be2008-03-04 18:08:48 +00002178 const char *TypeStr = Str->getStrData();
2179 unsigned TypeLen = Str->getByteLength();
Chris Lattner402b3372008-03-03 03:28:21 +00002180 llvm::GlobalValue::VisibilityTypes type;
2181
Chris Lattnere9d83be2008-03-04 18:08:48 +00002182 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattner402b3372008-03-03 03:28:21 +00002183 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002184 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattner402b3372008-03-03 03:28:21 +00002185 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattnere9d83be2008-03-04 18:08:48 +00002186 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattner402b3372008-03-03 03:28:21 +00002187 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattnere9d83be2008-03-04 18:08:48 +00002188 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattner402b3372008-03-03 03:28:21 +00002189 type = llvm::GlobalValue::ProtectedVisibility;
2190 else {
2191 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattnere9d83be2008-03-04 18:08:48 +00002192 "visibility", TypeStr);
Chris Lattner402b3372008-03-03 03:28:21 +00002193 return;
2194 }
2195
2196 d->addAttr(new VisibilityAttr(type));
2197}
2198
2199void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2200 // check the attribute arguments.
2201 if (rawAttr->getNumArgs() != 0) {
2202 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2203 std::string("0"));
2204 return;
2205 }
2206
2207 d->addAttr(new WeakAttr());
2208}
2209
2210void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2211 // check the attribute arguments.
2212 if (rawAttr->getNumArgs() != 0) {
2213 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2214 std::string("0"));
2215 return;
2216 }
2217
2218 d->addAttr(new DLLImportAttr());
2219}
2220
2221void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2222 // check the attribute arguments.
2223 if (rawAttr->getNumArgs() != 0) {
2224 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2225 std::string("0"));
2226 return;
2227 }
2228
2229 d->addAttr(new DLLExportAttr());
2230}
2231
Nate Begemand75d28b2008-03-07 20:04:22 +00002232void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2233 // check the attribute arguments.
2234 if (rawAttr->getNumArgs() != 0) {
2235 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2236 std::string("0"));
2237 return;
2238 }
2239
2240 d->addAttr(new StdCallAttr());
2241}
2242
2243void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2244 // check the attribute arguments.
2245 if (rawAttr->getNumArgs() != 0) {
2246 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2247 std::string("0"));
2248 return;
2249 }
2250
2251 d->addAttr(new FastCallAttr());
2252}
2253
Chris Lattner402b3372008-03-03 03:28:21 +00002254void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2255 // check the attribute arguments.
2256 if (rawAttr->getNumArgs() != 0) {
2257 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2258 std::string("0"));
2259 return;
2260 }
2261
2262 d->addAttr(new NoThrowAttr());
2263}
2264
Nuno Lopes02564e52008-03-25 23:01:48 +00002265static const FunctionTypeProto *getFunctionProto(Decl *d) {
2266 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2267 if (!decl) return 0;
2268
2269 QualType Ty = decl->getType();
2270
2271 if (Ty->isFunctionPointerType()) {
2272 const PointerType *PtrTy = Ty->getAsPointerType();
2273 Ty = PtrTy->getPointeeType();
2274 }
2275
2276 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2277 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2278
2279 return 0;
2280}
2281
2282
Ted Kremeneke5769412008-03-07 18:43:49 +00002283/// Handle __attribute__((format(type,idx,firstarg))) attributes
2284/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattner402b3372008-03-03 03:28:21 +00002285void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2286
2287 if (!rawAttr->getParameterName()) {
2288 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2289 "format", std::string("1"));
2290 return;
2291 }
2292
2293 if (rawAttr->getNumArgs() != 2) {
2294 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2295 std::string("3"));
2296 return;
2297 }
2298
Nuno Lopes02564e52008-03-25 23:01:48 +00002299 // GCC ignores the format attribute on K&R style function
2300 // prototypes, so we ignore it as well
2301 const FunctionTypeProto *proto = getFunctionProto(d);
2302
2303 if (!proto) {
Chris Lattner402b3372008-03-03 03:28:21 +00002304 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2305 "format", "function");
2306 return;
2307 }
2308
2309 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremeneke5769412008-03-07 18:43:49 +00002310 // this is needed in order to be compatible with GCC
Chris Lattner402b3372008-03-03 03:28:21 +00002311 // the index must start in 1 and the limit is numargs+1
Nuno Lopes02564e52008-03-25 23:01:48 +00002312 unsigned NumArgs = proto->getNumArgs();
Ted Kremeneke5769412008-03-07 18:43:49 +00002313 unsigned FirstIdx = 1;
Chris Lattner402b3372008-03-03 03:28:21 +00002314
2315 const char *Format = rawAttr->getParameterName()->getName();
2316 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2317
2318 // Normalize the argument, __foo__ becomes foo.
2319 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2320 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2321 Format += 2;
2322 FormatLen -= 4;
2323 }
2324
2325 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2326 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2327 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2328 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2329 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2330 "format", rawAttr->getParameterName()->getName());
2331 return;
2332 }
2333
Ted Kremeneke5769412008-03-07 18:43:49 +00002334 // checks for the 2nd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002335 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremeneke5769412008-03-07 18:43:49 +00002336 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002337 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2338 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2339 "format", std::string("2"), IdxExpr->getSourceRange());
2340 return;
2341 }
2342
Ted Kremeneke5769412008-03-07 18:43:49 +00002343 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002344 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2345 "format", std::string("2"), IdxExpr->getSourceRange());
2346 return;
2347 }
2348
Ted Kremeneke5769412008-03-07 18:43:49 +00002349 // make sure the format string is really a string
2350 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2351 if (!Ty->isPointerType() ||
2352 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2353 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2354 IdxExpr->getSourceRange());
2355 return;
2356 }
2357
2358
2359 // check the 3rd argument
Chris Lattner402b3372008-03-03 03:28:21 +00002360 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremeneke5769412008-03-07 18:43:49 +00002361 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattner402b3372008-03-03 03:28:21 +00002362 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2363 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2364 "format", std::string("3"), FirstArgExpr->getSourceRange());
2365 return;
2366 }
2367
Ted Kremeneke5769412008-03-07 18:43:49 +00002368 // check if the function is variadic if the 3rd argument non-zero
2369 if (FirstArg != 0) {
2370 if (proto->isVariadic()) {
2371 ++NumArgs; // +1 for ...
2372 } else {
2373 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2374 return;
2375 }
2376 }
2377
2378 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2379 // the input is just the current time + the format string
Chris Lattner402b3372008-03-03 03:28:21 +00002380 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremeneke5769412008-03-07 18:43:49 +00002381 if (FirstArg != 0) {
Chris Lattner402b3372008-03-03 03:28:21 +00002382 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2383 FirstArgExpr->getSourceRange());
2384 return;
2385 }
Ted Kremeneke5769412008-03-07 18:43:49 +00002386 // if 0 it disables parameter checking (to use with e.g. va_list)
2387 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner402b3372008-03-03 03:28:21 +00002388 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2389 "format", std::string("3"), FirstArgExpr->getSourceRange());
2390 return;
2391 }
2392
2393 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2394 Idx.getZExtValue(), FirstArg.getZExtValue()));
2395}
2396
Nate Begeman754d3fc2008-02-21 19:30:49 +00002397void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2398 // check the attribute arguments.
2399 if (rawAttr->getNumArgs() != 1) {
2400 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2401 std::string("1"));
2402 return;
2403 }
2404 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2405 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002406
Nate Begeman754d3fc2008-02-21 19:30:49 +00002407 // Make sure that there is a string literal as the annotation's single
2408 // argument.
2409 if (!SE) {
2410 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2411 return;
2412 }
2413 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2414 SE->getByteLength())));
2415}
2416
Anders Carlssonc8b44122007-12-19 07:19:40 +00002417void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2418{
2419 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00002420 if (rawAttr->getNumArgs() > 1) {
Chris Lattner9384f502008-02-20 23:25:22 +00002421 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonc8b44122007-12-19 07:19:40 +00002422 std::string("1"));
2423 return;
2424 }
Eli Friedman74820702008-01-30 17:38:42 +00002425
Anders Carlsson7dce0292008-02-16 19:51:27 +00002426 unsigned Align = 0;
2427
2428 if (rawAttr->getNumArgs() == 0) {
2429 // FIXME: This should be the target specific maximum alignment.
2430 // (For now we just use 128 bits which is the maximum on X86.
2431 Align = 128;
Eli Friedman74820702008-01-30 17:38:42 +00002432 return;
Anders Carlsson7dce0292008-02-16 19:51:27 +00002433 } else {
2434 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2435 llvm::APSInt alignment(32);
2436 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner9384f502008-02-20 23:25:22 +00002437 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson7dce0292008-02-16 19:51:27 +00002438 "aligned", alignmentExpr->getSourceRange());
2439 return;
2440 }
2441
2442 Align = alignment.getZExtValue() * 8;
2443 }
Eli Friedman74820702008-01-30 17:38:42 +00002444
Anders Carlsson7dce0292008-02-16 19:51:27 +00002445 d->addAttr(new AlignedAttr(Align));
Anders Carlssonc8b44122007-12-19 07:19:40 +00002446}