blob: 0f464a0bc79f6ea4148b93cb787e9a3552c39f45 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/AST/ASTContext.h"
Anders Carlssonf78915f2008-02-15 07:04:12 +000017#include "clang/AST/Attr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/Builtins.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/Type.h"
22#include "clang/Parse/DeclSpec.h"
23#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Basic/SourceManager.h"
27// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000028#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000029#include "clang/Lex/HeaderSearch.h"
Steve Naroff563477d2007-09-18 23:55:05 +000030#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000032#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34
Steve Naroffb327ce02008-04-02 14:35:35 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
36 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
37
38 if (IIDecl && (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000040 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000041}
42
Chris Lattnerb048c982008-04-06 04:47:34 +000043void Sema::PushDeclContext(DeclContext *CD) {
Chris Lattner0ed844b2008-04-04 06:12:32 +000044 assert(CD->getParent() == CurContext &&
Chris Lattnerb048c982008-04-06 04:47:34 +000045 "The next DeclContext should be directly contained in the current one.");
Chris Lattner0ed844b2008-04-04 06:12:32 +000046 CurContext = CD;
47}
48
Chris Lattnerb048c982008-04-06 04:47:34 +000049void Sema::PopDeclContext() {
50 assert(CurContext && "DeclContext imbalance!");
Chris Lattner0ed844b2008-04-04 06:12:32 +000051 CurContext = CurContext->getParent();
52}
53
Steve Naroffb216c882007-10-09 22:01:59 +000054void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000055 if (S->decl_empty()) return;
56 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
59 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000060 Decl *TmpD = static_cast<Decl*>(*I);
61 assert(TmpD && "This decl didn't get pushed??");
62 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
63 assert(D && "This decl isn't a ScopedDecl?");
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065 IdentifierInfo *II = D->getIdentifier();
66 if (!II) continue;
67
68 // Unlink this decl from the identifier. Because the scope contains decls
69 // in an unordered collection, and because we have multiple identifier
70 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
71 if (II->getFETokenInfo<Decl>() == D) {
72 // Normal case, no multiple decls in different namespaces.
73 II->setFETokenInfo(D->getNext());
74 } else {
75 // Scan ahead. There are only three namespaces in C, so this loop can
76 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000077 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000078 while (SomeDecl->getNext() != D) {
79 SomeDecl = SomeDecl->getNext();
80 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
81 }
82 SomeDecl->setNext(D->getNext());
83 }
84
85 // This will have to be revisited for C++: there we want to nest stuff in
86 // namespace decls etc. Even for C, we might want a top-level translation
87 // unit decl or something.
88 if (!CurFunctionDecl)
89 continue;
90
91 // Chain this decl to the containing function, it now owns the memory for
92 // the decl.
93 D->setNext(CurFunctionDecl->getDeclChain());
94 CurFunctionDecl->setDeclChain(D);
95 }
96}
97
Steve Naroffe8043c32008-04-01 23:04:06 +000098/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
99/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000100ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000101 // The third "scope" argument is 0 since we aren't enabling lazy built-in
102 // creation from this context.
103 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000104
Steve Naroffb327ce02008-04-02 14:35:35 +0000105 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000106}
107
Steve Naroffe8043c32008-04-01 23:04:06 +0000108/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000109/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000110Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
111 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (II == 0) return 0;
113 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
114
115 // Scan up the scope chain looking for a decl that matches this identifier
116 // that is in the appropriate namespace. This search should not take long, as
117 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000118 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 if (D->getIdentifierNamespace() == NS)
120 return D;
121
122 // If we didn't find a use of this identifier, and if the identifier
123 // corresponds to a compiler builtin, create the decl object for the builtin
124 // now, injecting it into translation unit scope, and return it.
125 if (NS == Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000126 if (enableLazyBuiltinCreation) {
127 // If this is a builtin on this (or all) targets, create the decl.
128 if (unsigned BuiltinID = II->getBuiltinID())
129 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
130 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000131 if (getLangOptions().ObjC1) {
132 // @interface and @compatibility_alias introduce typedef-like names.
133 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000134 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000135 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000136 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
137 if (IDI != ObjCInterfaceDecls.end())
138 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000139 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
140 if (I != ObjCAliasDecls.end())
141 return I->second->getClassInterface();
142 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 }
144 return 0;
145}
146
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000147void Sema::InitBuiltinVaListType()
148{
149 if (!Context.getBuiltinVaListType().isNull())
150 return;
151
152 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000153 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000154 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000155 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
156}
157
Reid Spencer5f016e22007-07-11 17:01:13 +0000158/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
159/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000160ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
161 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 Builtin::ID BID = (Builtin::ID)bid;
163
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000164 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000165 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000166 BID == Builtin::BI__builtin_va_end)
167 InitBuiltinVaListType();
168
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000169 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000170 FunctionDecl *New = FunctionDecl::Create(Context, CurContext,
171 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000172 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000173
174 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000175 if (Scope *FnS = S->getFnParent())
176 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 while (S->getParent())
178 S = S->getParent();
179 S->AddDecl(New);
180
181 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000182 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Scan until we find the last (outermost) decl in the id chain.
184 while (LastDecl->getNext())
185 LastDecl = LastDecl->getNext();
186 // Insert before (outside) it.
187 LastDecl->setNext(New);
188 } else {
189 II->setFETokenInfo(New);
190 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 return New;
192}
193
194/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
195/// and scope as a previous declaration 'Old'. Figure out how to resolve this
196/// situation, merging decls or emitting diagnostics as appropriate.
197///
Steve Naroffe8043c32008-04-01 23:04:06 +0000198TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // Verify the old decl was also a typedef.
200 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
201 if (!Old) {
202 Diag(New->getLocation(), diag::err_redefinition_different_kind,
203 New->getName());
204 Diag(OldD->getLocation(), diag::err_previous_definition);
205 return New;
206 }
207
Steve Naroff8ee529b2007-10-31 18:42:27 +0000208 // Allow multiple definitions for ObjC built-in typedefs.
209 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000210 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000211 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000212
213 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
214 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
215 // *either* declaration is in a system header. The code below implements
216 // this adhoc compatibility rule. FIXME: The following code will not
217 // work properly when compiling ".i" files (containing preprocessed output).
218 SourceManager &SrcMgr = Context.getSourceManager();
219 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
220 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
221 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
222 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
223 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
224
Steve Naroffc5e2f342008-03-26 21:27:00 +0000225 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
226 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
227 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000228 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000229 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000230
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
232 // TODO: This is totally simplistic. It should handle merging functions
233 // together etc, merging extern int X; int X; ...
234 Diag(New->getLocation(), diag::err_redefinition, New->getName());
235 Diag(Old->getLocation(), diag::err_previous_definition);
236 return New;
237}
238
Chris Lattnerddee4232008-03-03 03:28:21 +0000239/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
240static bool DeclHasAttr(const Decl *decl, const Attr *target) {
241 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
242 if (attr->getKind() == target->getKind())
243 return true;
244
245 return false;
246}
247
248/// MergeAttributes - append attributes from the Old decl to the New one.
249static void MergeAttributes(Decl *New, Decl *Old) {
250 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
251
252// FIXME: fix this code to cleanup the Old attrs correctly
253 while (attr) {
254 tmp = attr;
255 attr = attr->getNext();
256
257 if (!DeclHasAttr(New, tmp)) {
258 New->addAttr(tmp);
259 } else {
260 tmp->setNext(0);
261 delete(tmp);
262 }
263 }
264}
265
Reid Spencer5f016e22007-07-11 17:01:13 +0000266/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
267/// and scope as a previous declaration 'Old'. Figure out how to resolve this
268/// situation, merging decls or emitting diagnostics as appropriate.
269///
Steve Naroffe8043c32008-04-01 23:04:06 +0000270FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 // Verify the old decl was also a function.
272 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
273 if (!Old) {
274 Diag(New->getLocation(), diag::err_redefinition_different_kind,
275 New->getName());
276 Diag(OldD->getLocation(), diag::err_previous_definition);
277 return New;
278 }
Chris Lattner7e669b22008-02-29 16:48:43 +0000279
Chris Lattnerddee4232008-03-03 03:28:21 +0000280 MergeAttributes(New, Old);
281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000283 QualType OldQType = Context.getCanonicalType(Old->getType());
284 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000285
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000286 // Function types need to be compatible, not identical. This handles
287 // duplicate function decls like "void f(int); void f(enum X);" properly.
288 if (Context.functionTypesAreCompatible(OldQType, NewQType))
289 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000290
Steve Naroff837618c2008-01-16 15:01:34 +0000291 // A function that has already been declared has been redeclared or defined
292 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000293 diag::kind PrevDiag;
294 if (Old->getBody())
295 PrevDiag = diag::err_previous_definition;
296 else if (Old->isImplicit())
297 PrevDiag = diag::err_previous_implicit_declaration;
298 else
299 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000300
Reid Spencer5f016e22007-07-11 17:01:13 +0000301 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
302 // TODO: This is totally simplistic. It should handle merging functions
303 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000304 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
305 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 return New;
307}
308
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000309/// equivalentArrayTypes - Used to determine whether two array types are
310/// equivalent.
311/// We need to check this explicitly as an incomplete array definition is
312/// considered a VariableArrayType, so will not match a complete array
313/// definition that would be otherwise equivalent.
314static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
315 const ArrayType *NewAT = NewQType->getAsArrayType();
316 const ArrayType *OldAT = OldQType->getAsArrayType();
317
318 if (!NewAT || !OldAT)
319 return false;
320
321 // If either (or both) array types in incomplete we need to strip off the
322 // outer VariableArrayType. Once the outer VAT is removed the remaining
323 // types must be identical if the array types are to be considered
324 // equivalent.
325 // eg. int[][1] and int[1][1] become
326 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
327 // removing the outermost VAT gives
328 // CAT(1, int) and CAT(1, int)
329 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000330 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000331 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
332 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000333 NewQType = NewAT->getElementType().getCanonicalType();
334 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000335 }
336
337 return NewQType == OldQType;
338}
339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340/// MergeVarDecl - We just parsed a variable 'New' which has the same name
341/// and scope as a previous declaration 'Old'. Figure out how to resolve this
342/// situation, merging decls or emitting diagnostics as appropriate.
343///
344/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
345/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
346///
Steve Naroffe8043c32008-04-01 23:04:06 +0000347VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // Verify the old decl was also a variable.
349 VarDecl *Old = dyn_cast<VarDecl>(OldD);
350 if (!Old) {
351 Diag(New->getLocation(), diag::err_redefinition_different_kind,
352 New->getName());
353 Diag(OldD->getLocation(), diag::err_previous_definition);
354 return New;
355 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000356
357 MergeAttributes(New, Old);
358
Reid Spencer5f016e22007-07-11 17:01:13 +0000359 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000360 QualType OldCType = Context.getCanonicalType(Old->getType());
361 QualType NewCType = Context.getCanonicalType(New->getType());
362 if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000363 Diag(New->getLocation(), diag::err_redefinition, New->getName());
364 Diag(Old->getLocation(), diag::err_previous_definition);
365 return New;
366 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000367 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
368 if (New->getStorageClass() == VarDecl::Static &&
369 (Old->getStorageClass() == VarDecl::None ||
370 Old->getStorageClass() == VarDecl::Extern)) {
371 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
372 Diag(Old->getLocation(), diag::err_previous_definition);
373 return New;
374 }
375 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
376 if (New->getStorageClass() != VarDecl::Static &&
377 Old->getStorageClass() == VarDecl::Static) {
378 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
379 Diag(Old->getLocation(), diag::err_previous_definition);
380 return New;
381 }
382 // We've verified the types match, now handle "tentative" definitions.
383 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
384 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
385
386 if (OldFSDecl && NewFSDecl) {
387 // Handle C "tentative" external object definitions (C99 6.9.2).
388 bool OldIsTentative = false;
389 bool NewIsTentative = false;
390
391 if (!OldFSDecl->getInit() &&
392 (OldFSDecl->getStorageClass() == VarDecl::None ||
393 OldFSDecl->getStorageClass() == VarDecl::Static))
394 OldIsTentative = true;
395
396 // FIXME: this check doesn't work (since the initializer hasn't been
397 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
398 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
399 // thrown out the old decl.
400 if (!NewFSDecl->getInit() &&
401 (NewFSDecl->getStorageClass() == VarDecl::None ||
402 NewFSDecl->getStorageClass() == VarDecl::Static))
403 ; // change to NewIsTentative = true; once the code is moved.
404
405 if (NewIsTentative || OldIsTentative)
406 return New;
407 }
408 if (Old->getStorageClass() != VarDecl::Extern &&
409 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 Diag(New->getLocation(), diag::err_redefinition, New->getName());
411 Diag(Old->getLocation(), diag::err_previous_definition);
412 }
413 return New;
414}
415
416/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
417/// no declarator (e.g. "struct foo;") is parsed.
418Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
419 // TODO: emit error on 'int;' or 'const enum foo;'.
420 // TODO: emit error on 'typedef int;'
421 // if (!DS.isMissingDeclaratorOk()) Diag(...);
422
Steve Naroff92199282007-11-17 21:37:36 +0000423 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000424}
425
Steve Naroffd0091aa2008-01-10 22:15:12 +0000426bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000427 // Get the type before calling CheckSingleAssignmentConstraints(), since
428 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000429 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000430
Chris Lattner5cf216b2008-01-04 18:04:52 +0000431 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
432 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
433 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000434}
435
Steve Naroff9e8925e2007-09-04 14:36:54 +0000436bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000437 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000438 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000439 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000440 return true; // types weren't compatible.
441
Steve Naroff9e8925e2007-09-04 14:36:54 +0000442 if (savExpr != expr) // The type was promoted, update initializer list.
443 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000444 return false;
445}
446
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000447bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000448 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000449 // C99 6.7.8p14. We have an array of character type with unknown size
450 // being initialized to a string literal.
451 llvm::APSInt ConstVal(32);
452 ConstVal = strLiteral->getByteLength() + 1;
453 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000454 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000455 ArrayType::Normal, 0);
456 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
457 // C99 6.7.8p14. We have an array of character type with known size.
458 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
459 Diag(strLiteral->getSourceRange().getBegin(),
460 diag::warn_initializer_string_for_char_array_too_long,
461 strLiteral->getSourceRange());
462 } else {
463 assert(0 && "HandleStringLiteralInit(): Invalid array type");
464 }
465 // Set type from "char *" to "constant array of char".
466 strLiteral->setType(DeclT);
467 // For now, we always return false (meaning success).
468 return false;
469}
470
471StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000472 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000473 if (AT && AT->getElementType()->isCharType()) {
474 return dyn_cast<StringLiteral>(Init);
475 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000476 return 0;
477}
478
Steve Naroffa9960332008-01-25 00:51:06 +0000479// CheckInitializerListTypes - Checks the types of elements of an initializer
480// list. This function is recursive: it calls itself to initialize subelements
481// of aggregate types. Note that the topLevel parameter essentially refers to
482// whether this expression "owns" the initializer list passed in, or if this
483// initialization is taking elements out of a parent initializer. Each
484// call to this function adds zero or more to startIndex, reports any errors,
485// and returns true if it found any inconsistent types.
486bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
487 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000488 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000489
490 if (DeclType->isScalarType()) {
491 // The simplest case: initializing a single scalar
492 if (topLevel) {
493 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
494 IList->getSourceRange());
495 }
496 if (startIndex < IList->getNumInits()) {
497 Expr* expr = IList->getInit(startIndex);
498 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
499 // FIXME: Should an error be reported here instead?
500 unsigned newIndex = 0;
501 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
502 } else {
503 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
504 }
505 ++startIndex;
506 }
507 // FIXME: Should an error be reported for empty initializer list + scalar?
508 } else if (DeclType->isVectorType()) {
509 if (startIndex < IList->getNumInits()) {
510 const VectorType *VT = DeclType->getAsVectorType();
511 int maxElements = VT->getNumElements();
512 QualType elementType = VT->getElementType();
513
514 for (int i = 0; i < maxElements; ++i) {
515 // Don't attempt to go past the end of the init list
516 if (startIndex >= IList->getNumInits())
517 break;
518 Expr* expr = IList->getInit(startIndex);
519 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
520 unsigned newIndex = 0;
521 hadError |= CheckInitializerListTypes(SubInitList, elementType,
522 true, newIndex);
523 ++startIndex;
524 } else {
525 hadError |= CheckInitializerListTypes(IList, elementType,
526 false, startIndex);
527 }
528 }
529 }
530 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
531 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000532 if (startIndex < IList->getNumInits() && !topLevel &&
533 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
534 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000535 // We found a compatible struct; per the standard, this initializes the
536 // struct. (The C standard technically says that this only applies for
537 // initializers for declarations with automatic scope; however, this
538 // construct is unambiguous anyway because a struct cannot contain
539 // a type compatible with itself. We'll output an error when we check
540 // if the initializer is constant.)
541 // FIXME: Is a call to CheckSingleInitializer required here?
542 ++startIndex;
543 } else {
544 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000545
Steve Naroff406db932008-02-11 21:52:37 +0000546 // If the record is invalid, some of it's members are invalid. To avoid
547 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000548 if (structDecl->isInvalidDecl())
549 return true;
550
Steve Naroffa9960332008-01-25 00:51:06 +0000551 // If structDecl is a forward declaration, this loop won't do anything;
552 // That's okay, because an error should get printed out elsewhere. It
553 // might be worthwhile to skip over the rest of the initializer, though.
554 int numMembers = structDecl->getNumMembers() -
555 structDecl->hasFlexibleArrayMember();
556 for (int i = 0; i < numMembers; i++) {
557 // Don't attempt to go past the end of the init list
558 if (startIndex >= IList->getNumInits())
559 break;
560 FieldDecl * curField = structDecl->getMember(i);
561 if (!curField->getIdentifier()) {
562 // Don't initialize unnamed fields, e.g. "int : 20;"
563 continue;
564 }
565 QualType fieldType = curField->getType();
566 Expr* expr = IList->getInit(startIndex);
567 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
568 unsigned newStart = 0;
569 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
570 true, newStart);
571 ++startIndex;
572 } else {
573 hadError |= CheckInitializerListTypes(IList, fieldType,
574 false, startIndex);
575 }
576 if (DeclType->isUnionType())
577 break;
578 }
579 // FIXME: Implement flexible array initialization GCC extension (it's a
580 // really messy extension to implement, unfortunately...the necessary
581 // information isn't actually even here!)
582 }
583 } else if (DeclType->isArrayType()) {
584 // Check for the special-case of initializing an array with a string.
585 if (startIndex < IList->getNumInits()) {
586 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
587 DeclType)) {
588 CheckStringLiteralInit(lit, DeclType);
589 ++startIndex;
590 if (topLevel && startIndex < IList->getNumInits()) {
591 // We have leftover initializers; warn
592 Diag(IList->getInit(startIndex)->getLocStart(),
593 diag::err_excess_initializers_in_char_array_initializer,
594 IList->getInit(startIndex)->getSourceRange());
595 }
596 return false;
597 }
598 }
599 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000600 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000601 // FIXME: use a proper constant
602 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000603 } else if (const VariableArrayType *VAT =
604 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000605 // Check for VLAs; in standard C it would be possible to check this
606 // earlier, but I don't know where clang accepts VLAs (gcc accepts
607 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000608 Diag(VAT->getSizeExpr()->getLocStart(),
609 diag::err_variable_object_no_init,
610 VAT->getSizeExpr()->getSourceRange());
611 hadError = true;
612 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000613 } else {
614 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
615 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
616 }
617 QualType elementType = DeclType->getAsArrayType()->getElementType();
618 int numElements = 0;
619 for (int i = 0; i < maxElements; ++i, ++numElements) {
620 // Don't attempt to go past the end of the init list
621 if (startIndex >= IList->getNumInits())
622 break;
623 Expr* expr = IList->getInit(startIndex);
624 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
625 unsigned newIndex = 0;
626 hadError |= CheckInitializerListTypes(SubInitList, elementType,
627 true, newIndex);
628 ++startIndex;
629 } else {
630 hadError |= CheckInitializerListTypes(IList, elementType,
631 false, startIndex);
632 }
633 }
Eli Friedman9db13972008-02-15 12:53:51 +0000634 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000635 // If this is an incomplete array type, the actual type needs to
636 // be calculated here
637 if (numElements == 0) {
638 // Sizing an array implicitly to zero is not allowed
639 // (It could in theory be allowed, but it doesn't really matter.)
640 Diag(IList->getLocStart(),
641 diag::err_at_least_one_initializer_needed_to_size_array);
642 hadError = true;
643 } else {
644 llvm::APSInt ConstVal(32);
645 ConstVal = numElements;
646 DeclType = Context.getConstantArrayType(elementType, ConstVal,
647 ArrayType::Normal, 0);
648 }
649 }
650 } else {
651 assert(0 && "Aggregate that isn't a function or array?!");
652 }
653 } else {
654 // In C, all types are either scalars or aggregates, but
655 // additional handling is needed here for C++ (and possibly others?).
656 assert(0 && "Unsupported initializer type");
657 }
658
659 // If this init list is a base list, we set the type; an initializer doesn't
660 // fundamentally have a type, but this makes the ASTs a bit easier to read
661 if (topLevel)
662 IList->setType(DeclType);
663
664 if (topLevel && startIndex < IList->getNumInits()) {
665 // We have leftover initializers; warn
666 Diag(IList->getInit(startIndex)->getLocStart(),
667 diag::warn_excess_initializers,
668 IList->getInit(startIndex)->getSourceRange());
669 }
670 return hadError;
671}
672
673bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000674 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
675 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000676 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000677 return Diag(VAT->getSizeExpr()->getLocStart(),
678 diag::err_variable_object_no_init,
679 VAT->getSizeExpr()->getSourceRange());
680
Steve Naroff2fdc3742007-12-10 22:44:33 +0000681 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
682 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000683 // FIXME: Handle wide strings
684 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
685 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000686
687 if (DeclType->isArrayType())
688 return Diag(Init->getLocStart(),
689 diag::err_array_init_list_required,
690 Init->getSourceRange());
691
Steve Naroffd0091aa2008-01-10 22:15:12 +0000692 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000693 }
Steve Naroffa9960332008-01-25 00:51:06 +0000694 unsigned newIndex = 0;
695 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000696}
697
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000698Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000699Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000700 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 IdentifierInfo *II = D.getIdentifier();
702
Chris Lattnere80a59c2007-07-25 00:24:17 +0000703 // All of these full declarators require an identifier. If it doesn't have
704 // one, the ParsedFreeStandingDeclSpec action should be used.
705 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000706 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000707 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000708 D.getDeclSpec().getSourceRange(), D.getSourceRange());
709 return 0;
710 }
711
Chris Lattner31e05722007-08-26 06:24:45 +0000712 // The scope passed in may not be a decl scope. Zip up the scope tree until
713 // we find one that is.
714 while ((S->getFlags() & Scope::DeclScope) == 0)
715 S = S->getParent();
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000718 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000719 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000720 bool InvalidDecl = false;
721
Chris Lattner41af0932007-11-14 06:34:38 +0000722 QualType R = GetTypeForDeclarator(D, S);
723 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
724
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000726 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 if (!NewTD) return 0;
728
729 // Handle attributes prior to checking for duplicates in MergeVarDecl
730 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
731 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000732 // Merge the decl with the existing one if appropriate. If the decl is
733 // in an outer scope, it isn't the same thing.
734 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
736 if (NewTD == 0) return 0;
737 }
738 New = NewTD;
739 if (S->getParent() == 0) {
740 // C99 6.7.7p2: If a typedef name specifies a variably modified type
741 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000742 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
743 // FIXME: Diagnostic needs to be fixed.
744 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000745 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747 }
Chris Lattner41af0932007-11-14 06:34:38 +0000748 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000749 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 switch (D.getDeclSpec().getStorageClassSpec()) {
751 default: assert(0 && "Unknown storage class!");
752 case DeclSpec::SCS_auto:
753 case DeclSpec::SCS_register:
754 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
755 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000756 InvalidDecl = true;
757 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
759 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
760 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000761 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 }
763
Chris Lattnera98e58d2008-03-15 21:24:04 +0000764 bool isInline = D.getDeclSpec().isInlineSpecified();
Chris Lattner0ed844b2008-04-04 06:12:32 +0000765 FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
766 D.getIdentifierLoc(),
Chris Lattnera98e58d2008-03-15 21:24:04 +0000767 II, R, SC, isInline,
768 LastDeclarator);
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000769 // Handle attributes.
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000770 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
771 D.getAttributes());
Reid Spencer5f016e22007-07-11 17:01:13 +0000772
Steve Naroffffce4d52008-01-09 23:34:55 +0000773 // Merge the decl with the existing one if appropriate. Since C functions
774 // are in a flat namespace, make sure we consider decls in outer scopes.
Reid Spencer5f016e22007-07-11 17:01:13 +0000775 if (PrevDecl) {
776 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
777 if (NewFD == 0) return 0;
778 }
779 New = NewFD;
780 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000781 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000782 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
783 D.getIdentifier()->getName());
784 InvalidDecl = true;
785 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000786
787 VarDecl *NewVD;
788 VarDecl::StorageClass SC;
789 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000790 default: assert(0 && "Unknown storage class!");
791 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
792 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
793 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
794 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
795 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
796 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 }
798 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // C99 6.9p2: The storage-class specifiers auto and register shall not
800 // appear in the declaration specifiers in an external declaration.
801 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
802 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
803 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000804 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 }
Chris Lattner0ed844b2008-04-04 06:12:32 +0000806 NewVD = FileVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
807 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000808 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000809 } else {
Chris Lattner0ed844b2008-04-04 06:12:32 +0000810 NewVD = BlockVarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
811 II, R, SC,
Chris Lattnerc63e6602008-03-15 21:32:50 +0000812 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000813 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 // Handle attributes prior to checking for duplicates in MergeVarDecl
815 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
816 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000817
818 // Emit an error if an address space was applied to decl with local storage.
819 // This includes arrays of objects with address space qualifiers, but not
820 // automatic variables that point to other address spaces.
821 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000822 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
823 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
824 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000825 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000826 // Merge the decl with the existing one if appropriate. If the decl is
827 // in an outer scope, it isn't the same thing.
828 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 NewVD = MergeVarDecl(NewVD, PrevDecl);
830 if (NewVD == 0) return 0;
831 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000832 New = NewVD;
833 }
834
835 // If this has an identifier, add it to the scope stack.
836 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000837 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 II->setFETokenInfo(New);
839 S->AddDecl(New);
840 }
Steve Naroff5912a352007-08-28 20:14:24 +0000841 // If any semantic error occurred, mark the decl as invalid.
842 if (D.getInvalidType() || InvalidDecl)
843 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
845 return New;
846}
847
Steve Naroffd0091aa2008-01-10 22:15:12 +0000848bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
849 SourceLocation loc;
850 // FIXME: Remove the isReference check and handle assignment to a reference.
851 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
852 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
853 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
854 return true;
855 }
856 return false;
857}
858
Steve Naroffbb204692007-09-12 14:07:44 +0000859void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000860 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000861 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000862 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000863
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000864 // If there is no declaration, there was an error parsing it. Just ignore
865 // the initializer.
866 if (RealDecl == 0) {
867 delete Init;
868 return;
869 }
Steve Naroffbb204692007-09-12 14:07:44 +0000870
Steve Naroff410e3e22007-09-12 20:13:48 +0000871 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
872 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000873 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
874 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000875 RealDecl->setInvalidDecl();
876 return;
877 }
Steve Naroffbb204692007-09-12 14:07:44 +0000878 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000879 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000880 QualType DclT = VDecl->getType(), SavT = DclT;
881 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000882 VarDecl::StorageClass SC = BVD->getStorageClass();
883 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000884 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000885 BVD->setInvalidDecl();
886 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000887 if (CheckInitializerTypes(Init, DclT))
888 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000889 if (SC == VarDecl::Static) // C99 6.7.8p4.
890 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000891 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000892 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000893 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000894 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000895 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000896 if (CheckInitializerTypes(Init, DclT))
897 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000898
899 // C99 6.7.8p4. All file scoped initializers need to be constant.
900 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000901 }
902 // If the type changed, it means we had an incomplete type that was
903 // completed by the initializer. For example:
904 // int ary[] = { 1, 3, 5 };
905 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000906 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000907 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000908 Init->setType(DclT);
909 }
Steve Naroffbb204692007-09-12 14:07:44 +0000910
911 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000912 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000913 return;
914}
915
Reid Spencer5f016e22007-07-11 17:01:13 +0000916/// The declarators are chained together backwards, reverse the list.
917Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
918 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000919 Decl *GroupDecl = static_cast<Decl*>(group);
920 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000921 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000922
923 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
924 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000925 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000927 else { // reverse the list.
928 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000929 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000930 Group->setNextDeclarator(NewGroup);
931 NewGroup = Group;
932 Group = Next;
933 }
934 }
935 // Perform semantic analysis that depends on having fully processed both
936 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000937 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000938 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
939 if (!IDecl)
940 continue;
941 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
942 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
943 QualType T = IDecl->getType();
944
945 // C99 6.7.5.2p2: If an identifier is declared to be an object with
946 // static storage duration, it shall not have a variable length array.
947 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +0000948 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000949 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
950 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +0000951 }
952 }
953 // Block scope. C99 6.7p7: If an identifier for an object is declared with
954 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
955 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +0000956 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000957 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
958 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000959 IDecl->setInvalidDecl();
960 }
961 }
962 // File scope. C99 6.9.2p2: A declaration of an identifier for and
963 // object that has file scope without an initializer, and without a
964 // storage-class specifier or with the storage-class specifier "static",
965 // constitutes a tentative definition. Note: A tentative definition with
966 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000967 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
968 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +0000969 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000970 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
971 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +0000972 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000973 // C99 6.9.2p3: If the declaration of an identifier for an object is
974 // a tentative definition and has internal linkage (C99 6.2.2p3), the
975 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000976 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
977 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000978 IDecl->setInvalidDecl();
979 }
980 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 }
982 return NewGroup;
983}
Steve Naroffe1223f72007-08-28 03:03:08 +0000984
985// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000986ParmVarDecl *
Nate Begeman6d20d032008-02-17 21:02:04 +0000987Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
988 Scope *FnScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 IdentifierInfo *II = PI.Ident;
990 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
991 // Can this happen for params? We already checked that they don't conflict
992 // among each other. Here they can only shadow globals, which is ok.
Steve Naroffb327ce02008-04-02 14:35:35 +0000993 if (/*Decl *PrevDecl = */LookupDecl(II, Decl::IDNS_Ordinary, FnScope)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000994
995 }
996
997 // FIXME: Handle storage class (auto, register). No declarator?
998 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000999
1000 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1001 // Doing the promotion here has a win and a loss. The win is the type for
1002 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1003 // code generator). The loss is the orginal type isn't preserved. For example:
1004 //
1005 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1006 // int blockvardecl[5];
1007 // sizeof(parmvardecl); // size == 4
1008 // sizeof(blockvardecl); // size == 20
1009 // }
1010 //
1011 // For expressions, all implicit conversions are captured using the
1012 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1013 //
1014 // FIXME: If a source translation tool needs to see the original type, then
1015 // we need to consider storing both types (in ParmVarDecl)...
1016 //
1017 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnere6327742008-04-02 05:18:44 +00001018 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001019 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001020 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001021 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001022 parmDeclType = Context.getPointerType(parmDeclType);
1023
Chris Lattner0ed844b2008-04-04 06:12:32 +00001024 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, PI.IdentLoc, II,
1025 parmDeclType,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001026 VarDecl::None, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001027
Steve Naroff53a32342007-08-28 18:45:29 +00001028 if (PI.InvalidType)
1029 New->setInvalidDecl();
1030
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 // If this has an identifier, add it to the scope stack.
1032 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001033 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 II->setFETokenInfo(New);
1035 FnScope->AddDecl(New);
1036 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001037
1038 HandleDeclAttributes(New, PI.AttrList, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001039 return New;
1040}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001041
Chris Lattnerb652cea2007-10-09 17:14:05 +00001042Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001043 assert(CurFunctionDecl == 0 && "Function parsing confused");
1044 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1045 "Not a function declarator!");
1046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1047
1048 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1049 // for a K&R function.
1050 if (!FTI.hasPrototype) {
1051 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1052 if (FTI.ArgInfo[i].TypeInfo == 0) {
1053 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1054 FTI.ArgInfo[i].Ident->getName());
1055 // Implicitly declare the argument as type 'int' for lack of a better
1056 // type.
1057 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1058 }
1059 }
Chris Lattner52804082008-02-17 19:31:09 +00001060
Reid Spencer5f016e22007-07-11 17:01:13 +00001061 // Since this is a function definition, act as though we have information
1062 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001063 if (FTI.NumArgs)
1064 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 } else {
1066 // FIXME: Diagnose arguments without names in C.
1067
1068 }
1069
1070 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001071
1072 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001073 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001074 GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001075 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1076 if (FD->getBody()) {
1077 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1078 D.getIdentifier()->getName());
1079 Diag(FD->getLocation(), diag::err_previous_definition);
1080 }
1081 }
Steve Narofffabbc342008-02-12 01:09:36 +00001082 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001083 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 CurFunctionDecl = FD;
Chris Lattnerb048c982008-04-06 04:47:34 +00001085 PushDeclContext(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001086
1087 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1088 llvm::SmallVector<ParmVarDecl*, 16> Params;
1089
1090 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1091 // no arguments, not a function that takes a single void argument.
1092 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerf46699c2008-02-20 20:55:12 +00001093 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001094 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 // empty arg list, don't push any params.
1096 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001097 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Steve Naroff657aefe2008-03-19 23:07:49 +00001098 ParmVarDecl *parmDecl;
1099
1100 parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1101 FnBodyScope);
1102 // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1103 // declarator that is part of a function definition of that function
1104 // shall not have incomplete type.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001105 if (parmDecl->getType()->isIncompleteType() &&
1106 !parmDecl->isInvalidDecl()) {
Steve Naroff657aefe2008-03-19 23:07:49 +00001107 Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1108 parmDecl->getType().getAsString());
1109 parmDecl->setInvalidDecl();
1110 }
1111 Params.push_back(parmDecl);
Steve Naroff66499922007-11-12 03:44:46 +00001112 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001113 }
1114
1115 FD->setParams(&Params[0], Params.size());
1116
1117 return FD;
1118}
1119
Steve Naroffd6d054d2007-11-11 23:20:51 +00001120Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1121 Decl *dcl = static_cast<Decl *>(D);
1122 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1123 FD->setBody((Stmt*)Body);
1124 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001125 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001126 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001127 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001128 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001129 }
Chris Lattnerb048c982008-04-06 04:47:34 +00001130 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001131 // Verify and clean out per-function state.
1132
1133 // Check goto/label use.
1134 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1135 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1136 // Verify that we have no forward references left. If so, there was a goto
1137 // or address of a label taken, but no definition of it. Label fwd
1138 // definitions are indicated with a null substmt.
1139 if (I->second->getSubStmt() == 0) {
1140 LabelStmt *L = I->second;
1141 // Emit error.
1142 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1143
1144 // At this point, we have gotos that use the bogus label. Stitch it into
1145 // the function body so that they aren't leaked and that the AST is well
1146 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001147 if (Body) {
1148 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1149 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1150 } else {
1151 // The whole function wasn't parsed correctly, just delete this.
1152 delete L;
1153 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001154 }
1155 }
1156 LabelMap.clear();
1157
Steve Naroffd6d054d2007-11-11 23:20:51 +00001158 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001159}
1160
Reid Spencer5f016e22007-07-11 17:01:13 +00001161/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1162/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001163ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1164 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001165 if (getLangOptions().C99) // Extension in C99.
1166 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1167 else // Legal in C90, but warn about it.
1168 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1169
1170 // FIXME: handle stuff like:
1171 // void foo() { extern float X(); }
1172 // void bar() { X(); } <-- implicit decl for X in another scope.
1173
1174 // Set a Declarator for the implicit definition: int foo();
1175 const char *Dummy;
1176 DeclSpec DS;
1177 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1178 Error = Error; // Silence warning.
1179 assert(!Error && "Error setting up implicit decl!");
1180 Declarator D(DS, Declarator::BlockContext);
1181 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1182 D.SetIdentifier(&II, Loc);
1183
1184 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001185 if (Scope *FnS = S->getFnParent())
1186 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 while (S->getParent())
1188 S = S->getParent();
1189
Steve Naroffe2ef8152008-04-04 14:32:09 +00001190 FunctionDecl *FD =
1191 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
1192 FD->setImplicit();
1193 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001194}
1195
1196
Chris Lattner41af0932007-11-14 06:34:38 +00001197TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001198 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001199 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001200 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001201
1202 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001203 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1204 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001205 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001206 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001207 if (D.getInvalidType())
1208 NewTD->setInvalidDecl();
1209 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001210}
1211
Steve Naroff08d92e42007-09-15 18:49:24 +00001212/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001213/// former case, Name will be non-null. In the later case, Name will be null.
1214/// TagType indicates what kind of tag this is. TK indicates whether this is a
1215/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001216Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001217 SourceLocation KWLoc, IdentifierInfo *Name,
1218 SourceLocation NameLoc, AttributeList *Attr) {
1219 // If this is a use of an existing tag, it must have a name.
1220 assert((Name != 0 || TK == TK_Definition) &&
1221 "Nameless record must be a definition!");
1222
1223 Decl::Kind Kind;
1224 switch (TagType) {
1225 default: assert(0 && "Unknown tag type!");
1226 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1227 case DeclSpec::TST_union: Kind = Decl::Union; break;
1228//case DeclSpec::TST_class: Kind = Decl::Class; break;
1229 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1230 }
1231
1232 // If this is a named struct, check to see if there was a previous forward
1233 // declaration or definition.
1234 if (TagDecl *PrevDecl =
Steve Naroffb327ce02008-04-02 14:35:35 +00001235 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236
1237 // If this is a use of a previous tag, or if the tag is already declared in
1238 // the same scope (so that the definition/declaration completes or
1239 // rementions the tag), reuse the decl.
1240 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1241 // Make sure that this wasn't declared as an enum and now used as a struct
1242 // or something similar.
1243 if (PrevDecl->getKind() != Kind) {
1244 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1245 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1246 }
1247
1248 // If this is a use or a forward declaration, we're good.
1249 if (TK != TK_Definition)
1250 return PrevDecl;
1251
1252 // Diagnose attempts to redefine a tag.
1253 if (PrevDecl->isDefinition()) {
1254 Diag(NameLoc, diag::err_redefinition, Name->getName());
1255 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1256 // If this is a redefinition, recover by making this struct be
1257 // anonymous, which will make any later references get the previous
1258 // definition.
1259 Name = 0;
1260 } else {
1261 // Okay, this is definition of a previously declared or referenced tag.
1262 // Move the location of the decl to be the definition site.
1263 PrevDecl->setLocation(NameLoc);
1264 return PrevDecl;
1265 }
1266 }
1267 // If we get here, this is a definition of a new struct type in a nested
1268 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1269 // type.
1270 }
1271
1272 // If there is an identifier, use the location of the identifier as the
1273 // location of the decl, otherwise use the location of the struct/union
1274 // keyword.
1275 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1276
1277 // Otherwise, if this is the first time we've seen this tag, create the decl.
1278 TagDecl *New;
1279 switch (Kind) {
1280 default: assert(0 && "Unknown tag kind!");
1281 case Decl::Enum:
1282 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1283 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001284 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // If this is an undefined enum, warn.
1286 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1287 break;
1288 case Decl::Union:
1289 case Decl::Struct:
1290 case Decl::Class:
1291 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1292 // struct X { int A; } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001293 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 break;
1295 }
1296
1297 // If this has an identifier, add it to the scope stack.
1298 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001299 // The scope passed in may not be a decl scope. Zip up the scope tree until
1300 // we find one that is.
1301 while ((S->getFlags() & Scope::DeclScope) == 0)
1302 S = S->getParent();
1303
1304 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001305 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 Name->setFETokenInfo(New);
1307 S->AddDecl(New);
1308 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001309
Anders Carlssonad148062008-02-16 00:29:18 +00001310 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001311 return New;
1312}
1313
Steve Naroff08d92e42007-09-15 18:49:24 +00001314/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001315/// to create a FieldDecl object for it.
Chris Lattnerf9628082008-03-16 01:16:52 +00001316Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 SourceLocation DeclStart,
1318 Declarator &D, ExprTy *BitfieldWidth) {
1319 IdentifierInfo *II = D.getIdentifier();
1320 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattnerf9628082008-03-16 01:16:52 +00001321 Decl *TagDecl = static_cast<Decl *>(tagDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 SourceLocation Loc = DeclStart;
1323 if (II) Loc = D.getIdentifierLoc();
1324
1325 // FIXME: Unnamed fields can be handled in various different ways, for
1326 // example, unnamed unions inject all members into the struct namespace!
1327
1328
1329 if (BitWidth) {
1330 // TODO: Validate.
1331 //printf("WARNING: BITFIELDS IGNORED!\n");
1332
1333 // 6.7.2.1p3
1334 // 6.7.2.1p4
1335
1336 } else {
1337 // Not a bitfield.
1338
1339 // validate II.
1340
1341 }
1342
1343 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001344 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1345 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001346
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1348 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001349 if (T->isVariablyModifiedType()) {
1350 // FIXME: This diagnostic needs work
1351 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001352 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001354 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001355 FieldDecl *NewFD;
1356
Chris Lattnerb048c982008-04-06 04:47:34 +00001357 if (isa<RecordDecl>(TagDecl))
1358 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Chris Lattnerf9628082008-03-16 01:16:52 +00001359 else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1360 isa<ObjCImplementationDecl>(TagDecl) ||
1361 isa<ObjCCategoryDecl>(TagDecl) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001362 // FIXME: ivars are currently used to model properties, and
1363 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001364 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
Chris Lattnerf9628082008-03-16 01:16:52 +00001365 isa<ObjCProtocolDecl>(TagDecl))
Chris Lattnerb048c982008-04-06 04:47:34 +00001366 NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001367 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001368 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001369
Anders Carlssonad148062008-02-16 00:29:18 +00001370 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1371 D.getAttributes());
1372
Steve Naroff5912a352007-08-28 20:14:24 +00001373 if (D.getInvalidType() || InvalidDecl)
1374 NewFD->setInvalidDecl();
1375 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001376}
1377
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001378/// TranslateIvarVisibility - Translate visibility from a token ID to an
1379/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001380static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001381TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001382 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001383 case tok::objc_private: return ObjCIvarDecl::Private;
1384 case tok::objc_public: return ObjCIvarDecl::Public;
1385 case tok::objc_protected: return ObjCIvarDecl::Protected;
1386 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001387 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001388 }
1389}
1390
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001391void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001392 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001393 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001394 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001395 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001396 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1397 assert(EnclosingDecl && "missing record or interface decl");
1398 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1399
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001400 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001401 // Diagnose code like:
1402 // struct S { struct S {} X; };
1403 // We discover this when we complete the outer S. Reject and ignore the
1404 // outer S.
1405 Diag(Record->getLocation(), diag::err_nested_redefinition,
1406 Record->getKindName());
1407 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001408 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 return;
1410 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001411 // Verify that all the fields are okay.
1412 unsigned NumNamedMembers = 0;
1413 llvm::SmallVector<FieldDecl*, 32> RecFields;
1414 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001415
Reid Spencer5f016e22007-07-11 17:01:13 +00001416 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001417
Steve Naroff74216642007-09-14 22:20:54 +00001418 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1419 assert(FD && "missing field decl");
1420
1421 // Remember all fields.
1422 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001423
1424 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001425 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001426
Steve Narofff13271f2007-09-14 23:09:53 +00001427 // If we have visibility info, make sure the AST is set accordingly.
1428 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001429 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001430 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001431
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001433 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001434 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001436 FD->setInvalidDecl();
1437 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001438 continue;
1439 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1441 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001442 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001443 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001444 FD->setInvalidDecl();
1445 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001446 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001447 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001448 if (i != NumFields-1 || // ... that the last member ...
1449 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001450 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001452 FD->setInvalidDecl();
1453 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 continue;
1455 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001456 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001457 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1458 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001459 FD->setInvalidDecl();
1460 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 continue;
1462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001464 if (Record)
1465 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001467 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1468 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001469 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1471 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001472 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 Record->setHasFlexibleArrayMember(true);
1474 } else {
1475 // If this is a struct/class and this is not the last element, reject
1476 // it. Note that GCC supports variable sized arrays in the middle of
1477 // structures.
1478 if (i != NumFields-1) {
1479 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1480 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001481 FD->setInvalidDecl();
1482 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 continue;
1484 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001485 // We support flexible arrays at the end of structs in other structs
1486 // as an extension.
1487 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1488 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001489 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001490 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 }
1492 }
1493 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001494 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001495 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001496 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1497 FD->getName());
1498 FD->setInvalidDecl();
1499 EnclosingDecl->setInvalidDecl();
1500 continue;
1501 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // Keep track of the number of named members.
1503 if (IdentifierInfo *II = FD->getIdentifier()) {
1504 // Detect duplicate member names.
1505 if (!FieldIDs.insert(II)) {
1506 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1507 // Find the previous decl.
1508 SourceLocation PrevLoc;
1509 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1510 assert(i != e && "Didn't find previous def!");
1511 if (RecFields[i]->getIdentifier() == II) {
1512 PrevLoc = RecFields[i]->getLocation();
1513 break;
1514 }
1515 }
1516 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001517 FD->setInvalidDecl();
1518 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 continue;
1520 }
1521 ++NumNamedMembers;
1522 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 }
1524
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001526 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001527 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001528 Consumer.HandleTagDeclDefinition(Record);
1529 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001530 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1531 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1532 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1533 else if (ObjCImplementationDecl *IMPDecl =
1534 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001535 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1536 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001537 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001538 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001539 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001540}
1541
Steve Naroff08d92e42007-09-15 18:49:24 +00001542Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 DeclTy *lastEnumConst,
1544 SourceLocation IdLoc, IdentifierInfo *Id,
1545 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00001546 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 EnumConstantDecl *LastEnumConst =
1548 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1549 Expr *Val = static_cast<Expr*>(val);
1550
Chris Lattner31e05722007-08-26 06:24:45 +00001551 // The scope passed in may not be a decl scope. Zip up the scope tree until
1552 // we find one that is.
1553 while ((S->getFlags() & Scope::DeclScope) == 0)
1554 S = S->getParent();
1555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // Verify that there isn't already something declared with this name in this
1557 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00001558 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 if (S->isDeclScope(PrevDecl)) {
1560 if (isa<EnumConstantDecl>(PrevDecl))
1561 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1562 else
1563 Diag(IdLoc, diag::err_redefinition, Id->getName());
1564 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001565 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 return 0;
1567 }
1568 }
1569
1570 llvm::APSInt EnumVal(32);
1571 QualType EltTy;
1572 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001573 // Make sure to promote the operand type to int.
1574 UsualUnaryConversions(Val);
1575
Reid Spencer5f016e22007-07-11 17:01:13 +00001576 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1577 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001578 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1580 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001581 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001582 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001583 } else {
1584 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001586 }
1587
1588 if (!Val) {
1589 if (LastEnumConst) {
1590 // Assign the last value + 1.
1591 EnumVal = LastEnumConst->getInitVal();
1592 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001593
1594 // Check for overflow on increment.
1595 if (EnumVal < LastEnumConst->getInitVal())
1596 Diag(IdLoc, diag::warn_enum_value_overflow);
1597
Chris Lattnerb7416f92007-08-27 17:37:24 +00001598 EltTy = LastEnumConst->getType();
1599 } else {
1600 // First value, set to zero.
1601 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001602 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001603 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001604 }
1605
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001606 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00001607 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
1608 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001609 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001610
1611 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001612 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 Id->setFETokenInfo(New);
1614 S->AddDecl(New);
1615 return New;
1616}
1617
Steve Naroff08d92e42007-09-15 18:49:24 +00001618void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 DeclTy **Elements, unsigned NumElements) {
1620 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1621 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1622
Chris Lattnere37f0be2007-08-28 05:10:31 +00001623 // TODO: If the result value doesn't fit in an int, it must be a long or long
1624 // long value. ISO C does not support this, but GCC does as an extension,
1625 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001626 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001627
Chris Lattnerac609682007-08-28 06:15:15 +00001628 // Verify that all the values are okay, compute the size of the values, and
1629 // reverse the list.
1630 unsigned NumNegativeBits = 0;
1631 unsigned NumPositiveBits = 0;
1632
1633 // Keep track of whether all elements have type int.
1634 bool AllElementsInt = true;
1635
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 EnumConstantDecl *EltList = 0;
1637 for (unsigned i = 0; i != NumElements; ++i) {
1638 EnumConstantDecl *ECD =
1639 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1640 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001641
1642 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001643 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001644 assert(InitVal.getBitWidth() >= IntWidth &&
1645 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001646 if (InitVal.getBitWidth() > IntWidth) {
1647 llvm::APSInt V(InitVal);
1648 V.trunc(IntWidth);
1649 V.extend(InitVal.getBitWidth());
1650 if (V != InitVal)
1651 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1652 InitVal.toString());
1653 }
Chris Lattnerac609682007-08-28 06:15:15 +00001654
1655 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001656 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001657 NumPositiveBits = std::max(NumPositiveBits,
1658 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001659 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001660 NumNegativeBits = std::max(NumNegativeBits,
1661 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001662
Chris Lattnerac609682007-08-28 06:15:15 +00001663 // Keep track of whether every enum element has type int (very commmon).
1664 if (AllElementsInt)
1665 AllElementsInt = ECD->getType() == Context.IntTy;
1666
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 ECD->setNextDeclarator(EltList);
1668 EltList = ECD;
1669 }
1670
Chris Lattnerac609682007-08-28 06:15:15 +00001671 // Figure out the type that should be used for this enum.
1672 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1673 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001674 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001675
1676 if (NumNegativeBits) {
1677 // If there is a negative value, figure out the smallest integer type (of
1678 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001679 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001680 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001681 BestWidth = IntWidth;
1682 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001683 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001684
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001685 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001686 BestType = Context.LongTy;
1687 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001688 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001689
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001690 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001691 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1692 BestType = Context.LongLongTy;
1693 }
1694 }
1695 } else {
1696 // If there is no negative value, figure out which of uint, ulong, ulonglong
1697 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001698 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001699 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001700 BestWidth = IntWidth;
1701 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001702 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001703 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001704 } else {
1705 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001706 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001707 "How could an initializer get larger than ULL?");
1708 BestType = Context.UnsignedLongLongTy;
1709 }
1710 }
1711
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001712 // Loop over all of the enumerator constants, changing their types to match
1713 // the type of the enum if needed.
1714 for (unsigned i = 0; i != NumElements; ++i) {
1715 EnumConstantDecl *ECD =
1716 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1717 if (!ECD) continue; // Already issued a diagnostic.
1718
1719 // Standard C says the enumerators have int type, but we allow, as an
1720 // extension, the enumerators to be larger than int size. If each
1721 // enumerator value fits in an int, type it as an int, otherwise type it the
1722 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1723 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001724 if (ECD->getType() == Context.IntTy) {
1725 // Make sure the init value is signed.
1726 llvm::APSInt IV = ECD->getInitVal();
1727 IV.setIsSigned(true);
1728 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001729 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001730 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001731
1732 // Determine whether the value fits into an int.
1733 llvm::APSInt InitVal = ECD->getInitVal();
1734 bool FitsInInt;
1735 if (InitVal.isUnsigned() || !InitVal.isNegative())
1736 FitsInInt = InitVal.getActiveBits() < IntWidth;
1737 else
1738 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1739
1740 // If it fits into an integer type, force it. Otherwise force it to match
1741 // the enum decl type.
1742 QualType NewTy;
1743 unsigned NewWidth;
1744 bool NewSign;
1745 if (FitsInInt) {
1746 NewTy = Context.IntTy;
1747 NewWidth = IntWidth;
1748 NewSign = true;
1749 } else if (ECD->getType() == BestType) {
1750 // Already the right type!
1751 continue;
1752 } else {
1753 NewTy = BestType;
1754 NewWidth = BestWidth;
1755 NewSign = BestType->isSignedIntegerType();
1756 }
1757
1758 // Adjust the APSInt value.
1759 InitVal.extOrTrunc(NewWidth);
1760 InitVal.setIsSigned(NewSign);
1761 ECD->setInitVal(InitVal);
1762
1763 // Adjust the Expr initializer and type.
1764 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1765 ECD->setType(NewTy);
1766 }
Chris Lattnerac609682007-08-28 06:15:15 +00001767
Chris Lattnere00b18c2007-08-28 18:24:31 +00001768 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001769 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001770}
1771
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001772Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1773 ExprTy *expr) {
1774 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1775
Chris Lattner8e25d862008-03-16 00:16:02 +00001776 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001777}
1778
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001779Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001780 SourceLocation LBrace,
1781 SourceLocation RBrace,
1782 const char *Lang,
1783 unsigned StrSize,
1784 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001785 LinkageSpecDecl::LanguageIDs Language;
1786 Decl *dcl = static_cast<Decl *>(D);
1787 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1788 Language = LinkageSpecDecl::lang_c;
1789 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1790 Language = LinkageSpecDecl::lang_cxx;
1791 else {
1792 Diag(Loc, diag::err_bad_language);
1793 return 0;
1794 }
1795
1796 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001797 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001798}
1799
Chris Lattner74788ba2008-02-21 00:48:22 +00001800void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001801
Chris Lattner74788ba2008-02-21 00:48:22 +00001802 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001803 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001805 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001806 if (!newType.isNull()) // install the new vector type into the decl
1807 vDecl->setType(newType);
1808 }
1809 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1810 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001811 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 if (!newType.isNull()) // install the new vector type into the decl
1813 tDecl->setUnderlyingType(newType);
1814 }
Chris Lattner212839c2008-02-20 23:17:35 +00001815 break;
1816 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001817 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001818 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001819 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001820 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001821 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001822 break;
1823 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001824 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1825 QualType newType = HandleAddressSpaceTypeAttribute(
1826 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001827 Attr);
1828 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001829 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1830 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001831 Attr);
1832 // install the new addr spaced type into the decl
1833 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001834 }
Chris Lattner212839c2008-02-20 23:17:35 +00001835 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001836 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001837 HandleDeprecatedAttribute(New, Attr);
1838 break;
1839 case AttributeList::AT_visibility:
1840 HandleVisibilityAttribute(New, Attr);
1841 break;
1842 case AttributeList::AT_weak:
1843 HandleWeakAttribute(New, Attr);
1844 break;
1845 case AttributeList::AT_dllimport:
1846 HandleDLLImportAttribute(New, Attr);
1847 break;
1848 case AttributeList::AT_dllexport:
1849 HandleDLLExportAttribute(New, Attr);
1850 break;
1851 case AttributeList::AT_nothrow:
1852 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001853 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001854 case AttributeList::AT_stdcall:
1855 HandleStdCallAttribute(New, Attr);
1856 break;
1857 case AttributeList::AT_fastcall:
1858 HandleFastCallAttribute(New, Attr);
1859 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001860 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001861 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001862 break;
1863 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001864 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001865 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001866 case AttributeList::AT_annotate:
1867 HandleAnnotateAttribute(New, Attr);
1868 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001869 case AttributeList::AT_noreturn:
1870 HandleNoReturnAttribute(New, Attr);
1871 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001872 case AttributeList::AT_format:
1873 HandleFormatAttribute(New, Attr);
1874 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001875 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001876#if 0
1877 // TODO: when we have the full set of attributes, warn about unknown ones.
1878 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1879 Attr->getName()->getName());
1880#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001881 break;
1882 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001883}
1884
1885void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1886 AttributeList *declarator_postfix) {
1887 while (declspec_prefix) {
1888 HandleDeclAttribute(New, declspec_prefix);
1889 declspec_prefix = declspec_prefix->getNext();
1890 }
1891 while (declarator_postfix) {
1892 HandleDeclAttribute(New, declarator_postfix);
1893 declarator_postfix = declarator_postfix->getNext();
1894 }
1895}
1896
Steve Naroffbea0b342007-07-29 16:33:31 +00001897void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1898 AttributeList *rawAttr) {
1899 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001900 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001901 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001902 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00001903 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001904 return;
Steve Naroff73322922007-07-18 18:00:27 +00001905 }
1906 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1907 llvm::APSInt vecSize(32);
1908 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001909 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001910 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001911 return;
Steve Naroff73322922007-07-18 18:00:27 +00001912 }
1913 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1914 // in conjunction with complex types (pointers, arrays, functions, etc.).
1915 Type *canonType = curType.getCanonicalType().getTypePtr();
1916 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001917 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00001918 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001919 return;
Steve Naroff73322922007-07-18 18:00:27 +00001920 }
1921 // unlike gcc's vector_size attribute, the size is specified as the
1922 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001923 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001924
1925 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001926 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00001927 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001928 return;
Steve Naroff73322922007-07-18 18:00:27 +00001929 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001930 // Instantiate/Install the vector type, the number of elements is > 0.
1931 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1932 // Remember this typedef decl, we will need it later for diagnostics.
1933 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001934}
1935
Reid Spencer5f016e22007-07-11 17:01:13 +00001936QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001937 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 // check the attribute arugments.
1939 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001940 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 std::string("1"));
1942 return QualType();
1943 }
1944 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1945 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001946 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001947 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001948 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 return QualType();
1950 }
1951 // navigate to the base type - we need to provide for vector pointers,
1952 // vector arrays, and functions returning vectors.
1953 Type *canonType = curType.getCanonicalType().getTypePtr();
1954
Steve Naroff73322922007-07-18 18:00:27 +00001955 if (canonType->isPointerType() || canonType->isArrayType() ||
1956 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001957 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001958 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1959 do {
1960 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1961 canonType = PT->getPointeeType().getTypePtr();
1962 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1963 canonType = AT->getElementType().getTypePtr();
1964 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1965 canonType = FT->getResultType().getTypePtr();
1966 } while (canonType->isPointerType() || canonType->isArrayType() ||
1967 canonType->isFunctionType());
1968 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 }
1970 // the base type must be integer or float.
1971 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001972 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 curType.getCanonicalType().getAsString());
1974 return QualType();
1975 }
Chris Lattner98be4942008-03-05 18:54:05 +00001976 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001978 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001979
1980 // the vector size needs to be an integral multiple of the type size.
1981 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00001982 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 sizeExpr->getSourceRange());
1984 return QualType();
1985 }
1986 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001987 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 sizeExpr->getSourceRange());
1989 return QualType();
1990 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00001991 // Instantiate the vector type, the number of elements is > 0, and not
1992 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00001993 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994}
1995
Chris Lattner2070d802008-02-20 23:25:22 +00001996void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00001997 // check the attribute arguments.
1998 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001999 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00002000 std::string("0"));
2001 return;
2002 }
2003
2004 if (TagDecl *TD = dyn_cast<TagDecl>(d))
2005 TD->addAttr(new PackedAttr);
2006 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
2007 // If the alignment is less than or equal to 8 bits, the packed attribute
2008 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002009 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002010 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002011 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002012 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002013 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002014 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002015 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002016 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2017 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002018}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002019
Ted Kremenekaecb3832008-02-27 20:43:06 +00002020void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2021 // check the attribute arguments.
2022 if (rawAttr->getNumArgs() != 0) {
2023 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2024 std::string("0"));
2025 return;
2026 }
2027
Ted Kremenek3465fb32008-03-03 16:52:27 +00002028 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2029
2030 if (!Fn) {
2031 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2032 "noreturn", "function");
2033 return;
2034 }
2035
Ted Kremenekaecb3832008-02-27 20:43:06 +00002036 d->addAttr(new NoReturnAttr());
2037}
2038
Chris Lattnerddee4232008-03-03 03:28:21 +00002039void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2040 // check the attribute arguments.
2041 if (rawAttr->getNumArgs() != 0) {
2042 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2043 std::string("0"));
2044 return;
2045 }
2046
2047 d->addAttr(new DeprecatedAttr());
2048}
2049
2050void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2051 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002052 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002053 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2054 std::string("1"));
2055 return;
2056 }
2057
Chris Lattner7b937ae2008-03-04 18:08:48 +00002058 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2059 Arg = Arg->IgnoreParenCasts();
2060 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2061
2062 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002063 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002064 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002065 return;
2066 }
2067
Chris Lattner7b937ae2008-03-04 18:08:48 +00002068 const char *TypeStr = Str->getStrData();
2069 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002070 llvm::GlobalValue::VisibilityTypes type;
2071
Chris Lattner7b937ae2008-03-04 18:08:48 +00002072 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002073 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002074 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002075 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002076 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002077 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002078 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002079 type = llvm::GlobalValue::ProtectedVisibility;
2080 else {
2081 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002082 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002083 return;
2084 }
2085
2086 d->addAttr(new VisibilityAttr(type));
2087}
2088
2089void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2090 // check the attribute arguments.
2091 if (rawAttr->getNumArgs() != 0) {
2092 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2093 std::string("0"));
2094 return;
2095 }
2096
2097 d->addAttr(new WeakAttr());
2098}
2099
2100void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2101 // check the attribute arguments.
2102 if (rawAttr->getNumArgs() != 0) {
2103 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2104 std::string("0"));
2105 return;
2106 }
2107
2108 d->addAttr(new DLLImportAttr());
2109}
2110
2111void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2112 // check the attribute arguments.
2113 if (rawAttr->getNumArgs() != 0) {
2114 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2115 std::string("0"));
2116 return;
2117 }
2118
2119 d->addAttr(new DLLExportAttr());
2120}
2121
Nate Begeman440b4562008-03-07 20:04:22 +00002122void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2123 // check the attribute arguments.
2124 if (rawAttr->getNumArgs() != 0) {
2125 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2126 std::string("0"));
2127 return;
2128 }
2129
2130 d->addAttr(new StdCallAttr());
2131}
2132
2133void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2134 // check the attribute arguments.
2135 if (rawAttr->getNumArgs() != 0) {
2136 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2137 std::string("0"));
2138 return;
2139 }
2140
2141 d->addAttr(new FastCallAttr());
2142}
2143
Chris Lattnerddee4232008-03-03 03:28:21 +00002144void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2145 // check the attribute arguments.
2146 if (rawAttr->getNumArgs() != 0) {
2147 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2148 std::string("0"));
2149 return;
2150 }
2151
2152 d->addAttr(new NoThrowAttr());
2153}
2154
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002155static const FunctionTypeProto *getFunctionProto(Decl *d) {
2156 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2157 if (!decl) return 0;
2158
2159 QualType Ty = decl->getType();
2160
2161 if (Ty->isFunctionPointerType()) {
2162 const PointerType *PtrTy = Ty->getAsPointerType();
2163 Ty = PtrTy->getPointeeType();
2164 }
2165
2166 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2167 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2168
2169 return 0;
2170}
2171
2172
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002173/// Handle __attribute__((format(type,idx,firstarg))) attributes
2174/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002175void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2176
2177 if (!rawAttr->getParameterName()) {
2178 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2179 "format", std::string("1"));
2180 return;
2181 }
2182
2183 if (rawAttr->getNumArgs() != 2) {
2184 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2185 std::string("3"));
2186 return;
2187 }
2188
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002189 // GCC ignores the format attribute on K&R style function
2190 // prototypes, so we ignore it as well
2191 const FunctionTypeProto *proto = getFunctionProto(d);
2192
2193 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002194 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2195 "format", "function");
2196 return;
2197 }
2198
2199 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002200 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002201 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002202 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002203 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002204
2205 const char *Format = rawAttr->getParameterName()->getName();
2206 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2207
2208 // Normalize the argument, __foo__ becomes foo.
2209 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2210 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2211 Format += 2;
2212 FormatLen -= 4;
2213 }
2214
2215 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2216 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2217 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2218 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2219 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2220 "format", rawAttr->getParameterName()->getName());
2221 return;
2222 }
2223
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002224 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002225 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002226 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002227 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2228 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2229 "format", std::string("2"), IdxExpr->getSourceRange());
2230 return;
2231 }
2232
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002233 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002234 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2235 "format", std::string("2"), IdxExpr->getSourceRange());
2236 return;
2237 }
2238
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002239 // make sure the format string is really a string
2240 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2241 if (!Ty->isPointerType() ||
2242 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2243 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2244 IdxExpr->getSourceRange());
2245 return;
2246 }
2247
2248
2249 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002250 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002251 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002252 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2253 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2254 "format", std::string("3"), FirstArgExpr->getSourceRange());
2255 return;
2256 }
2257
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002258 // check if the function is variadic if the 3rd argument non-zero
2259 if (FirstArg != 0) {
2260 if (proto->isVariadic()) {
2261 ++NumArgs; // +1 for ...
2262 } else {
2263 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2264 return;
2265 }
2266 }
2267
2268 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2269 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002270 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002271 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002272 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2273 FirstArgExpr->getSourceRange());
2274 return;
2275 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002276 // if 0 it disables parameter checking (to use with e.g. va_list)
2277 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002278 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2279 "format", std::string("3"), FirstArgExpr->getSourceRange());
2280 return;
2281 }
2282
2283 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2284 Idx.getZExtValue(), FirstArg.getZExtValue()));
2285}
2286
Nate Begemanc398f0b2008-02-21 19:30:49 +00002287void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2288 // check the attribute arguments.
2289 if (rawAttr->getNumArgs() != 1) {
2290 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2291 std::string("1"));
2292 return;
2293 }
2294 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2295 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002296
Nate Begemanc398f0b2008-02-21 19:30:49 +00002297 // Make sure that there is a string literal as the annotation's single
2298 // argument.
2299 if (!SE) {
2300 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2301 return;
2302 }
2303 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2304 SE->getByteLength())));
2305}
2306
Anders Carlsson78aaae92007-12-19 07:19:40 +00002307void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2308{
2309 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002310 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002311 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002312 std::string("1"));
2313 return;
2314 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002315
Anders Carlsson042c4e72008-02-16 19:51:27 +00002316 unsigned Align = 0;
2317
2318 if (rawAttr->getNumArgs() == 0) {
2319 // FIXME: This should be the target specific maximum alignment.
2320 // (For now we just use 128 bits which is the maximum on X86.
2321 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002322 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002323 } else {
2324 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2325 llvm::APSInt alignment(32);
2326 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002327 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002328 "aligned", alignmentExpr->getSourceRange());
2329 return;
2330 }
2331
2332 Align = alignment.getZExtValue() * 8;
2333 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002334
Anders Carlsson042c4e72008-02-16 19:51:27 +00002335 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002336}