blob: 0280ef2127b35a2583dcb3f9672085e8f3c7b81e [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
Reid Spencer5f016e22007-07-11 17:01:13 +000035Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000036 Decl *IIDecl = II.getFETokenInfo<Decl>();
37 // Find first occurance of none-tagged declaration
Steve Naroffe8043c32008-04-01 23:04:06 +000038 while (IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000039 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
Steve Naroffe8043c32008-04-01 23:04:06 +000040
41 if (!IIDecl) {
42 if (getLangOptions().ObjC1) {
43 // @interface and @compatibility_alias result in new type references.
44 // Creating a class alias is *extremely* rare.
45 ObjCAliasTy::const_iterator I = ObjCAliasDecls.find((IdentifierInfo*)&II);
46 if (I != ObjCAliasDecls.end())
47 return I->second->getClassInterface();
48 }
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000049 return 0;
Steve Naroffe8043c32008-04-01 23:04:06 +000050 }
51 // FIXME: remove ObjCInterfaceDecl check when we make it a named decl.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000053 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000054 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000055}
56
Steve Naroffb216c882007-10-09 22:01:59 +000057void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000058 if (S->decl_empty()) return;
59 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
60
Reid Spencer5f016e22007-07-11 17:01:13 +000061 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
62 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000063 Decl *TmpD = static_cast<Decl*>(*I);
64 assert(TmpD && "This decl didn't get pushed??");
65 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
66 assert(D && "This decl isn't a ScopedDecl?");
67
Reid Spencer5f016e22007-07-11 17:01:13 +000068 IdentifierInfo *II = D->getIdentifier();
69 if (!II) continue;
70
71 // Unlink this decl from the identifier. Because the scope contains decls
72 // in an unordered collection, and because we have multiple identifier
73 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
74 if (II->getFETokenInfo<Decl>() == D) {
75 // Normal case, no multiple decls in different namespaces.
76 II->setFETokenInfo(D->getNext());
77 } else {
78 // Scan ahead. There are only three namespaces in C, so this loop can
79 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000080 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000081 while (SomeDecl->getNext() != D) {
82 SomeDecl = SomeDecl->getNext();
83 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
84 }
85 SomeDecl->setNext(D->getNext());
86 }
87
88 // This will have to be revisited for C++: there we want to nest stuff in
89 // namespace decls etc. Even for C, we might want a top-level translation
90 // unit decl or something.
91 if (!CurFunctionDecl)
92 continue;
93
94 // Chain this decl to the containing function, it now owns the memory for
95 // the decl.
96 D->setNext(CurFunctionDecl->getDeclChain());
97 CurFunctionDecl->setDeclChain(D);
98 }
99}
100
Steve Naroffe8043c32008-04-01 23:04:06 +0000101/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
102/// return 0 if one not found.
103/// FIXME: removed this when ObjCInterfaceDecl's aren't ScopedDecl's.
104ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000105 ScopedDecl *IDecl;
106 // Scan up the scope chain looking for a decl that matches this identifier
107 // that is in the appropriate namespace.
Steve Naroffe8043c32008-04-01 23:04:06 +0000108 for (IDecl = Id->getFETokenInfo<ScopedDecl>(); IDecl;
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000109 IDecl = IDecl->getNext())
110 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
111 break;
112
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000113 if (ObjCCompatibleAliasDecl *ADecl =
114 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000115 return ADecl->getClassInterface();
Steve Naroffe8043c32008-04-01 23:04:06 +0000116 return cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000117}
118
Steve Naroffe8043c32008-04-01 23:04:06 +0000119/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000120/// namespace.
Steve Naroffe8043c32008-04-01 23:04:06 +0000121Decl *Sema::LookupDecl(IdentifierInfo *II, unsigned NSI,
122 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 if (II == 0) return 0;
124 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
125
126 // Scan up the scope chain looking for a decl that matches this identifier
127 // that is in the appropriate namespace. This search should not take long, as
128 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000129 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 if (D->getIdentifierNamespace() == NS)
131 return D;
132
133 // If we didn't find a use of this identifier, and if the identifier
134 // corresponds to a compiler builtin, create the decl object for the builtin
135 // now, injecting it into translation unit scope, and return it.
136 if (NS == Decl::IDNS_Ordinary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 // If this is a builtin on this (or all) targets, create the decl.
138 if (unsigned BuiltinID = II->getBuiltinID())
139 return LazilyCreateBuiltin(II, BuiltinID, S);
Steve Naroffe8043c32008-04-01 23:04:06 +0000140
141 if (getLangOptions().ObjC1) {
142 // @interface and @compatibility_alias introduce typedef-like names.
143 // Unlike typedef's, they can only be introduced at file-scope (and are
144 // not therefore not scoped decls). They can, however, be shadowed by
145 // other names in IDNS_Ordinary.
146 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
147 if (I != ObjCAliasDecls.end())
148 return I->second->getClassInterface();
149 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 }
151 return 0;
152}
153
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000154void Sema::InitBuiltinVaListType()
155{
156 if (!Context.getBuiltinVaListType().isNull())
157 return;
158
159 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffe8043c32008-04-01 23:04:06 +0000160 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary,
161 SourceLocation(), TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000162 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000163 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
164}
165
Reid Spencer5f016e22007-07-11 17:01:13 +0000166/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
167/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000168ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
169 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 Builtin::ID BID = (Builtin::ID)bid;
171
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000172 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlsson793680e2007-10-12 23:56:29 +0000173 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000174 BID == Builtin::BI__builtin_va_end)
175 InitBuiltinVaListType();
176
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000177 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattnera98e58d2008-03-15 21:24:04 +0000178 FunctionDecl *New = FunctionDecl::Create(Context, SourceLocation(), II, R,
179 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000180
181 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000182 if (Scope *FnS = S->getFnParent())
183 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 while (S->getParent())
185 S = S->getParent();
186 S->AddDecl(New);
187
188 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000189 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 // Scan until we find the last (outermost) decl in the id chain.
191 while (LastDecl->getNext())
192 LastDecl = LastDecl->getNext();
193 // Insert before (outside) it.
194 LastDecl->setNext(New);
195 } else {
196 II->setFETokenInfo(New);
197 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 return New;
199}
200
201/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
202/// and scope as a previous declaration 'Old'. Figure out how to resolve this
203/// situation, merging decls or emitting diagnostics as appropriate.
204///
Steve Naroffe8043c32008-04-01 23:04:06 +0000205TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 // Verify the old decl was also a typedef.
207 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
208 if (!Old) {
209 Diag(New->getLocation(), diag::err_redefinition_different_kind,
210 New->getName());
211 Diag(OldD->getLocation(), diag::err_previous_definition);
212 return New;
213 }
214
Steve Naroff8ee529b2007-10-31 18:42:27 +0000215 // Allow multiple definitions for ObjC built-in typedefs.
216 // FIXME: Verify the underlying types are equivalent!
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000217 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroff8ee529b2007-10-31 18:42:27 +0000218 return Old;
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000219
220 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
221 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
222 // *either* declaration is in a system header. The code below implements
223 // this adhoc compatibility rule. FIXME: The following code will not
224 // work properly when compiling ".i" files (containing preprocessed output).
225 SourceManager &SrcMgr = Context.getSourceManager();
226 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
227 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
228 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
229 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
230 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
231
Steve Naroffc5e2f342008-03-26 21:27:00 +0000232 // Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
233 if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
234 NewDirType != DirectoryLookup::NormalHeaderDir) ||
Steve Naroffd62701b2008-02-07 03:50:06 +0000235 getLangOptions().Microsoft)
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000236 return New;
Steve Naroffc5e2f342008-03-26 21:27:00 +0000237
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
239 // TODO: This is totally simplistic. It should handle merging functions
240 // together etc, merging extern int X; int X; ...
241 Diag(New->getLocation(), diag::err_redefinition, New->getName());
242 Diag(Old->getLocation(), diag::err_previous_definition);
243 return New;
244}
245
Chris Lattnerddee4232008-03-03 03:28:21 +0000246/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
247static bool DeclHasAttr(const Decl *decl, const Attr *target) {
248 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
249 if (attr->getKind() == target->getKind())
250 return true;
251
252 return false;
253}
254
255/// MergeAttributes - append attributes from the Old decl to the New one.
256static void MergeAttributes(Decl *New, Decl *Old) {
257 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
258
259// FIXME: fix this code to cleanup the Old attrs correctly
260 while (attr) {
261 tmp = attr;
262 attr = attr->getNext();
263
264 if (!DeclHasAttr(New, tmp)) {
265 New->addAttr(tmp);
266 } else {
267 tmp->setNext(0);
268 delete(tmp);
269 }
270 }
271}
272
Reid Spencer5f016e22007-07-11 17:01:13 +0000273/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
274/// and scope as a previous declaration 'Old'. Figure out how to resolve this
275/// situation, merging decls or emitting diagnostics as appropriate.
276///
Steve Naroffe8043c32008-04-01 23:04:06 +0000277FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 // Verify the old decl was also a function.
279 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
280 if (!Old) {
281 Diag(New->getLocation(), diag::err_redefinition_different_kind,
282 New->getName());
283 Diag(OldD->getLocation(), diag::err_previous_definition);
284 return New;
285 }
Chris Lattner7e669b22008-02-29 16:48:43 +0000286
Chris Lattnerddee4232008-03-03 03:28:21 +0000287 MergeAttributes(New, Old);
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
Chris Lattner55196442007-11-20 19:04:50 +0000290 QualType OldQType = Old->getCanonicalType();
291 QualType NewQType = New->getCanonicalType();
292
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000293 // Function types need to be compatible, not identical. This handles
294 // duplicate function decls like "void f(int); void f(enum X);" properly.
295 if (Context.functionTypesAreCompatible(OldQType, NewQType))
296 return New;
Chris Lattnere3995fe2007-11-06 06:07:26 +0000297
Steve Naroff837618c2008-01-16 15:01:34 +0000298 // A function that has already been declared has been redeclared or defined
299 // with a different type- show appropriate diagnostic
300 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
301 diag::err_previous_declaration;
302
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
304 // TODO: This is totally simplistic. It should handle merging functions
305 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000306 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
307 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000308 return New;
309}
310
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000311/// equivalentArrayTypes - Used to determine whether two array types are
312/// equivalent.
313/// We need to check this explicitly as an incomplete array definition is
314/// considered a VariableArrayType, so will not match a complete array
315/// definition that would be otherwise equivalent.
316static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
317 const ArrayType *NewAT = NewQType->getAsArrayType();
318 const ArrayType *OldAT = OldQType->getAsArrayType();
319
320 if (!NewAT || !OldAT)
321 return false;
322
323 // If either (or both) array types in incomplete we need to strip off the
324 // outer VariableArrayType. Once the outer VAT is removed the remaining
325 // types must be identical if the array types are to be considered
326 // equivalent.
327 // eg. int[][1] and int[1][1] become
328 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
329 // removing the outermost VAT gives
330 // CAT(1, int) and CAT(1, int)
331 // which are equal, therefore the array types are equivalent.
Eli Friedman9db13972008-02-15 12:53:51 +0000332 if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000333 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
334 return false;
Eli Friedman04930252008-01-29 07:51:12 +0000335 NewQType = NewAT->getElementType().getCanonicalType();
336 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000337 }
338
339 return NewQType == OldQType;
340}
341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342/// MergeVarDecl - We just parsed a variable 'New' which has the same name
343/// and scope as a previous declaration 'Old'. Figure out how to resolve this
344/// situation, merging decls or emitting diagnostics as appropriate.
345///
346/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
347/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
348///
Steve Naroffe8043c32008-04-01 23:04:06 +0000349VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 // Verify the old decl was also a variable.
351 VarDecl *Old = dyn_cast<VarDecl>(OldD);
352 if (!Old) {
353 Diag(New->getLocation(), diag::err_redefinition_different_kind,
354 New->getName());
355 Diag(OldD->getLocation(), diag::err_previous_definition);
356 return New;
357 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000358
359 MergeAttributes(New, Old);
360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Verify the types match.
Chris Lattnerfcc2d262007-11-06 04:28:31 +0000362 if (Old->getCanonicalType() != New->getCanonicalType() &&
363 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 Diag(New->getLocation(), diag::err_redefinition, New->getName());
365 Diag(Old->getLocation(), diag::err_previous_definition);
366 return New;
367 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000368 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
369 if (New->getStorageClass() == VarDecl::Static &&
370 (Old->getStorageClass() == VarDecl::None ||
371 Old->getStorageClass() == VarDecl::Extern)) {
372 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
373 Diag(Old->getLocation(), diag::err_previous_definition);
374 return New;
375 }
376 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
377 if (New->getStorageClass() != VarDecl::Static &&
378 Old->getStorageClass() == VarDecl::Static) {
379 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
380 Diag(Old->getLocation(), diag::err_previous_definition);
381 return New;
382 }
383 // We've verified the types match, now handle "tentative" definitions.
384 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
385 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
386
387 if (OldFSDecl && NewFSDecl) {
388 // Handle C "tentative" external object definitions (C99 6.9.2).
389 bool OldIsTentative = false;
390 bool NewIsTentative = false;
391
392 if (!OldFSDecl->getInit() &&
393 (OldFSDecl->getStorageClass() == VarDecl::None ||
394 OldFSDecl->getStorageClass() == VarDecl::Static))
395 OldIsTentative = true;
396
397 // FIXME: this check doesn't work (since the initializer hasn't been
398 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
399 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
400 // thrown out the old decl.
401 if (!NewFSDecl->getInit() &&
402 (NewFSDecl->getStorageClass() == VarDecl::None ||
403 NewFSDecl->getStorageClass() == VarDecl::Static))
404 ; // change to NewIsTentative = true; once the code is moved.
405
406 if (NewIsTentative || OldIsTentative)
407 return New;
408 }
409 if (Old->getStorageClass() != VarDecl::Extern &&
410 New->getStorageClass() != VarDecl::Extern) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 Diag(New->getLocation(), diag::err_redefinition, New->getName());
412 Diag(Old->getLocation(), diag::err_previous_definition);
413 }
414 return New;
415}
416
417/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
418/// no declarator (e.g. "struct foo;") is parsed.
419Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
420 // TODO: emit error on 'int;' or 'const enum foo;'.
421 // TODO: emit error on 'typedef int;'
422 // if (!DS.isMissingDeclaratorOk()) Diag(...);
423
Steve Naroff92199282007-11-17 21:37:36 +0000424 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000425}
426
Steve Naroffd0091aa2008-01-10 22:15:12 +0000427bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000428 // Get the type before calling CheckSingleAssignmentConstraints(), since
429 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000430 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000431
Chris Lattner5cf216b2008-01-04 18:04:52 +0000432 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
433 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
434 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000435}
436
Steve Naroff9e8925e2007-09-04 14:36:54 +0000437bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Naroffd0091aa2008-01-10 22:15:12 +0000438 QualType ElementType) {
Chris Lattner33b7b062007-12-11 23:15:04 +0000439 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroffd0091aa2008-01-10 22:15:12 +0000440 if (CheckSingleInitializer(expr, ElementType))
Chris Lattner33b7b062007-12-11 23:15:04 +0000441 return true; // types weren't compatible.
442
Steve Naroff9e8925e2007-09-04 14:36:54 +0000443 if (savExpr != expr) // The type was promoted, update initializer list.
444 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000445 return false;
446}
447
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000448bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000449 if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000450 // C99 6.7.8p14. We have an array of character type with unknown size
451 // being initialized to a string literal.
452 llvm::APSInt ConstVal(32);
453 ConstVal = strLiteral->getByteLength() + 1;
454 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000455 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000456 ArrayType::Normal, 0);
457 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
458 // C99 6.7.8p14. We have an array of character type with known size.
459 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
460 Diag(strLiteral->getSourceRange().getBegin(),
461 diag::warn_initializer_string_for_char_array_too_long,
462 strLiteral->getSourceRange());
463 } else {
464 assert(0 && "HandleStringLiteralInit(): Invalid array type");
465 }
466 // Set type from "char *" to "constant array of char".
467 strLiteral->setType(DeclT);
468 // For now, we always return false (meaning success).
469 return false;
470}
471
472StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000473 const ArrayType *AT = DeclType->getAsArrayType();
Steve Naroffa9960332008-01-25 00:51:06 +0000474 if (AT && AT->getElementType()->isCharType()) {
475 return dyn_cast<StringLiteral>(Init);
476 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000477 return 0;
478}
479
Steve Naroffa9960332008-01-25 00:51:06 +0000480// CheckInitializerListTypes - Checks the types of elements of an initializer
481// list. This function is recursive: it calls itself to initialize subelements
482// of aggregate types. Note that the topLevel parameter essentially refers to
483// whether this expression "owns" the initializer list passed in, or if this
484// initialization is taking elements out of a parent initializer. Each
485// call to this function adds zero or more to startIndex, reports any errors,
486// and returns true if it found any inconsistent types.
487bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
488 bool topLevel, unsigned& startIndex) {
Steve Naroff2fdc3742007-12-10 22:44:33 +0000489 bool hadError = false;
Steve Naroffa9960332008-01-25 00:51:06 +0000490
491 if (DeclType->isScalarType()) {
492 // The simplest case: initializing a single scalar
493 if (topLevel) {
494 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
495 IList->getSourceRange());
496 }
497 if (startIndex < IList->getNumInits()) {
498 Expr* expr = IList->getInit(startIndex);
499 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
500 // FIXME: Should an error be reported here instead?
501 unsigned newIndex = 0;
502 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
503 } else {
504 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
505 }
506 ++startIndex;
507 }
508 // FIXME: Should an error be reported for empty initializer list + scalar?
509 } else if (DeclType->isVectorType()) {
510 if (startIndex < IList->getNumInits()) {
511 const VectorType *VT = DeclType->getAsVectorType();
512 int maxElements = VT->getNumElements();
513 QualType elementType = VT->getElementType();
514
515 for (int i = 0; i < maxElements; ++i) {
516 // Don't attempt to go past the end of the init list
517 if (startIndex >= IList->getNumInits())
518 break;
519 Expr* expr = IList->getInit(startIndex);
520 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
521 unsigned newIndex = 0;
522 hadError |= CheckInitializerListTypes(SubInitList, elementType,
523 true, newIndex);
524 ++startIndex;
525 } else {
526 hadError |= CheckInitializerListTypes(IList, elementType,
527 false, startIndex);
528 }
529 }
530 }
531 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
532 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroff578edc62008-01-28 02:00:41 +0000533 if (startIndex < IList->getNumInits() && !topLevel &&
534 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
535 DeclType)) {
Steve Naroffa9960332008-01-25 00:51:06 +0000536 // We found a compatible struct; per the standard, this initializes the
537 // struct. (The C standard technically says that this only applies for
538 // initializers for declarations with automatic scope; however, this
539 // construct is unambiguous anyway because a struct cannot contain
540 // a type compatible with itself. We'll output an error when we check
541 // if the initializer is constant.)
542 // FIXME: Is a call to CheckSingleInitializer required here?
543 ++startIndex;
544 } else {
545 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffb43eaa52008-02-11 00:06:17 +0000546
Steve Naroff406db932008-02-11 21:52:37 +0000547 // If the record is invalid, some of it's members are invalid. To avoid
548 // confusion, we forgo checking the intializer for the entire record.
Steve Naroffb43eaa52008-02-11 00:06:17 +0000549 if (structDecl->isInvalidDecl())
550 return true;
551
Steve Naroffa9960332008-01-25 00:51:06 +0000552 // If structDecl is a forward declaration, this loop won't do anything;
553 // That's okay, because an error should get printed out elsewhere. It
554 // might be worthwhile to skip over the rest of the initializer, though.
555 int numMembers = structDecl->getNumMembers() -
556 structDecl->hasFlexibleArrayMember();
557 for (int i = 0; i < numMembers; i++) {
558 // Don't attempt to go past the end of the init list
559 if (startIndex >= IList->getNumInits())
560 break;
561 FieldDecl * curField = structDecl->getMember(i);
562 if (!curField->getIdentifier()) {
563 // Don't initialize unnamed fields, e.g. "int : 20;"
564 continue;
565 }
566 QualType fieldType = curField->getType();
567 Expr* expr = IList->getInit(startIndex);
568 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
569 unsigned newStart = 0;
570 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
571 true, newStart);
572 ++startIndex;
573 } else {
574 hadError |= CheckInitializerListTypes(IList, fieldType,
575 false, startIndex);
576 }
577 if (DeclType->isUnionType())
578 break;
579 }
580 // FIXME: Implement flexible array initialization GCC extension (it's a
581 // really messy extension to implement, unfortunately...the necessary
582 // information isn't actually even here!)
583 }
584 } else if (DeclType->isArrayType()) {
585 // Check for the special-case of initializing an array with a string.
586 if (startIndex < IList->getNumInits()) {
587 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
588 DeclType)) {
589 CheckStringLiteralInit(lit, DeclType);
590 ++startIndex;
591 if (topLevel && startIndex < IList->getNumInits()) {
592 // We have leftover initializers; warn
593 Diag(IList->getInit(startIndex)->getLocStart(),
594 diag::err_excess_initializers_in_char_array_initializer,
595 IList->getInit(startIndex)->getSourceRange());
596 }
597 return false;
598 }
599 }
600 int maxElements;
Eli Friedmanc5773c42008-02-15 18:16:39 +0000601 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000602 // FIXME: use a proper constant
603 maxElements = 0x7FFFFFFF;
Chris Lattner212839c2008-02-20 23:17:35 +0000604 } else if (const VariableArrayType *VAT =
605 DeclType->getAsVariableArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000606 // Check for VLAs; in standard C it would be possible to check this
607 // earlier, but I don't know where clang accepts VLAs (gcc accepts
608 // them in all sorts of strange places).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000609 Diag(VAT->getSizeExpr()->getLocStart(),
610 diag::err_variable_object_no_init,
611 VAT->getSizeExpr()->getSourceRange());
612 hadError = true;
613 maxElements = 0x7FFFFFFF;
Steve Naroffa9960332008-01-25 00:51:06 +0000614 } else {
615 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
616 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
617 }
618 QualType elementType = DeclType->getAsArrayType()->getElementType();
619 int numElements = 0;
620 for (int i = 0; i < maxElements; ++i, ++numElements) {
621 // Don't attempt to go past the end of the init list
622 if (startIndex >= IList->getNumInits())
623 break;
624 Expr* expr = IList->getInit(startIndex);
625 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
626 unsigned newIndex = 0;
627 hadError |= CheckInitializerListTypes(SubInitList, elementType,
628 true, newIndex);
629 ++startIndex;
630 } else {
631 hadError |= CheckInitializerListTypes(IList, elementType,
632 false, startIndex);
633 }
634 }
Eli Friedman9db13972008-02-15 12:53:51 +0000635 if (DeclType->isIncompleteArrayType()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000636 // If this is an incomplete array type, the actual type needs to
637 // be calculated here
638 if (numElements == 0) {
639 // Sizing an array implicitly to zero is not allowed
640 // (It could in theory be allowed, but it doesn't really matter.)
641 Diag(IList->getLocStart(),
642 diag::err_at_least_one_initializer_needed_to_size_array);
643 hadError = true;
644 } else {
645 llvm::APSInt ConstVal(32);
646 ConstVal = numElements;
647 DeclType = Context.getConstantArrayType(elementType, ConstVal,
648 ArrayType::Normal, 0);
649 }
650 }
651 } else {
652 assert(0 && "Aggregate that isn't a function or array?!");
653 }
654 } else {
655 // In C, all types are either scalars or aggregates, but
656 // additional handling is needed here for C++ (and possibly others?).
657 assert(0 && "Unsupported initializer type");
658 }
659
660 // If this init list is a base list, we set the type; an initializer doesn't
661 // fundamentally have a type, but this makes the ASTs a bit easier to read
662 if (topLevel)
663 IList->setType(DeclType);
664
665 if (topLevel && startIndex < IList->getNumInits()) {
666 // We have leftover initializers; warn
667 Diag(IList->getInit(startIndex)->getLocStart(),
668 diag::warn_excess_initializers,
669 IList->getInit(startIndex)->getSourceRange());
670 }
671 return hadError;
672}
673
674bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000675 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
676 // of unknown size ("[]") or an object type that is not a variable array type.
Eli Friedmanc5773c42008-02-15 18:16:39 +0000677 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
Steve Naroffca107302008-01-21 23:53:58 +0000678 return Diag(VAT->getSizeExpr()->getLocStart(),
679 diag::err_variable_object_no_init,
680 VAT->getSizeExpr()->getSourceRange());
681
Steve Naroff2fdc3742007-12-10 22:44:33 +0000682 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
683 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000684 // FIXME: Handle wide strings
685 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
686 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000687
688 if (DeclType->isArrayType())
689 return Diag(Init->getLocStart(),
690 diag::err_array_init_list_required,
691 Init->getSourceRange());
692
Steve Naroffd0091aa2008-01-10 22:15:12 +0000693 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000694 }
Steve Naroffa9960332008-01-25 00:51:06 +0000695 unsigned newIndex = 0;
696 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Narofff0090632007-09-02 02:04:30 +0000697}
698
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000699Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000700Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000701 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 IdentifierInfo *II = D.getIdentifier();
703
Chris Lattnere80a59c2007-07-25 00:24:17 +0000704 // All of these full declarators require an identifier. If it doesn't have
705 // one, the ParsedFreeStandingDeclSpec action should be used.
706 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000707 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000708 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000709 D.getDeclSpec().getSourceRange(), D.getSourceRange());
710 return 0;
711 }
712
Chris Lattner31e05722007-08-26 06:24:45 +0000713 // The scope passed in may not be a decl scope. Zip up the scope tree until
714 // we find one that is.
715 while ((S->getFlags() & Scope::DeclScope) == 0)
716 S = S->getParent();
717
Reid Spencer5f016e22007-07-11 17:01:13 +0000718 // See if this is a redefinition of a variable in the same scope.
Steve Naroffe8043c32008-04-01 23:04:06 +0000719 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, D.getIdentifierLoc(), S);
Steve Naroffc752d042007-09-13 18:10:37 +0000720 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000721 bool InvalidDecl = false;
722
Chris Lattner41af0932007-11-14 06:34:38 +0000723 QualType R = GetTypeForDeclarator(D, S);
724 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner41af0932007-11-14 06:34:38 +0000727 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000728 if (!NewTD) return 0;
729
730 // Handle attributes prior to checking for duplicates in MergeVarDecl
731 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
732 D.getAttributes());
Steve Naroffffce4d52008-01-09 23:34:55 +0000733 // Merge the decl with the existing one if appropriate. If the decl is
734 // in an outer scope, it isn't the same thing.
735 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
737 if (NewTD == 0) return 0;
738 }
739 New = NewTD;
740 if (S->getParent() == 0) {
741 // C99 6.7.7p2: If a typedef name specifies a variably modified type
742 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000743 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
744 // FIXME: Diagnostic needs to be fixed.
745 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000746 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 }
748 }
Chris Lattner41af0932007-11-14 06:34:38 +0000749 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000750 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 switch (D.getDeclSpec().getStorageClassSpec()) {
752 default: assert(0 && "Unknown storage class!");
753 case DeclSpec::SCS_auto:
754 case DeclSpec::SCS_register:
755 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
756 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000757 InvalidDecl = true;
758 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
760 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
761 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000762 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 }
764
Chris Lattnera98e58d2008-03-15 21:24:04 +0000765 bool isInline = D.getDeclSpec().isInlineSpecified();
766 FunctionDecl *NewFD = FunctionDecl::Create(Context, D.getIdentifierLoc(),
767 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 Lattnerc63e6602008-03-15 21:32:50 +0000806 NewVD = FileVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
807 LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000808 } else {
Chris Lattnerc63e6602008-03-15 21:32:50 +0000809 NewVD = BlockVarDecl::Create(Context, D.getIdentifierLoc(), II, R, SC,
810 LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000811 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000812 // Handle attributes prior to checking for duplicates in MergeVarDecl
813 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
814 D.getAttributes());
Nate Begemanc8e89a82008-03-14 18:07:10 +0000815
816 // Emit an error if an address space was applied to decl with local storage.
817 // This includes arrays of objects with address space qualifiers, but not
818 // automatic variables that point to other address spaces.
819 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000820 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
821 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
822 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000823 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000824 // Merge the decl with the existing one if appropriate. If the decl is
825 // in an outer scope, it isn't the same thing.
826 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 NewVD = MergeVarDecl(NewVD, PrevDecl);
828 if (NewVD == 0) return 0;
829 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 New = NewVD;
831 }
832
833 // If this has an identifier, add it to the scope stack.
834 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000835 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 II->setFETokenInfo(New);
837 S->AddDecl(New);
838 }
Steve Naroff5912a352007-08-28 20:14:24 +0000839 // If any semantic error occurred, mark the decl as invalid.
840 if (D.getInvalidType() || InvalidDecl)
841 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000842
843 return New;
844}
845
Steve Naroffd0091aa2008-01-10 22:15:12 +0000846bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
847 SourceLocation loc;
848 // FIXME: Remove the isReference check and handle assignment to a reference.
849 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
850 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
851 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
852 return true;
853 }
854 return false;
855}
856
Steve Naroffbb204692007-09-12 14:07:44 +0000857void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000858 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000859 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000860 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000861
Chris Lattner9a11b9a2007-10-19 20:10:30 +0000862 // If there is no declaration, there was an error parsing it. Just ignore
863 // the initializer.
864 if (RealDecl == 0) {
865 delete Init;
866 return;
867 }
Steve Naroffbb204692007-09-12 14:07:44 +0000868
Steve Naroff410e3e22007-09-12 20:13:48 +0000869 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
870 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000871 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
872 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000873 RealDecl->setInvalidDecl();
874 return;
875 }
Steve Naroffbb204692007-09-12 14:07:44 +0000876 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +0000877 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000878 QualType DclT = VDecl->getType(), SavT = DclT;
879 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000880 VarDecl::StorageClass SC = BVD->getStorageClass();
881 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000882 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000883 BVD->setInvalidDecl();
884 } else if (!BVD->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +0000885 if (CheckInitializerTypes(Init, DclT))
886 BVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000887 if (SC == VarDecl::Static) // C99 6.7.8p4.
888 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000889 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000890 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000891 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000892 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000893 if (!FVD->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +0000894 if (CheckInitializerTypes(Init, DclT))
895 FVD->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +0000896
897 // C99 6.7.8p4. All file scoped initializers need to be constant.
898 CheckForConstantInitializer(Init, DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000899 }
900 // If the type changed, it means we had an incomplete type that was
901 // completed by the initializer. For example:
902 // int ary[] = { 1, 3, 5 };
903 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +0000904 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000905 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +0000906 Init->setType(DclT);
907 }
Steve Naroffbb204692007-09-12 14:07:44 +0000908
909 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000910 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000911 return;
912}
913
Reid Spencer5f016e22007-07-11 17:01:13 +0000914/// The declarators are chained together backwards, reverse the list.
915Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
916 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000917 Decl *GroupDecl = static_cast<Decl*>(group);
918 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000919 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000920
921 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
922 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000923 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000925 else { // reverse the list.
926 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000927 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000928 Group->setNextDeclarator(NewGroup);
929 NewGroup = Group;
930 Group = Next;
931 }
932 }
933 // Perform semantic analysis that depends on having fully processed both
934 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000935 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000936 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
937 if (!IDecl)
938 continue;
939 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
940 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
941 QualType T = IDecl->getType();
942
943 // C99 6.7.5.2p2: If an identifier is declared to be an object with
944 // static storage duration, it shall not have a variable length array.
945 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
Eli Friedman3fe02932008-02-15 19:53:52 +0000946 if (T->getAsVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +0000947 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
948 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +0000949 }
950 }
951 // Block scope. C99 6.7p7: If an identifier for an object is declared with
952 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
953 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
954 if (T->isIncompleteType()) {
Chris Lattner8b1be772007-12-02 07:50:03 +0000955 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
956 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000957 IDecl->setInvalidDecl();
958 }
959 }
960 // File scope. C99 6.9.2p2: A declaration of an identifier for and
961 // object that has file scope without an initializer, and without a
962 // storage-class specifier or with the storage-class specifier "static",
963 // constitutes a tentative definition. Note: A tentative definition with
964 // external linkage is valid (C99 6.2.2p5).
Steve Naroffd3cd1e52008-01-18 00:39:39 +0000965 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
966 FVD->getStorageClass() == VarDecl::None)) {
Eli Friedman9db13972008-02-15 12:53:51 +0000967 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +0000968 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
969 // array to be completed. Don't issue a diagnostic.
970 } else if (T->isIncompleteType()) {
971 // C99 6.9.2p3: If the declaration of an identifier for an object is
972 // a tentative definition and has internal linkage (C99 6.2.2p3), the
973 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +0000974 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
975 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +0000976 IDecl->setInvalidDecl();
977 }
978 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 }
980 return NewGroup;
981}
Steve Naroffe1223f72007-08-28 03:03:08 +0000982
983// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000984ParmVarDecl *
Nate Begeman6d20d032008-02-17 21:02:04 +0000985Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI,
986 Scope *FnScope) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000987 IdentifierInfo *II = PI.Ident;
988 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
989 // Can this happen for params? We already checked that they don't conflict
990 // among each other. Here they can only shadow globals, which is ok.
Steve Naroffe8043c32008-04-01 23:04:06 +0000991 if (/*Decl *PrevDecl = */LookupDecl(II, Decl::IDNS_Ordinary,
992 PI.IdentLoc, FnScope)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000993
994 }
995
996 // FIXME: Handle storage class (auto, register). No declarator?
997 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000998
999 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1000 // Doing the promotion here has a win and a loss. The win is the type for
1001 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1002 // code generator). The loss is the orginal type isn't preserved. For example:
1003 //
1004 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1005 // int blockvardecl[5];
1006 // sizeof(parmvardecl); // size == 4
1007 // sizeof(blockvardecl); // size == 20
1008 // }
1009 //
1010 // For expressions, all implicit conversions are captured using the
1011 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1012 //
1013 // FIXME: If a source translation tool needs to see the original type, then
1014 // we need to consider storing both types (in ParmVarDecl)...
1015 //
1016 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattner529bd022008-01-02 22:50:48 +00001017 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
1018 // int x[restrict 4] -> int *restrict
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001019 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattner529bd022008-01-02 22:50:48 +00001020 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
1021 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001022 parmDeclType = Context.getPointerType(parmDeclType);
1023
Chris Lattnerc63e6602008-03-15 21:32:50 +00001024 ParmVarDecl *New = ParmVarDecl::Create(Context, PI.IdentLoc, II, parmDeclType,
1025 VarDecl::None, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001026
Steve Naroff53a32342007-08-28 18:45:29 +00001027 if (PI.InvalidType)
1028 New->setInvalidDecl();
1029
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 // If this has an identifier, add it to the scope stack.
1031 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +00001032 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 II->setFETokenInfo(New);
1034 FnScope->AddDecl(New);
1035 }
Nate Begemanb7894b52008-02-17 21:20:31 +00001036
1037 HandleDeclAttributes(New, PI.AttrList, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 return New;
1039}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001040
Chris Lattnerb652cea2007-10-09 17:14:05 +00001041Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 assert(CurFunctionDecl == 0 && "Function parsing confused");
1043 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1044 "Not a function declarator!");
1045 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1046
1047 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1048 // for a K&R function.
1049 if (!FTI.hasPrototype) {
1050 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1051 if (FTI.ArgInfo[i].TypeInfo == 0) {
1052 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1053 FTI.ArgInfo[i].Ident->getName());
1054 // Implicitly declare the argument as type 'int' for lack of a better
1055 // type.
1056 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1057 }
1058 }
Chris Lattner52804082008-02-17 19:31:09 +00001059
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 // Since this is a function definition, act as though we have information
1061 // about the arguments.
Chris Lattner52804082008-02-17 19:31:09 +00001062 if (FTI.NumArgs)
1063 FTI.hasPrototype = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 } else {
1065 // FIXME: Diagnose arguments without names in C.
1066
1067 }
1068
1069 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001070
1071 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001072 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1073 D.getIdentifierLoc(), GlobalScope);
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001074 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1075 if (FD->getBody()) {
1076 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1077 D.getIdentifier()->getName());
1078 Diag(FD->getLocation(), diag::err_previous_definition);
1079 }
1080 }
Steve Narofffabbc342008-02-12 01:09:36 +00001081 Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattnere9ba3232008-02-16 01:20:36 +00001082 FunctionDecl *FD = cast<FunctionDecl>(decl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 CurFunctionDecl = FD;
1084
1085 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1086 llvm::SmallVector<ParmVarDecl*, 16> Params;
1087
1088 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1089 // no arguments, not a function that takes a single void argument.
1090 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerf46699c2008-02-20 20:55:12 +00001091 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getCVRQualifiers() &&
Chris Lattnerb751c282007-11-28 18:51:29 +00001092 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 // empty arg list, don't push any params.
1094 } else {
Steve Naroff66499922007-11-12 03:44:46 +00001095 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Steve Naroff657aefe2008-03-19 23:07:49 +00001096 ParmVarDecl *parmDecl;
1097
1098 parmDecl = ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
1099 FnBodyScope);
1100 // C99 6.7.5.3p4: the parameters in a parameter type list in a function
1101 // declarator that is part of a function definition of that function
1102 // shall not have incomplete type.
1103 if (parmDecl->getType()->isIncompleteType()) {
1104 Diag(parmDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1105 parmDecl->getType().getAsString());
1106 parmDecl->setInvalidDecl();
1107 }
1108 Params.push_back(parmDecl);
Steve Naroff66499922007-11-12 03:44:46 +00001109 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001110 }
1111
1112 FD->setParams(&Params[0], Params.size());
1113
1114 return FD;
1115}
1116
Steve Naroffd6d054d2007-11-11 23:20:51 +00001117Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1118 Decl *dcl = static_cast<Decl *>(D);
1119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1120 FD->setBody((Stmt*)Body);
1121 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff4d832202007-12-13 18:18:56 +00001122 CurFunctionDecl = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001123 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001124 MD->setBody((Stmt*)Body);
Steve Naroff03300712007-11-12 13:56:41 +00001125 CurMethodDecl = 0;
Steve Naroff4d832202007-12-13 18:18:56 +00001126 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 // Verify and clean out per-function state.
1128
1129 // Check goto/label use.
1130 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1131 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1132 // Verify that we have no forward references left. If so, there was a goto
1133 // or address of a label taken, but no definition of it. Label fwd
1134 // definitions are indicated with a null substmt.
1135 if (I->second->getSubStmt() == 0) {
1136 LabelStmt *L = I->second;
1137 // Emit error.
1138 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1139
1140 // At this point, we have gotos that use the bogus label. Stitch it into
1141 // the function body so that they aren't leaked and that the AST is well
1142 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001143 if (Body) {
1144 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1145 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1146 } else {
1147 // The whole function wasn't parsed correctly, just delete this.
1148 delete L;
1149 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001150 }
1151 }
1152 LabelMap.clear();
1153
Steve Naroffd6d054d2007-11-11 23:20:51 +00001154 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001155}
1156
Reid Spencer5f016e22007-07-11 17:01:13 +00001157/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1158/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001159ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1160 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001161 if (getLangOptions().C99) // Extension in C99.
1162 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1163 else // Legal in C90, but warn about it.
1164 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1165
1166 // FIXME: handle stuff like:
1167 // void foo() { extern float X(); }
1168 // void bar() { X(); } <-- implicit decl for X in another scope.
1169
1170 // Set a Declarator for the implicit definition: int foo();
1171 const char *Dummy;
1172 DeclSpec DS;
1173 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1174 Error = Error; // Silence warning.
1175 assert(!Error && "Error setting up implicit decl!");
1176 Declarator D(DS, Declarator::BlockContext);
1177 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1178 D.SetIdentifier(&II, Loc);
1179
1180 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +00001181 if (Scope *FnS = S->getFnParent())
1182 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +00001183 while (S->getParent())
1184 S = S->getParent();
1185
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001186 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +00001187}
1188
1189
Chris Lattner41af0932007-11-14 06:34:38 +00001190TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001191 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001192 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001193 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001194
1195 // Scope manipulation handled by caller.
Chris Lattnerc63e6602008-03-15 21:32:50 +00001196 TypedefDecl *NewTD = TypedefDecl::Create(Context, D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001197 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001198 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001199 if (D.getInvalidType())
1200 NewTD->setInvalidDecl();
1201 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001202}
1203
Steve Naroff08d92e42007-09-15 18:49:24 +00001204/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001205/// former case, Name will be non-null. In the later case, Name will be null.
1206/// TagType indicates what kind of tag this is. TK indicates whether this is a
1207/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001208Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001209 SourceLocation KWLoc, IdentifierInfo *Name,
1210 SourceLocation NameLoc, AttributeList *Attr) {
1211 // If this is a use of an existing tag, it must have a name.
1212 assert((Name != 0 || TK == TK_Definition) &&
1213 "Nameless record must be a definition!");
1214
1215 Decl::Kind Kind;
1216 switch (TagType) {
1217 default: assert(0 && "Unknown tag type!");
1218 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1219 case DeclSpec::TST_union: Kind = Decl::Union; break;
1220//case DeclSpec::TST_class: Kind = Decl::Class; break;
1221 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1222 }
1223
1224 // If this is a named struct, check to see if there was a previous forward
1225 // declaration or definition.
1226 if (TagDecl *PrevDecl =
Steve Naroffe8043c32008-04-01 23:04:06 +00001227 dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,
1228 NameLoc, S))) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001229
1230 // If this is a use of a previous tag, or if the tag is already declared in
1231 // the same scope (so that the definition/declaration completes or
1232 // rementions the tag), reuse the decl.
1233 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1234 // Make sure that this wasn't declared as an enum and now used as a struct
1235 // or something similar.
1236 if (PrevDecl->getKind() != Kind) {
1237 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1238 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1239 }
1240
1241 // If this is a use or a forward declaration, we're good.
1242 if (TK != TK_Definition)
1243 return PrevDecl;
1244
1245 // Diagnose attempts to redefine a tag.
1246 if (PrevDecl->isDefinition()) {
1247 Diag(NameLoc, diag::err_redefinition, Name->getName());
1248 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1249 // If this is a redefinition, recover by making this struct be
1250 // anonymous, which will make any later references get the previous
1251 // definition.
1252 Name = 0;
1253 } else {
1254 // Okay, this is definition of a previously declared or referenced tag.
1255 // Move the location of the decl to be the definition site.
1256 PrevDecl->setLocation(NameLoc);
1257 return PrevDecl;
1258 }
1259 }
1260 // If we get here, this is a definition of a new struct type in a nested
1261 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1262 // type.
1263 }
1264
1265 // If there is an identifier, use the location of the identifier as the
1266 // location of the decl, otherwise use the location of the struct/union
1267 // keyword.
1268 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1269
1270 // Otherwise, if this is the first time we've seen this tag, create the decl.
1271 TagDecl *New;
1272 switch (Kind) {
1273 default: assert(0 && "Unknown tag kind!");
1274 case Decl::Enum:
1275 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1276 // enum X { A, B, C } D; D should chain to X.
Chris Lattnerc63e6602008-03-15 21:32:50 +00001277 New = EnumDecl::Create(Context, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001278 // If this is an undefined enum, warn.
1279 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1280 break;
1281 case Decl::Union:
1282 case Decl::Struct:
1283 case Decl::Class:
1284 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1285 // struct X { int A; } D; D should chain to X.
Chris Lattnerc63e6602008-03-15 21:32:50 +00001286 New = RecordDecl::Create(Context, Kind, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 break;
1288 }
1289
1290 // If this has an identifier, add it to the scope stack.
1291 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001292 // The scope passed in may not be a decl scope. Zip up the scope tree until
1293 // we find one that is.
1294 while ((S->getFlags() & Scope::DeclScope) == 0)
1295 S = S->getParent();
1296
1297 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001298 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 Name->setFETokenInfo(New);
1300 S->AddDecl(New);
1301 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001302
Anders Carlssonad148062008-02-16 00:29:18 +00001303 HandleDeclAttributes(New, Attr, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 return New;
1305}
1306
Steve Naroff08d92e42007-09-15 18:49:24 +00001307/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001308/// to create a FieldDecl object for it.
Chris Lattnerf9628082008-03-16 01:16:52 +00001309Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *tagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 SourceLocation DeclStart,
1311 Declarator &D, ExprTy *BitfieldWidth) {
1312 IdentifierInfo *II = D.getIdentifier();
1313 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattnerf9628082008-03-16 01:16:52 +00001314 Decl *TagDecl = static_cast<Decl *>(tagDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001315 SourceLocation Loc = DeclStart;
1316 if (II) Loc = D.getIdentifierLoc();
1317
1318 // FIXME: Unnamed fields can be handled in various different ways, for
1319 // example, unnamed unions inject all members into the struct namespace!
1320
1321
1322 if (BitWidth) {
1323 // TODO: Validate.
1324 //printf("WARNING: BITFIELDS IGNORED!\n");
1325
1326 // 6.7.2.1p3
1327 // 6.7.2.1p4
1328
1329 } else {
1330 // Not a bitfield.
1331
1332 // validate II.
1333
1334 }
1335
1336 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001337 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1338 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1341 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00001342 if (T->isVariablyModifiedType()) {
1343 // FIXME: This diagnostic needs work
1344 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
Steve Naroffd7444aa2007-08-31 17:20:07 +00001345 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001347 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001348 FieldDecl *NewFD;
1349
Chris Lattnerf9628082008-03-16 01:16:52 +00001350 if (isa<RecordDecl>(TagDecl))
Chris Lattner8e25d862008-03-16 00:16:02 +00001351 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Chris Lattnerf9628082008-03-16 01:16:52 +00001352 else if (isa<ObjCInterfaceDecl>(TagDecl) ||
1353 isa<ObjCImplementationDecl>(TagDecl) ||
1354 isa<ObjCCategoryDecl>(TagDecl) ||
Steve Naroffddd600f2007-11-14 14:15:31 +00001355 // FIXME: ivars are currently used to model properties, and
1356 // properties can appear within a protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001357 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
Chris Lattnerf9628082008-03-16 01:16:52 +00001358 isa<ObjCProtocolDecl>(TagDecl))
Chris Lattner0e77ba02008-03-16 01:15:50 +00001359 NewFD = ObjCIvarDecl::Create(Context, Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001360 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001361 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001362
Anders Carlssonad148062008-02-16 00:29:18 +00001363 HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
1364 D.getAttributes());
1365
Steve Naroff5912a352007-08-28 20:14:24 +00001366 if (D.getInvalidType() || InvalidDecl)
1367 NewFD->setInvalidDecl();
1368 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001369}
1370
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001371/// TranslateIvarVisibility - Translate visibility from a token ID to an
1372/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001373static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001374TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001375 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001376 case tok::objc_private: return ObjCIvarDecl::Private;
1377 case tok::objc_public: return ObjCIvarDecl::Public;
1378 case tok::objc_protected: return ObjCIvarDecl::Protected;
1379 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001380 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001381 }
1382}
1383
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001384void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001385 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001386 DeclTy **Fields, unsigned NumFields,
Steve Naroff60fccee2007-10-29 21:38:07 +00001387 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff08d92e42007-09-15 18:49:24 +00001388 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001389 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1390 assert(EnclosingDecl && "missing record or interface decl");
1391 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1392
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001393 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // Diagnose code like:
1395 // struct S { struct S {} X; };
1396 // We discover this when we complete the outer S. Reject and ignore the
1397 // outer S.
1398 Diag(Record->getLocation(), diag::err_nested_redefinition,
1399 Record->getKindName());
1400 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001401 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 return;
1403 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001404 // Verify that all the fields are okay.
1405 unsigned NumNamedMembers = 0;
1406 llvm::SmallVector<FieldDecl*, 32> RecFields;
1407 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001408
Reid Spencer5f016e22007-07-11 17:01:13 +00001409 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001410
Steve Naroff74216642007-09-14 22:20:54 +00001411 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1412 assert(FD && "missing field decl");
1413
1414 // Remember all fields.
1415 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001416
1417 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001418 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001419
Steve Narofff13271f2007-09-14 23:09:53 +00001420 // If we have visibility info, make sure the AST is set accordingly.
1421 if (visibility)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001422 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001423 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001424
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001426 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001427 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001429 FD->setInvalidDecl();
1430 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 continue;
1432 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1434 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001435 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001436 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001437 FD->setInvalidDecl();
1438 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001439 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 if (i != NumFields-1 || // ... that the last member ...
1442 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001443 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001445 FD->setInvalidDecl();
1446 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 continue;
1448 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001449 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001450 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1451 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 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001457 if (Record)
1458 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1461 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001462 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1464 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001465 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 Record->setHasFlexibleArrayMember(true);
1467 } else {
1468 // If this is a struct/class and this is not the last element, reject
1469 // it. Note that GCC supports variable sized arrays in the middle of
1470 // structures.
1471 if (i != NumFields-1) {
1472 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1473 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001474 FD->setInvalidDecl();
1475 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 continue;
1477 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001478 // We support flexible arrays at the end of structs in other structs
1479 // as an extension.
1480 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1481 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001482 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001483 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 }
1485 }
1486 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001487 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001488 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001489 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1490 FD->getName());
1491 FD->setInvalidDecl();
1492 EnclosingDecl->setInvalidDecl();
1493 continue;
1494 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // Keep track of the number of named members.
1496 if (IdentifierInfo *II = FD->getIdentifier()) {
1497 // Detect duplicate member names.
1498 if (!FieldIDs.insert(II)) {
1499 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1500 // Find the previous decl.
1501 SourceLocation PrevLoc;
1502 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1503 assert(i != e && "Didn't find previous def!");
1504 if (RecFields[i]->getIdentifier() == II) {
1505 PrevLoc = RecFields[i]->getLocation();
1506 break;
1507 }
1508 }
1509 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001510 FD->setInvalidDecl();
1511 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 continue;
1513 }
1514 ++NumNamedMembers;
1515 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001516 }
1517
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00001519 if (Record) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001520 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattnere1e79852008-02-06 00:51:33 +00001521 Consumer.HandleTagDeclDefinition(Record);
1522 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00001523 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1524 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1525 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1526 else if (ObjCImplementationDecl *IMPDecl =
1527 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001528 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1529 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00001530 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001531 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001532 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001533}
1534
Steve Naroff08d92e42007-09-15 18:49:24 +00001535Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 DeclTy *lastEnumConst,
1537 SourceLocation IdLoc, IdentifierInfo *Id,
1538 SourceLocation EqualLoc, ExprTy *val) {
1539 theEnumDecl = theEnumDecl; // silence unused warning.
1540 EnumConstantDecl *LastEnumConst =
1541 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1542 Expr *Val = static_cast<Expr*>(val);
1543
Chris Lattner31e05722007-08-26 06:24:45 +00001544 // The scope passed in may not be a decl scope. Zip up the scope tree until
1545 // we find one that is.
1546 while ((S->getFlags() & Scope::DeclScope) == 0)
1547 S = S->getParent();
1548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 // Verify that there isn't already something declared with this name in this
1550 // scope.
Steve Naroffe8043c32008-04-01 23:04:06 +00001551 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 if (S->isDeclScope(PrevDecl)) {
1553 if (isa<EnumConstantDecl>(PrevDecl))
1554 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1555 else
1556 Diag(IdLoc, diag::err_redefinition, Id->getName());
1557 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00001558 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 return 0;
1560 }
1561 }
1562
1563 llvm::APSInt EnumVal(32);
1564 QualType EltTy;
1565 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001566 // Make sure to promote the operand type to int.
1567 UsualUnaryConversions(Val);
1568
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1570 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001571 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1573 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00001574 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001575 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001576 } else {
1577 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001579 }
1580
1581 if (!Val) {
1582 if (LastEnumConst) {
1583 // Assign the last value + 1.
1584 EnumVal = LastEnumConst->getInitVal();
1585 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001586
1587 // Check for overflow on increment.
1588 if (EnumVal < LastEnumConst->getInitVal())
1589 Diag(IdLoc, diag::warn_enum_value_overflow);
1590
Chris Lattnerb7416f92007-08-27 17:37:24 +00001591 EltTy = LastEnumConst->getType();
1592 } else {
1593 // First value, set to zero.
1594 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001595 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001596 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 }
1598
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001599 EnumConstantDecl *New =
Chris Lattnerc63e6602008-03-15 21:32:50 +00001600 EnumConstantDecl::Create(Context, IdLoc, Id, EltTy, Val, EnumVal,
1601 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00001602
1603 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001604 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 Id->setFETokenInfo(New);
1606 S->AddDecl(New);
1607 return New;
1608}
1609
Steve Naroff08d92e42007-09-15 18:49:24 +00001610void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 DeclTy **Elements, unsigned NumElements) {
1612 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1613 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1614
Chris Lattnere37f0be2007-08-28 05:10:31 +00001615 // TODO: If the result value doesn't fit in an int, it must be a long or long
1616 // long value. ISO C does not support this, but GCC does as an extension,
1617 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00001618 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00001619
Chris Lattnerac609682007-08-28 06:15:15 +00001620 // Verify that all the values are okay, compute the size of the values, and
1621 // reverse the list.
1622 unsigned NumNegativeBits = 0;
1623 unsigned NumPositiveBits = 0;
1624
1625 // Keep track of whether all elements have type int.
1626 bool AllElementsInt = true;
1627
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 EnumConstantDecl *EltList = 0;
1629 for (unsigned i = 0; i != NumElements; ++i) {
1630 EnumConstantDecl *ECD =
1631 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1632 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001633
1634 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00001635 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00001636 assert(InitVal.getBitWidth() >= IntWidth &&
1637 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00001638 if (InitVal.getBitWidth() > IntWidth) {
1639 llvm::APSInt V(InitVal);
1640 V.trunc(IntWidth);
1641 V.extend(InitVal.getBitWidth());
1642 if (V != InitVal)
1643 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1644 InitVal.toString());
1645 }
Chris Lattnerac609682007-08-28 06:15:15 +00001646
1647 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00001648 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00001649 NumPositiveBits = std::max(NumPositiveBits,
1650 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00001651 else
Chris Lattner21dd8212008-01-14 21:47:29 +00001652 NumNegativeBits = std::max(NumNegativeBits,
1653 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001654
Chris Lattnerac609682007-08-28 06:15:15 +00001655 // Keep track of whether every enum element has type int (very commmon).
1656 if (AllElementsInt)
1657 AllElementsInt = ECD->getType() == Context.IntTy;
1658
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 ECD->setNextDeclarator(EltList);
1660 EltList = ECD;
1661 }
1662
Chris Lattnerac609682007-08-28 06:15:15 +00001663 // Figure out the type that should be used for this enum.
1664 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1665 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001666 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001667
1668 if (NumNegativeBits) {
1669 // If there is a negative value, figure out the smallest integer type (of
1670 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001671 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001672 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001673 BestWidth = IntWidth;
1674 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00001675 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001676
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001677 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001678 BestType = Context.LongTy;
1679 else {
Chris Lattner98be4942008-03-05 18:54:05 +00001680 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001681
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001682 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001683 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1684 BestType = Context.LongLongTy;
1685 }
1686 }
1687 } else {
1688 // If there is no negative value, figure out which of uint, ulong, ulonglong
1689 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001690 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001691 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001692 BestWidth = IntWidth;
1693 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00001694 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00001695 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00001696 } else {
1697 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001698 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001699 "How could an initializer get larger than ULL?");
1700 BestType = Context.UnsignedLongLongTy;
1701 }
1702 }
1703
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001704 // Loop over all of the enumerator constants, changing their types to match
1705 // the type of the enum if needed.
1706 for (unsigned i = 0; i != NumElements; ++i) {
1707 EnumConstantDecl *ECD =
1708 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1709 if (!ECD) continue; // Already issued a diagnostic.
1710
1711 // Standard C says the enumerators have int type, but we allow, as an
1712 // extension, the enumerators to be larger than int size. If each
1713 // enumerator value fits in an int, type it as an int, otherwise type it the
1714 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1715 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00001716 if (ECD->getType() == Context.IntTy) {
1717 // Make sure the init value is signed.
1718 llvm::APSInt IV = ECD->getInitVal();
1719 IV.setIsSigned(true);
1720 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001721 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00001722 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001723
1724 // Determine whether the value fits into an int.
1725 llvm::APSInt InitVal = ECD->getInitVal();
1726 bool FitsInInt;
1727 if (InitVal.isUnsigned() || !InitVal.isNegative())
1728 FitsInInt = InitVal.getActiveBits() < IntWidth;
1729 else
1730 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1731
1732 // If it fits into an integer type, force it. Otherwise force it to match
1733 // the enum decl type.
1734 QualType NewTy;
1735 unsigned NewWidth;
1736 bool NewSign;
1737 if (FitsInInt) {
1738 NewTy = Context.IntTy;
1739 NewWidth = IntWidth;
1740 NewSign = true;
1741 } else if (ECD->getType() == BestType) {
1742 // Already the right type!
1743 continue;
1744 } else {
1745 NewTy = BestType;
1746 NewWidth = BestWidth;
1747 NewSign = BestType->isSignedIntegerType();
1748 }
1749
1750 // Adjust the APSInt value.
1751 InitVal.extOrTrunc(NewWidth);
1752 InitVal.setIsSigned(NewSign);
1753 ECD->setInitVal(InitVal);
1754
1755 // Adjust the Expr initializer and type.
1756 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1757 ECD->setType(NewTy);
1758 }
Chris Lattnerac609682007-08-28 06:15:15 +00001759
Chris Lattnere00b18c2007-08-28 18:24:31 +00001760 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00001761 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00001762}
1763
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001764Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1765 ExprTy *expr) {
1766 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1767
Chris Lattner8e25d862008-03-16 00:16:02 +00001768 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00001769}
1770
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001771Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00001772 SourceLocation LBrace,
1773 SourceLocation RBrace,
1774 const char *Lang,
1775 unsigned StrSize,
1776 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001777 LinkageSpecDecl::LanguageIDs Language;
1778 Decl *dcl = static_cast<Decl *>(D);
1779 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1780 Language = LinkageSpecDecl::lang_c;
1781 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1782 Language = LinkageSpecDecl::lang_cxx;
1783 else {
1784 Diag(Loc, diag::err_bad_language);
1785 return 0;
1786 }
1787
1788 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00001789 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00001790}
1791
Chris Lattner74788ba2008-02-21 00:48:22 +00001792void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
Anders Carlsson6ede0ff2007-12-19 06:16:30 +00001793
Chris Lattner74788ba2008-02-21 00:48:22 +00001794 switch (Attr->getKind()) {
Chris Lattner212839c2008-02-20 23:17:35 +00001795 case AttributeList::AT_vector_size:
Reid Spencer5f016e22007-07-11 17:01:13 +00001796 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
Chris Lattner74788ba2008-02-21 00:48:22 +00001797 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 if (!newType.isNull()) // install the new vector type into the decl
1799 vDecl->setType(newType);
1800 }
1801 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1802 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001803 Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 if (!newType.isNull()) // install the new vector type into the decl
1805 tDecl->setUnderlyingType(newType);
1806 }
Chris Lattner212839c2008-02-20 23:17:35 +00001807 break;
1808 case AttributeList::AT_ocu_vector_type:
Steve Naroffbea0b342007-07-29 16:33:31 +00001809 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
Chris Lattner74788ba2008-02-21 00:48:22 +00001810 HandleOCUVectorTypeAttribute(tDecl, Attr);
Steve Naroffbea0b342007-07-29 16:33:31 +00001811 else
Chris Lattner74788ba2008-02-21 00:48:22 +00001812 Diag(Attr->getLoc(),
Steve Naroff73322922007-07-18 18:00:27 +00001813 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner212839c2008-02-20 23:17:35 +00001814 break;
1815 case AttributeList::AT_address_space:
Christopher Lambebb97e92008-02-04 02:31:56 +00001816 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1817 QualType newType = HandleAddressSpaceTypeAttribute(
1818 tDecl->getUnderlyingType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001819 Attr);
1820 tDecl->setUnderlyingType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001821 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1822 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Chris Lattner74788ba2008-02-21 00:48:22 +00001823 Attr);
1824 // install the new addr spaced type into the decl
1825 vDecl->setType(newType);
Christopher Lambebb97e92008-02-04 02:31:56 +00001826 }
Chris Lattner212839c2008-02-20 23:17:35 +00001827 break;
Chris Lattner7e669b22008-02-29 16:48:43 +00001828 case AttributeList::AT_deprecated:
Chris Lattnerddee4232008-03-03 03:28:21 +00001829 HandleDeprecatedAttribute(New, Attr);
1830 break;
1831 case AttributeList::AT_visibility:
1832 HandleVisibilityAttribute(New, Attr);
1833 break;
1834 case AttributeList::AT_weak:
1835 HandleWeakAttribute(New, Attr);
1836 break;
1837 case AttributeList::AT_dllimport:
1838 HandleDLLImportAttribute(New, Attr);
1839 break;
1840 case AttributeList::AT_dllexport:
1841 HandleDLLExportAttribute(New, Attr);
1842 break;
1843 case AttributeList::AT_nothrow:
1844 HandleNothrowAttribute(New, Attr);
Chris Lattner7e669b22008-02-29 16:48:43 +00001845 break;
Nate Begeman440b4562008-03-07 20:04:22 +00001846 case AttributeList::AT_stdcall:
1847 HandleStdCallAttribute(New, Attr);
1848 break;
1849 case AttributeList::AT_fastcall:
1850 HandleFastCallAttribute(New, Attr);
1851 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001852 case AttributeList::AT_aligned:
Chris Lattner74788ba2008-02-21 00:48:22 +00001853 HandleAlignedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001854 break;
1855 case AttributeList::AT_packed:
Chris Lattner74788ba2008-02-21 00:48:22 +00001856 HandlePackedAttribute(New, Attr);
Chris Lattner212839c2008-02-20 23:17:35 +00001857 break;
Nate Begemanc398f0b2008-02-21 19:30:49 +00001858 case AttributeList::AT_annotate:
1859 HandleAnnotateAttribute(New, Attr);
1860 break;
Ted Kremenekaecb3832008-02-27 20:43:06 +00001861 case AttributeList::AT_noreturn:
1862 HandleNoReturnAttribute(New, Attr);
1863 break;
Chris Lattnerddee4232008-03-03 03:28:21 +00001864 case AttributeList::AT_format:
1865 HandleFormatAttribute(New, Attr);
1866 break;
Chris Lattner212839c2008-02-20 23:17:35 +00001867 default:
Chris Lattner7e669b22008-02-29 16:48:43 +00001868#if 0
1869 // TODO: when we have the full set of attributes, warn about unknown ones.
1870 Diag(Attr->getLoc(), diag::warn_attribute_ignored,
1871 Attr->getName()->getName());
1872#endif
Chris Lattner212839c2008-02-20 23:17:35 +00001873 break;
1874 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001875}
1876
1877void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1878 AttributeList *declarator_postfix) {
1879 while (declspec_prefix) {
1880 HandleDeclAttribute(New, declspec_prefix);
1881 declspec_prefix = declspec_prefix->getNext();
1882 }
1883 while (declarator_postfix) {
1884 HandleDeclAttribute(New, declarator_postfix);
1885 declarator_postfix = declarator_postfix->getNext();
1886 }
1887}
1888
Steve Naroffbea0b342007-07-29 16:33:31 +00001889void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1890 AttributeList *rawAttr) {
1891 QualType curType = tDecl->getUnderlyingType();
Anders Carlsson78aaae92007-12-19 07:19:40 +00001892 // check the attribute arguments.
Steve Naroff73322922007-07-18 18:00:27 +00001893 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001894 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Steve Naroff73322922007-07-18 18:00:27 +00001895 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001896 return;
Steve Naroff73322922007-07-18 18:00:27 +00001897 }
1898 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1899 llvm::APSInt vecSize(32);
1900 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001901 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001902 "ocu_vector_type", sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001903 return;
Steve Naroff73322922007-07-18 18:00:27 +00001904 }
1905 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1906 // in conjunction with complex types (pointers, arrays, functions, etc.).
1907 Type *canonType = curType.getCanonicalType().getTypePtr();
1908 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001909 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Steve Naroff73322922007-07-18 18:00:27 +00001910 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001911 return;
Steve Naroff73322922007-07-18 18:00:27 +00001912 }
1913 // unlike gcc's vector_size attribute, the size is specified as the
1914 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001915 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001916
1917 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001918 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Steve Naroff73322922007-07-18 18:00:27 +00001919 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001920 return;
Steve Naroff73322922007-07-18 18:00:27 +00001921 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001922 // Instantiate/Install the vector type, the number of elements is > 0.
1923 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1924 // Remember this typedef decl, we will need it later for diagnostics.
1925 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001926}
1927
Reid Spencer5f016e22007-07-11 17:01:13 +00001928QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001929 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 // check the attribute arugments.
1931 if (rawAttr->getNumArgs() != 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00001932 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 std::string("1"));
1934 return QualType();
1935 }
1936 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1937 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001938 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00001939 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00001940 "vector_size", sizeExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 return QualType();
1942 }
1943 // navigate to the base type - we need to provide for vector pointers,
1944 // vector arrays, and functions returning vectors.
1945 Type *canonType = curType.getCanonicalType().getTypePtr();
1946
Steve Naroff73322922007-07-18 18:00:27 +00001947 if (canonType->isPointerType() || canonType->isArrayType() ||
1948 canonType->isFunctionType()) {
Chris Lattner54b263b2007-12-19 05:38:06 +00001949 assert(0 && "HandleVector(): Complex type construction unimplemented");
Steve Naroff73322922007-07-18 18:00:27 +00001950 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1951 do {
1952 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1953 canonType = PT->getPointeeType().getTypePtr();
1954 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1955 canonType = AT->getElementType().getTypePtr();
1956 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1957 canonType = FT->getResultType().getTypePtr();
1958 } while (canonType->isPointerType() || canonType->isArrayType() ||
1959 canonType->isFunctionType());
1960 */
Reid Spencer5f016e22007-07-11 17:01:13 +00001961 }
1962 // the base type must be integer or float.
1963 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Chris Lattner2070d802008-02-20 23:25:22 +00001964 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
Reid Spencer5f016e22007-07-11 17:01:13 +00001965 curType.getCanonicalType().getAsString());
1966 return QualType();
1967 }
Chris Lattner98be4942008-03-05 18:54:05 +00001968 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001970 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00001971
1972 // the vector size needs to be an integral multiple of the type size.
1973 if (vectorSize % typeSize) {
Chris Lattner2070d802008-02-20 23:25:22 +00001974 Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 sizeExpr->getSourceRange());
1976 return QualType();
1977 }
1978 if (vectorSize == 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001979 Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 sizeExpr->getSourceRange());
1981 return QualType();
1982 }
Nate Begemanc398f0b2008-02-21 19:30:49 +00001983 // Instantiate the vector type, the number of elements is > 0, and not
1984 // required to be a power of 2, unlike GCC.
Steve Naroff73322922007-07-18 18:00:27 +00001985 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00001986}
1987
Chris Lattner2070d802008-02-20 23:25:22 +00001988void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
Anders Carlssonad148062008-02-16 00:29:18 +00001989 // check the attribute arguments.
1990 if (rawAttr->getNumArgs() > 0) {
Chris Lattner2070d802008-02-20 23:25:22 +00001991 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlssonad148062008-02-16 00:29:18 +00001992 std::string("0"));
1993 return;
1994 }
1995
1996 if (TagDecl *TD = dyn_cast<TagDecl>(d))
1997 TD->addAttr(new PackedAttr);
1998 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
1999 // If the alignment is less than or equal to 8 bits, the packed attribute
2000 // has no effect.
Chris Lattner98be4942008-03-05 18:54:05 +00002001 if (Context.getTypeAlign(FD->getType()) <= 8)
Chris Lattner2070d802008-02-20 23:25:22 +00002002 Diag(rawAttr->getLoc(),
Anders Carlssonad148062008-02-16 00:29:18 +00002003 diag::warn_attribute_ignored_for_field_of_type,
Chris Lattner2070d802008-02-20 23:25:22 +00002004 rawAttr->getName()->getName(), FD->getType().getAsString());
Anders Carlssonad148062008-02-16 00:29:18 +00002005 else
Anders Carlsson425a6092008-02-16 00:39:40 +00002006 FD->addAttr(new PackedAttr);
Anders Carlssonad148062008-02-16 00:29:18 +00002007 } else
Chris Lattner2070d802008-02-20 23:25:22 +00002008 Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
2009 rawAttr->getName()->getName());
Anders Carlssonad148062008-02-16 00:29:18 +00002010}
Nate Begemanc398f0b2008-02-21 19:30:49 +00002011
Ted Kremenekaecb3832008-02-27 20:43:06 +00002012void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
2013 // check the attribute arguments.
2014 if (rawAttr->getNumArgs() != 0) {
2015 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2016 std::string("0"));
2017 return;
2018 }
2019
Ted Kremenek3465fb32008-03-03 16:52:27 +00002020 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2021
2022 if (!Fn) {
2023 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2024 "noreturn", "function");
2025 return;
2026 }
2027
Ted Kremenekaecb3832008-02-27 20:43:06 +00002028 d->addAttr(new NoReturnAttr());
2029}
2030
Chris Lattnerddee4232008-03-03 03:28:21 +00002031void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
2032 // check the attribute arguments.
2033 if (rawAttr->getNumArgs() != 0) {
2034 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2035 std::string("0"));
2036 return;
2037 }
2038
2039 d->addAttr(new DeprecatedAttr());
2040}
2041
2042void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
2043 // check the attribute arguments.
Chris Lattner7b937ae2008-03-04 18:08:48 +00002044 if (rawAttr->getNumArgs() != 1) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002045 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2046 std::string("1"));
2047 return;
2048 }
2049
Chris Lattner7b937ae2008-03-04 18:08:48 +00002050 Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
2051 Arg = Arg->IgnoreParenCasts();
2052 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2053
2054 if (Str == 0 || Str->isWide()) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002055 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002056 "visibility", std::string("1"));
Chris Lattnerddee4232008-03-03 03:28:21 +00002057 return;
2058 }
2059
Chris Lattner7b937ae2008-03-04 18:08:48 +00002060 const char *TypeStr = Str->getStrData();
2061 unsigned TypeLen = Str->getByteLength();
Chris Lattnerddee4232008-03-03 03:28:21 +00002062 llvm::GlobalValue::VisibilityTypes type;
2063
Chris Lattner7b937ae2008-03-04 18:08:48 +00002064 if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
Chris Lattnerddee4232008-03-03 03:28:21 +00002065 type = llvm::GlobalValue::DefaultVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002066 else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
Chris Lattnerddee4232008-03-03 03:28:21 +00002067 type = llvm::GlobalValue::HiddenVisibility;
Chris Lattner7b937ae2008-03-04 18:08:48 +00002068 else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
Chris Lattnerddee4232008-03-03 03:28:21 +00002069 type = llvm::GlobalValue::HiddenVisibility; // FIXME
Chris Lattner7b937ae2008-03-04 18:08:48 +00002070 else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
Chris Lattnerddee4232008-03-03 03:28:21 +00002071 type = llvm::GlobalValue::ProtectedVisibility;
2072 else {
2073 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
Chris Lattner7b937ae2008-03-04 18:08:48 +00002074 "visibility", TypeStr);
Chris Lattnerddee4232008-03-03 03:28:21 +00002075 return;
2076 }
2077
2078 d->addAttr(new VisibilityAttr(type));
2079}
2080
2081void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
2082 // check the attribute arguments.
2083 if (rawAttr->getNumArgs() != 0) {
2084 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2085 std::string("0"));
2086 return;
2087 }
2088
2089 d->addAttr(new WeakAttr());
2090}
2091
2092void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
2093 // check the attribute arguments.
2094 if (rawAttr->getNumArgs() != 0) {
2095 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2096 std::string("0"));
2097 return;
2098 }
2099
2100 d->addAttr(new DLLImportAttr());
2101}
2102
2103void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
2104 // check the attribute arguments.
2105 if (rawAttr->getNumArgs() != 0) {
2106 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2107 std::string("0"));
2108 return;
2109 }
2110
2111 d->addAttr(new DLLExportAttr());
2112}
2113
Nate Begeman440b4562008-03-07 20:04:22 +00002114void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
2115 // check the attribute arguments.
2116 if (rawAttr->getNumArgs() != 0) {
2117 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2118 std::string("0"));
2119 return;
2120 }
2121
2122 d->addAttr(new StdCallAttr());
2123}
2124
2125void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
2126 // check the attribute arguments.
2127 if (rawAttr->getNumArgs() != 0) {
2128 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2129 std::string("0"));
2130 return;
2131 }
2132
2133 d->addAttr(new FastCallAttr());
2134}
2135
Chris Lattnerddee4232008-03-03 03:28:21 +00002136void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
2137 // check the attribute arguments.
2138 if (rawAttr->getNumArgs() != 0) {
2139 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2140 std::string("0"));
2141 return;
2142 }
2143
2144 d->addAttr(new NoThrowAttr());
2145}
2146
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002147static const FunctionTypeProto *getFunctionProto(Decl *d) {
2148 ValueDecl *decl = dyn_cast<ValueDecl>(d);
2149 if (!decl) return 0;
2150
2151 QualType Ty = decl->getType();
2152
2153 if (Ty->isFunctionPointerType()) {
2154 const PointerType *PtrTy = Ty->getAsPointerType();
2155 Ty = PtrTy->getPointeeType();
2156 }
2157
2158 if (const FunctionType *FnTy = Ty->getAsFunctionType())
2159 return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
2160
2161 return 0;
2162}
2163
2164
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002165/// Handle __attribute__((format(type,idx,firstarg))) attributes
2166/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chris Lattnerddee4232008-03-03 03:28:21 +00002167void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
2168
2169 if (!rawAttr->getParameterName()) {
2170 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
2171 "format", std::string("1"));
2172 return;
2173 }
2174
2175 if (rawAttr->getNumArgs() != 2) {
2176 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2177 std::string("3"));
2178 return;
2179 }
2180
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002181 // GCC ignores the format attribute on K&R style function
2182 // prototypes, so we ignore it as well
2183 const FunctionTypeProto *proto = getFunctionProto(d);
2184
2185 if (!proto) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002186 Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
2187 "format", "function");
2188 return;
2189 }
2190
2191 // FIXME: in C++ the implicit 'this' function parameter also counts.
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002192 // this is needed in order to be compatible with GCC
Chris Lattnerddee4232008-03-03 03:28:21 +00002193 // the index must start in 1 and the limit is numargs+1
Nuno Lopes8c1a9a82008-03-25 23:01:48 +00002194 unsigned NumArgs = proto->getNumArgs();
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002195 unsigned FirstIdx = 1;
Chris Lattnerddee4232008-03-03 03:28:21 +00002196
2197 const char *Format = rawAttr->getParameterName()->getName();
2198 unsigned FormatLen = rawAttr->getParameterName()->getLength();
2199
2200 // Normalize the argument, __foo__ becomes foo.
2201 if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
2202 Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
2203 Format += 2;
2204 FormatLen -= 4;
2205 }
2206
2207 if (!((FormatLen == 5 && !memcmp(Format, "scanf", 5))
2208 || (FormatLen == 6 && !memcmp(Format, "printf", 6))
2209 || (FormatLen == 7 && !memcmp(Format, "strfmon", 7))
2210 || (FormatLen == 8 && !memcmp(Format, "strftime", 8)))) {
2211 Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
2212 "format", rawAttr->getParameterName()->getName());
2213 return;
2214 }
2215
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002216 // checks for the 2nd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002217 Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002218 llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002219 if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
2220 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2221 "format", std::string("2"), IdxExpr->getSourceRange());
2222 return;
2223 }
2224
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002225 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002226 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2227 "format", std::string("2"), IdxExpr->getSourceRange());
2228 return;
2229 }
2230
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002231 // make sure the format string is really a string
2232 QualType Ty = proto->getArgType(Idx.getZExtValue()-1);
2233 if (!Ty->isPointerType() ||
2234 !Ty->getAsPointerType()->getPointeeType()->isCharType()) {
2235 Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
2236 IdxExpr->getSourceRange());
2237 return;
2238 }
2239
2240
2241 // check the 3rd argument
Chris Lattnerddee4232008-03-03 03:28:21 +00002242 Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002243 llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
Chris Lattnerddee4232008-03-03 03:28:21 +00002244 if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
2245 Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
2246 "format", std::string("3"), FirstArgExpr->getSourceRange());
2247 return;
2248 }
2249
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002250 // check if the function is variadic if the 3rd argument non-zero
2251 if (FirstArg != 0) {
2252 if (proto->isVariadic()) {
2253 ++NumArgs; // +1 for ...
2254 } else {
2255 Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
2256 return;
2257 }
2258 }
2259
2260 // strftime requires FirstArg to be 0 because it doesn't read from any variable
2261 // the input is just the current time + the format string
Chris Lattnerddee4232008-03-03 03:28:21 +00002262 if (FormatLen == 8 && !memcmp(Format, "strftime", 8)) {
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002263 if (FirstArg != 0) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002264 Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
2265 FirstArgExpr->getSourceRange());
2266 return;
2267 }
Ted Kremenekaa8f9762008-03-07 18:43:49 +00002268 // if 0 it disables parameter checking (to use with e.g. va_list)
2269 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattnerddee4232008-03-03 03:28:21 +00002270 Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
2271 "format", std::string("3"), FirstArgExpr->getSourceRange());
2272 return;
2273 }
2274
2275 d->addAttr(new FormatAttr(std::string(Format, FormatLen),
2276 Idx.getZExtValue(), FirstArg.getZExtValue()));
2277}
2278
Nate Begemanc398f0b2008-02-21 19:30:49 +00002279void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
2280 // check the attribute arguments.
2281 if (rawAttr->getNumArgs() != 1) {
2282 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
2283 std::string("1"));
2284 return;
2285 }
2286 Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
2287 StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
Anders Carlssonad148062008-02-16 00:29:18 +00002288
Nate Begemanc398f0b2008-02-21 19:30:49 +00002289 // Make sure that there is a string literal as the annotation's single
2290 // argument.
2291 if (!SE) {
2292 Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
2293 return;
2294 }
2295 d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
2296 SE->getByteLength())));
2297}
2298
Anders Carlsson78aaae92007-12-19 07:19:40 +00002299void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
2300{
2301 // check the attribute arguments.
Eli Friedman4ca08672008-01-30 17:38:42 +00002302 if (rawAttr->getNumArgs() > 1) {
Chris Lattner2070d802008-02-20 23:25:22 +00002303 Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
Anders Carlsson78aaae92007-12-19 07:19:40 +00002304 std::string("1"));
2305 return;
2306 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002307
Anders Carlsson042c4e72008-02-16 19:51:27 +00002308 unsigned Align = 0;
2309
2310 if (rawAttr->getNumArgs() == 0) {
2311 // FIXME: This should be the target specific maximum alignment.
2312 // (For now we just use 128 bits which is the maximum on X86.
2313 Align = 128;
Eli Friedman4ca08672008-01-30 17:38:42 +00002314 return;
Anders Carlsson042c4e72008-02-16 19:51:27 +00002315 } else {
2316 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
2317 llvm::APSInt alignment(32);
2318 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Chris Lattner2070d802008-02-20 23:25:22 +00002319 Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
Anders Carlsson042c4e72008-02-16 19:51:27 +00002320 "aligned", alignmentExpr->getSourceRange());
2321 return;
2322 }
2323
2324 Align = alignment.getZExtValue() * 8;
2325 }
Eli Friedman4ca08672008-01-30 17:38:42 +00002326
Anders Carlsson042c4e72008-02-16 19:51:27 +00002327 d->addAttr(new AlignedAttr(Align));
Anders Carlsson78aaae92007-12-19 07:19:40 +00002328}