blob: c6f1203e6822a7c0a90de8502d7633f4d98f88e1 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000015#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/Builtins.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000025#include "clang/Basic/SourceManager.h"
26// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000027#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000028#include "clang/Lex/HeaderSearch.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000029#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000031#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Chris Lattner4b009652007-07-25 00:24:17 +000034Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000035 Decl *IIDecl = II.getFETokenInfo<Decl>();
36 // Find first occurance of none-tagged declaration
37 while(IIDecl && IIDecl->getIdentifierNamespace() != Decl::IDNS_Ordinary)
38 IIDecl = cast<ScopedDecl>(IIDecl)->getNext();
39 if (!IIDecl)
40 return 0;
Ted Kremenek42730c52008-01-07 19:49:32 +000041 if (isa<TypedefDecl>(IIDecl) || isa<ObjCInterfaceDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000042 return IIDecl;
Ted Kremenek42730c52008-01-07 19:49:32 +000043 if (ObjCCompatibleAliasDecl *ADecl =
44 dyn_cast<ObjCCompatibleAliasDecl>(IIDecl))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000045 return ADecl->getClassInterface();
Steve Naroff81f1bba2007-09-06 21:24:23 +000046 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000047}
48
Steve Naroff9637a9b2007-10-09 22:01:59 +000049void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000050 if (S->decl_empty()) return;
51 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
52
Chris Lattner4b009652007-07-25 00:24:17 +000053 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
54 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000055 Decl *TmpD = static_cast<Decl*>(*I);
56 assert(TmpD && "This decl didn't get pushed??");
57 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
58 assert(D && "This decl isn't a ScopedDecl?");
59
Chris Lattner4b009652007-07-25 00:24:17 +000060 IdentifierInfo *II = D->getIdentifier();
61 if (!II) continue;
62
63 // Unlink this decl from the identifier. Because the scope contains decls
64 // in an unordered collection, and because we have multiple identifier
65 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
66 if (II->getFETokenInfo<Decl>() == D) {
67 // Normal case, no multiple decls in different namespaces.
68 II->setFETokenInfo(D->getNext());
69 } else {
70 // Scan ahead. There are only three namespaces in C, so this loop can
71 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000072 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000073 while (SomeDecl->getNext() != D) {
74 SomeDecl = SomeDecl->getNext();
75 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
76 }
77 SomeDecl->setNext(D->getNext());
78 }
79
80 // This will have to be revisited for C++: there we want to nest stuff in
81 // namespace decls etc. Even for C, we might want a top-level translation
82 // unit decl or something.
83 if (!CurFunctionDecl)
84 continue;
85
86 // Chain this decl to the containing function, it now owns the memory for
87 // the decl.
88 D->setNext(CurFunctionDecl->getDeclChain());
89 CurFunctionDecl->setDeclChain(D);
90 }
91}
92
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000093/// LookupInterfaceDecl - Lookup interface declaration in the scope chain.
94/// Return the first declaration found (which may or may not be a class
Fariborz Jahanian8eaeff52007-10-12 19:53:08 +000095/// declaration. Caller is responsible for handling the none-class case.
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +000096/// Bypassing the alias of a class by returning the aliased class.
97ScopedDecl *Sema::LookupInterfaceDecl(IdentifierInfo *ClassName) {
98 ScopedDecl *IDecl;
99 // Scan up the scope chain looking for a decl that matches this identifier
100 // that is in the appropriate namespace.
101 for (IDecl = ClassName->getFETokenInfo<ScopedDecl>(); IDecl;
102 IDecl = IDecl->getNext())
103 if (IDecl->getIdentifierNamespace() == Decl::IDNS_Ordinary)
104 break;
105
Ted Kremenek42730c52008-01-07 19:49:32 +0000106 if (ObjCCompatibleAliasDecl *ADecl =
107 dyn_cast_or_null<ObjCCompatibleAliasDecl>(IDecl))
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000108 return ADecl->getClassInterface();
109 return IDecl;
110}
111
Ted Kremenek42730c52008-01-07 19:49:32 +0000112/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000113/// return 0 if one not found.
Ted Kremenek42730c52008-01-07 19:49:32 +0000114ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000115 ScopedDecl *IdDecl = LookupInterfaceDecl(Id);
Ted Kremenek42730c52008-01-07 19:49:32 +0000116 return cast_or_null<ObjCInterfaceDecl>(IdDecl);
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +0000117}
118
Chris Lattner4b009652007-07-25 00:24:17 +0000119/// LookupScopedDecl - Look up the inner-most declaration in the specified
120/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000121ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
122 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffd21bc0d2007-09-13 18:10:37 +0000129 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +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) {
137 // If this is a builtin on some other target, or if this builtin varies
138 // across targets (e.g. in type), emit a diagnostic and mark the translation
139 // unit non-portable for using it.
140 if (II->isNonPortableBuiltin()) {
141 // Only emit this diagnostic once for this builtin.
142 II->setNonPortableBuiltin(false);
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000143 Context.Target.DiagnoseNonPortability(Context.getFullLoc(IdLoc),
Chris Lattner4b009652007-07-25 00:24:17 +0000144 diag::port_target_builtin_use);
145 }
146 // If this is a builtin on this (or all) targets, create the decl.
147 if (unsigned BuiltinID = II->getBuiltinID())
148 return LazilyCreateBuiltin(II, BuiltinID, S);
149 }
150 return 0;
151}
152
Anders Carlsson36760332007-10-15 20:28:48 +0000153void Sema::InitBuiltinVaListType()
154{
155 if (!Context.getBuiltinVaListType().isNull())
156 return;
157
158 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
159 ScopedDecl *VaDecl = LookupScopedDecl(VaIdent, Decl::IDNS_Ordinary,
160 SourceLocation(), TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000161 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000162 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
163}
164
Chris Lattner4b009652007-07-25 00:24:17 +0000165/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
166/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000167ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
168 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000169 Builtin::ID BID = (Builtin::ID)bid;
170
Anders Carlsson36760332007-10-15 20:28:48 +0000171 if (BID == Builtin::BI__builtin_va_start ||
Anders Carlssoncebb8d62007-10-12 23:56:29 +0000172 BID == Builtin::BI__builtin_va_copy ||
Anders Carlsson36760332007-10-15 20:28:48 +0000173 BID == Builtin::BI__builtin_va_end)
174 InitBuiltinVaListType();
175
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000176 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000177 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000178 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000179
180 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000181 if (Scope *FnS = S->getFnParent())
182 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000183 while (S->getParent())
184 S = S->getParent();
185 S->AddDecl(New);
186
187 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000188 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000189 // Scan until we find the last (outermost) decl in the id chain.
190 while (LastDecl->getNext())
191 LastDecl = LastDecl->getNext();
192 // Insert before (outside) it.
193 LastDecl->setNext(New);
194 } else {
195 II->setFETokenInfo(New);
196 }
Chris Lattner4b009652007-07-25 00:24:17 +0000197 return New;
198}
199
200/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
201/// and scope as a previous declaration 'Old'. Figure out how to resolve this
202/// situation, merging decls or emitting diagnostics as appropriate.
203///
Steve Naroffcb597472007-09-13 21:41:19 +0000204TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000205 // Verify the old decl was also a typedef.
206 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
207 if (!Old) {
208 Diag(New->getLocation(), diag::err_redefinition_different_kind,
209 New->getName());
210 Diag(OldD->getLocation(), diag::err_previous_definition);
211 return New;
212 }
213
Steve Naroffae84af82007-10-31 18:42:27 +0000214 // Allow multiple definitions for ObjC built-in typedefs.
215 // FIXME: Verify the underlying types are equivalent!
Ted Kremenek42730c52008-01-07 19:49:32 +0000216 if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
Steve Naroffae84af82007-10-31 18:42:27 +0000217 return Old;
Steve Naroffa9eae582008-01-30 23:46:05 +0000218
219 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
220 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
221 // *either* declaration is in a system header. The code below implements
222 // this adhoc compatibility rule. FIXME: The following code will not
223 // work properly when compiling ".i" files (containing preprocessed output).
224 SourceManager &SrcMgr = Context.getSourceManager();
225 const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
226 const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
227 HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
228 DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
229 DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
230
Steve Naroff73a07032008-02-07 03:50:06 +0000231 if ((OldDirType == DirectoryLookup::ExternCSystemHeaderDir ||
232 NewDirType == DirectoryLookup::ExternCSystemHeaderDir) ||
233 getLangOptions().Microsoft)
Steve Naroffa9eae582008-01-30 23:46:05 +0000234 return New;
Steve Naroffae84af82007-10-31 18:42:27 +0000235
Chris Lattner4b009652007-07-25 00:24:17 +0000236 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
237 // TODO: This is totally simplistic. It should handle merging functions
238 // together etc, merging extern int X; int X; ...
239 Diag(New->getLocation(), diag::err_redefinition, New->getName());
240 Diag(Old->getLocation(), diag::err_previous_definition);
241 return New;
242}
243
244/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
245/// and scope as a previous declaration 'Old'. Figure out how to resolve this
246/// situation, merging decls or emitting diagnostics as appropriate.
247///
Steve Naroffcb597472007-09-13 21:41:19 +0000248FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000249 // Verify the old decl was also a function.
250 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
251 if (!Old) {
252 Diag(New->getLocation(), diag::err_redefinition_different_kind,
253 New->getName());
254 Diag(OldD->getLocation(), diag::err_previous_definition);
255 return New;
256 }
257
Chris Lattner60476ff2007-11-20 19:04:50 +0000258 QualType OldQType = Old->getCanonicalType();
259 QualType NewQType = New->getCanonicalType();
260
261 // This is not right, but it's a start.
262 // If Old is a function prototype with no defined arguments we only compare
263 // the return type; If arguments are defined on the prototype we validate the
264 // entire function type.
265 // FIXME: We should link up decl objects here.
266 if (Old->getBody() == 0) {
267 if (OldQType.getTypePtr()->getTypeClass() == Type::FunctionNoProto &&
268 Old->getResultType() == New->getResultType())
269 return New;
Chris Lattner4b009652007-07-25 00:24:17 +0000270 }
Steve Naroff1d5bd642008-01-14 20:51:29 +0000271 // Function types need to be compatible, not identical. This handles
272 // duplicate function decls like "void f(int); void f(enum X);" properly.
273 if (Context.functionTypesAreCompatible(OldQType, NewQType))
274 return New;
Chris Lattner1470b072007-11-06 06:07:26 +0000275
Steve Naroff6c9e7922008-01-16 15:01:34 +0000276 // A function that has already been declared has been redeclared or defined
277 // with a different type- show appropriate diagnostic
278 diag::kind PrevDiag = Old->getBody() ? diag::err_previous_definition :
279 diag::err_previous_declaration;
280
Chris Lattner4b009652007-07-25 00:24:17 +0000281 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
282 // TODO: This is totally simplistic. It should handle merging functions
283 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000284 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
285 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000286 return New;
287}
288
Chris Lattnerf9167d12007-11-06 04:28:31 +0000289
290/// hasUndefinedLength - Used by equivalentArrayTypes to determine whether the
291/// the outermost VariableArrayType has no size defined.
292static bool hasUndefinedLength(const ArrayType *Array) {
293 const VariableArrayType *VAT = Array->getAsVariableArrayType();
294 return VAT && !VAT->getSizeExpr();
295}
296
297/// equivalentArrayTypes - Used to determine whether two array types are
298/// equivalent.
299/// We need to check this explicitly as an incomplete array definition is
300/// considered a VariableArrayType, so will not match a complete array
301/// definition that would be otherwise equivalent.
302static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
303 const ArrayType *NewAT = NewQType->getAsArrayType();
304 const ArrayType *OldAT = OldQType->getAsArrayType();
305
306 if (!NewAT || !OldAT)
307 return false;
308
309 // If either (or both) array types in incomplete we need to strip off the
310 // outer VariableArrayType. Once the outer VAT is removed the remaining
311 // types must be identical if the array types are to be considered
312 // equivalent.
313 // eg. int[][1] and int[1][1] become
314 // VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
315 // removing the outermost VAT gives
316 // CAT(1, int) and CAT(1, int)
317 // which are equal, therefore the array types are equivalent.
318 if (hasUndefinedLength(NewAT) || hasUndefinedLength(OldAT)) {
319 if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
320 return false;
Eli Friedmand32157f2008-01-29 07:51:12 +0000321 NewQType = NewAT->getElementType().getCanonicalType();
322 OldQType = OldAT->getElementType().getCanonicalType();
Chris Lattnerf9167d12007-11-06 04:28:31 +0000323 }
324
325 return NewQType == OldQType;
326}
327
Chris Lattner4b009652007-07-25 00:24:17 +0000328/// MergeVarDecl - We just parsed a variable 'New' which has the same name
329/// and scope as a previous declaration 'Old'. Figure out how to resolve this
330/// situation, merging decls or emitting diagnostics as appropriate.
331///
332/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
333/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
334///
Steve Naroffcb597472007-09-13 21:41:19 +0000335VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000336 // Verify the old decl was also a variable.
337 VarDecl *Old = dyn_cast<VarDecl>(OldD);
338 if (!Old) {
339 Diag(New->getLocation(), diag::err_redefinition_different_kind,
340 New->getName());
341 Diag(OldD->getLocation(), diag::err_previous_definition);
342 return New;
343 }
344 // Verify the types match.
Chris Lattnerf9167d12007-11-06 04:28:31 +0000345 if (Old->getCanonicalType() != New->getCanonicalType() &&
346 !areEquivalentArrayTypes(New->getCanonicalType(), Old->getCanonicalType())) {
Chris Lattner4b009652007-07-25 00:24:17 +0000347 Diag(New->getLocation(), diag::err_redefinition, New->getName());
348 Diag(Old->getLocation(), diag::err_previous_definition);
349 return New;
350 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000351 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
352 if (New->getStorageClass() == VarDecl::Static &&
353 (Old->getStorageClass() == VarDecl::None ||
354 Old->getStorageClass() == VarDecl::Extern)) {
355 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
356 Diag(Old->getLocation(), diag::err_previous_definition);
357 return New;
358 }
359 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
360 if (New->getStorageClass() != VarDecl::Static &&
361 Old->getStorageClass() == VarDecl::Static) {
362 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
363 Diag(Old->getLocation(), diag::err_previous_definition);
364 return New;
365 }
366 // We've verified the types match, now handle "tentative" definitions.
367 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
368 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
369
370 if (OldFSDecl && NewFSDecl) {
371 // Handle C "tentative" external object definitions (C99 6.9.2).
372 bool OldIsTentative = false;
373 bool NewIsTentative = false;
374
375 if (!OldFSDecl->getInit() &&
376 (OldFSDecl->getStorageClass() == VarDecl::None ||
377 OldFSDecl->getStorageClass() == VarDecl::Static))
378 OldIsTentative = true;
379
380 // FIXME: this check doesn't work (since the initializer hasn't been
381 // attached yet). This check should be moved to FinalizeDeclaratorGroup.
382 // Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
383 // thrown out the old decl.
384 if (!NewFSDecl->getInit() &&
385 (NewFSDecl->getStorageClass() == VarDecl::None ||
386 NewFSDecl->getStorageClass() == VarDecl::Static))
387 ; // change to NewIsTentative = true; once the code is moved.
388
389 if (NewIsTentative || OldIsTentative)
390 return New;
391 }
392 if (Old->getStorageClass() != VarDecl::Extern &&
393 New->getStorageClass() != VarDecl::Extern) {
Chris Lattner4b009652007-07-25 00:24:17 +0000394 Diag(New->getLocation(), diag::err_redefinition, New->getName());
395 Diag(Old->getLocation(), diag::err_previous_definition);
396 }
397 return New;
398}
399
400/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
401/// no declarator (e.g. "struct foo;") is parsed.
402Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
403 // TODO: emit error on 'int;' or 'const enum foo;'.
404 // TODO: emit error on 'typedef int;'
405 // if (!DS.isMissingDeclaratorOk()) Diag(...);
406
Steve Naroffedafc0b2007-11-17 21:37:36 +0000407 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000408}
409
Steve Narofff0b23542008-01-10 22:15:12 +0000410bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000411 // Get the type before calling CheckSingleAssignmentConstraints(), since
412 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000413 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000414
Chris Lattner005ed752008-01-04 18:04:52 +0000415 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
416 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
417 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000418}
419
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000420bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
Steve Narofff0b23542008-01-10 22:15:12 +0000421 QualType ElementType) {
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000422 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Narofff0b23542008-01-10 22:15:12 +0000423 if (CheckSingleInitializer(expr, ElementType))
Chris Lattnerba0f1cb2007-12-11 23:15:04 +0000424 return true; // types weren't compatible.
425
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000426 if (savExpr != expr) // The type was promoted, update initializer list.
427 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000428 return false;
429}
430
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000431bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
432 if (const VariableArrayType *VAT = DeclT->getAsIncompleteArrayType()) {
433 // C99 6.7.8p14. We have an array of character type with unknown size
434 // being initialized to a string literal.
435 llvm::APSInt ConstVal(32);
436 ConstVal = strLiteral->getByteLength() + 1;
437 // Return a new array type (C99 6.7.8p22).
438 DeclT = Context.getConstantArrayType(VAT->getElementType(), ConstVal,
439 ArrayType::Normal, 0);
440 } else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
441 // C99 6.7.8p14. We have an array of character type with known size.
442 if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
443 Diag(strLiteral->getSourceRange().getBegin(),
444 diag::warn_initializer_string_for_char_array_too_long,
445 strLiteral->getSourceRange());
446 } else {
447 assert(0 && "HandleStringLiteralInit(): Invalid array type");
448 }
449 // Set type from "char *" to "constant array of char".
450 strLiteral->setType(DeclT);
451 // For now, we always return false (meaning success).
452 return false;
453}
454
455StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000456 const ArrayType *AT = DeclType->getAsArrayType();
Steve Narofff3cb5142008-01-25 00:51:06 +0000457 if (AT && AT->getElementType()->isCharType()) {
458 return dyn_cast<StringLiteral>(Init);
459 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000460 return 0;
461}
462
Steve Narofff3cb5142008-01-25 00:51:06 +0000463// CheckInitializerListTypes - Checks the types of elements of an initializer
464// list. This function is recursive: it calls itself to initialize subelements
465// of aggregate types. Note that the topLevel parameter essentially refers to
466// whether this expression "owns" the initializer list passed in, or if this
467// initialization is taking elements out of a parent initializer. Each
468// call to this function adds zero or more to startIndex, reports any errors,
469// and returns true if it found any inconsistent types.
470bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
471 bool topLevel, unsigned& startIndex) {
Steve Naroffcb69fb72007-12-10 22:44:33 +0000472 bool hadError = false;
Steve Narofff3cb5142008-01-25 00:51:06 +0000473
474 if (DeclType->isScalarType()) {
475 // The simplest case: initializing a single scalar
476 if (topLevel) {
477 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
478 IList->getSourceRange());
479 }
480 if (startIndex < IList->getNumInits()) {
481 Expr* expr = IList->getInit(startIndex);
482 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
483 // FIXME: Should an error be reported here instead?
484 unsigned newIndex = 0;
485 CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
486 } else {
487 hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
488 }
489 ++startIndex;
490 }
491 // FIXME: Should an error be reported for empty initializer list + scalar?
492 } else if (DeclType->isVectorType()) {
493 if (startIndex < IList->getNumInits()) {
494 const VectorType *VT = DeclType->getAsVectorType();
495 int maxElements = VT->getNumElements();
496 QualType elementType = VT->getElementType();
497
498 for (int i = 0; i < maxElements; ++i) {
499 // Don't attempt to go past the end of the init list
500 if (startIndex >= IList->getNumInits())
501 break;
502 Expr* expr = IList->getInit(startIndex);
503 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
504 unsigned newIndex = 0;
505 hadError |= CheckInitializerListTypes(SubInitList, elementType,
506 true, newIndex);
507 ++startIndex;
508 } else {
509 hadError |= CheckInitializerListTypes(IList, elementType,
510 false, startIndex);
511 }
512 }
513 }
514 } else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
515 if (DeclType->isStructureType() || DeclType->isUnionType()) {
Steve Naroffedce4ec2008-01-28 02:00:41 +0000516 if (startIndex < IList->getNumInits() && !topLevel &&
517 Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
518 DeclType)) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000519 // We found a compatible struct; per the standard, this initializes the
520 // struct. (The C standard technically says that this only applies for
521 // initializers for declarations with automatic scope; however, this
522 // construct is unambiguous anyway because a struct cannot contain
523 // a type compatible with itself. We'll output an error when we check
524 // if the initializer is constant.)
525 // FIXME: Is a call to CheckSingleInitializer required here?
526 ++startIndex;
527 } else {
528 RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
Steve Naroffee467032008-02-11 00:06:17 +0000529
530 // If the record is invalid, it's members can't be trusted.
531 if (structDecl->isInvalidDecl())
532 return true;
533
Steve Narofff3cb5142008-01-25 00:51:06 +0000534 // If structDecl is a forward declaration, this loop won't do anything;
535 // That's okay, because an error should get printed out elsewhere. It
536 // might be worthwhile to skip over the rest of the initializer, though.
537 int numMembers = structDecl->getNumMembers() -
538 structDecl->hasFlexibleArrayMember();
539 for (int i = 0; i < numMembers; i++) {
540 // Don't attempt to go past the end of the init list
541 if (startIndex >= IList->getNumInits())
542 break;
543 FieldDecl * curField = structDecl->getMember(i);
544 if (!curField->getIdentifier()) {
545 // Don't initialize unnamed fields, e.g. "int : 20;"
546 continue;
547 }
548 QualType fieldType = curField->getType();
549 Expr* expr = IList->getInit(startIndex);
550 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
551 unsigned newStart = 0;
552 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
553 true, newStart);
554 ++startIndex;
555 } else {
556 hadError |= CheckInitializerListTypes(IList, fieldType,
557 false, startIndex);
558 }
559 if (DeclType->isUnionType())
560 break;
561 }
562 // FIXME: Implement flexible array initialization GCC extension (it's a
563 // really messy extension to implement, unfortunately...the necessary
564 // information isn't actually even here!)
565 }
566 } else if (DeclType->isArrayType()) {
567 // Check for the special-case of initializing an array with a string.
568 if (startIndex < IList->getNumInits()) {
569 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
570 DeclType)) {
571 CheckStringLiteralInit(lit, DeclType);
572 ++startIndex;
573 if (topLevel && startIndex < IList->getNumInits()) {
574 // We have leftover initializers; warn
575 Diag(IList->getInit(startIndex)->getLocStart(),
576 diag::err_excess_initializers_in_char_array_initializer,
577 IList->getInit(startIndex)->getSourceRange());
578 }
579 return false;
580 }
581 }
582 int maxElements;
583 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
584 // FIXME: use a proper constant
585 maxElements = 0x7FFFFFFF;
586 // Check for VLAs; in standard C it would be possible to check this
587 // earlier, but I don't know where clang accepts VLAs (gcc accepts
588 // them in all sorts of strange places).
589 if (const Expr *expr = VAT->getSizeExpr()) {
590 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
591 expr->getSourceRange());
592 hadError = true;
593 }
594 } else {
595 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
596 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
597 }
598 QualType elementType = DeclType->getAsArrayType()->getElementType();
599 int numElements = 0;
600 for (int i = 0; i < maxElements; ++i, ++numElements) {
601 // Don't attempt to go past the end of the init list
602 if (startIndex >= IList->getNumInits())
603 break;
604 Expr* expr = IList->getInit(startIndex);
605 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
606 unsigned newIndex = 0;
607 hadError |= CheckInitializerListTypes(SubInitList, elementType,
608 true, newIndex);
609 ++startIndex;
610 } else {
611 hadError |= CheckInitializerListTypes(IList, elementType,
612 false, startIndex);
613 }
614 }
615 if (DeclType->getAsVariableArrayType()) {
616 // If this is an incomplete array type, the actual type needs to
617 // be calculated here
618 if (numElements == 0) {
619 // Sizing an array implicitly to zero is not allowed
620 // (It could in theory be allowed, but it doesn't really matter.)
621 Diag(IList->getLocStart(),
622 diag::err_at_least_one_initializer_needed_to_size_array);
623 hadError = true;
624 } else {
625 llvm::APSInt ConstVal(32);
626 ConstVal = numElements;
627 DeclType = Context.getConstantArrayType(elementType, ConstVal,
628 ArrayType::Normal, 0);
629 }
630 }
631 } else {
632 assert(0 && "Aggregate that isn't a function or array?!");
633 }
634 } else {
635 // In C, all types are either scalars or aggregates, but
636 // additional handling is needed here for C++ (and possibly others?).
637 assert(0 && "Unsupported initializer type");
638 }
639
640 // If this init list is a base list, we set the type; an initializer doesn't
641 // fundamentally have a type, but this makes the ASTs a bit easier to read
642 if (topLevel)
643 IList->setType(DeclType);
644
645 if (topLevel && startIndex < IList->getNumInits()) {
646 // We have leftover initializers; warn
647 Diag(IList->getInit(startIndex)->getLocStart(),
648 diag::warn_excess_initializers,
649 IList->getInit(startIndex)->getSourceRange());
650 }
651 return hadError;
652}
653
654bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000655 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
656 // of unknown size ("[]") or an object type that is not a variable array type.
657 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
658 return Diag(VAT->getSizeExpr()->getLocStart(),
659 diag::err_variable_object_no_init,
660 VAT->getSizeExpr()->getSourceRange());
661
Steve Naroffcb69fb72007-12-10 22:44:33 +0000662 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
663 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000664 // FIXME: Handle wide strings
665 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
666 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000667
668 if (DeclType->isArrayType())
669 return Diag(Init->getLocStart(),
670 diag::err_array_init_list_required,
671 Init->getSourceRange());
672
Steve Narofff0b23542008-01-10 22:15:12 +0000673 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000674 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000675 unsigned newIndex = 0;
676 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000677}
678
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000679Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000680Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000681 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000682 IdentifierInfo *II = D.getIdentifier();
683
684 // All of these full declarators require an identifier. If it doesn't have
685 // one, the ParsedFreeStandingDeclSpec action should be used.
686 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000687 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000688 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000689 D.getDeclSpec().getSourceRange(), D.getSourceRange());
690 return 0;
691 }
692
Chris Lattnera7549902007-08-26 06:24:45 +0000693 // The scope passed in may not be a decl scope. Zip up the scope tree until
694 // we find one that is.
695 while ((S->getFlags() & Scope::DeclScope) == 0)
696 S = S->getParent();
697
Chris Lattner4b009652007-07-25 00:24:17 +0000698 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000699 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
700 D.getIdentifierLoc(), S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000701 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000702 bool InvalidDecl = false;
703
Chris Lattner82bb4792007-11-14 06:34:38 +0000704 QualType R = GetTypeForDeclarator(D, S);
705 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
706
Chris Lattner4b009652007-07-25 00:24:17 +0000707 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000708 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000709 if (!NewTD) return 0;
710
711 // Handle attributes prior to checking for duplicates in MergeVarDecl
712 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
713 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000714 // Merge the decl with the existing one if appropriate. If the decl is
715 // in an outer scope, it isn't the same thing.
716 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000717 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
718 if (NewTD == 0) return 0;
719 }
720 New = NewTD;
721 if (S->getParent() == 0) {
722 // C99 6.7.7p2: If a typedef name specifies a variably modified type
723 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000724 if (const VariableArrayType *VAT =
725 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
726 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
727 VAT->getSizeExpr()->getSourceRange());
728 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000729 }
730 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000731 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000732 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000733 switch (D.getDeclSpec().getStorageClassSpec()) {
734 default: assert(0 && "Unknown storage class!");
735 case DeclSpec::SCS_auto:
736 case DeclSpec::SCS_register:
737 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
738 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000739 InvalidDecl = true;
740 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000741 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
742 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
743 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000744 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000745 }
746
747 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000748 D.getDeclSpec().isInlineSpecified(),
Nate Begeman84079d72007-11-13 22:14:47 +0000749 LastDeclarator,
750 D.getDeclSpec().getAttributes());
751
752 // Transfer ownership of DeclSpec attributes to FunctionDecl
753 D.getDeclSpec().clearAttributes();
Chris Lattner4b009652007-07-25 00:24:17 +0000754
Steve Narofff8a09432008-01-09 23:34:55 +0000755 // Merge the decl with the existing one if appropriate. Since C functions
756 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000757 if (PrevDecl) {
758 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
759 if (NewFD == 0) return 0;
760 }
761 New = NewFD;
762 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000763 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000764 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
765 D.getIdentifier()->getName());
766 InvalidDecl = true;
767 }
Chris Lattner4b009652007-07-25 00:24:17 +0000768
769 VarDecl *NewVD;
770 VarDecl::StorageClass SC;
771 switch (D.getDeclSpec().getStorageClassSpec()) {
772 default: assert(0 && "Unknown storage class!");
Steve Naroff1cbb2762008-01-25 22:14:40 +0000773 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
774 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
775 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
776 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
777 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
778 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000779 }
780 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000781 // C99 6.9p2: The storage-class specifiers auto and register shall not
782 // appear in the declaration specifiers in an external declaration.
783 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
784 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
785 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000786 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000787 }
Chris Lattner4b009652007-07-25 00:24:17 +0000788 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000789 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000790 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000791 }
Chris Lattner4b009652007-07-25 00:24:17 +0000792 // Handle attributes prior to checking for duplicates in MergeVarDecl
793 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
794 D.getAttributes());
795
Steve Narofff8a09432008-01-09 23:34:55 +0000796 // Merge the decl with the existing one if appropriate. If the decl is
797 // in an outer scope, it isn't the same thing.
798 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000799 NewVD = MergeVarDecl(NewVD, PrevDecl);
800 if (NewVD == 0) return 0;
801 }
Chris Lattner4b009652007-07-25 00:24:17 +0000802 New = NewVD;
803 }
804
805 // If this has an identifier, add it to the scope stack.
806 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000807 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000808 II->setFETokenInfo(New);
809 S->AddDecl(New);
810 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000811 // If any semantic error occurred, mark the decl as invalid.
812 if (D.getInvalidType() || InvalidDecl)
813 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000814
815 return New;
816}
817
Steve Narofff0b23542008-01-10 22:15:12 +0000818bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
819 SourceLocation loc;
820 // FIXME: Remove the isReference check and handle assignment to a reference.
821 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
822 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
823 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
824 return true;
825 }
826 return false;
827}
828
Steve Naroff6a0e2092007-09-12 14:07:44 +0000829void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000830 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000831 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000832 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000833
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000834 // If there is no declaration, there was an error parsing it. Just ignore
835 // the initializer.
836 if (RealDecl == 0) {
837 delete Init;
838 return;
839 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000840
Steve Naroff420d0f52007-09-12 20:13:48 +0000841 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
842 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000843 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
844 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000845 RealDecl->setInvalidDecl();
846 return;
847 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000848 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000849 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000850 QualType DclT = VDecl->getType(), SavT = DclT;
851 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000852 VarDecl::StorageClass SC = BVD->getStorageClass();
853 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000854 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000855 BVD->setInvalidDecl();
856 } else if (!BVD->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000857 if (CheckInitializerTypes(Init, DclT))
858 BVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000859 if (SC == VarDecl::Static) // C99 6.7.8p4.
860 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000861 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000862 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000863 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000864 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000865 if (!FVD->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000866 if (CheckInitializerTypes(Init, DclT))
867 FVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000868
869 // C99 6.7.8p4. All file scoped initializers need to be constant.
870 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000871 }
872 // If the type changed, it means we had an incomplete type that was
873 // completed by the initializer. For example:
874 // int ary[] = { 1, 3, 5 };
875 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000876 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000877 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000878 Init->setType(DclT);
879 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000880
881 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000882 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000883 return;
884}
885
Chris Lattner4b009652007-07-25 00:24:17 +0000886/// The declarators are chained together backwards, reverse the list.
887Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
888 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000889 Decl *GroupDecl = static_cast<Decl*>(group);
890 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000891 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000892
893 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
894 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000895 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000896 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000897 else { // reverse the list.
898 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000899 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000900 Group->setNextDeclarator(NewGroup);
901 NewGroup = Group;
902 Group = Next;
903 }
904 }
905 // Perform semantic analysis that depends on having fully processed both
906 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000907 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000908 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
909 if (!IDecl)
910 continue;
911 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
912 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
913 QualType T = IDecl->getType();
914
915 // C99 6.7.5.2p2: If an identifier is declared to be an object with
916 // static storage duration, it shall not have a variable length array.
917 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
918 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
919 if (VLA->getSizeExpr()) {
920 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
921 IDecl->setInvalidDecl();
922 }
923 }
924 }
925 // Block scope. C99 6.7p7: If an identifier for an object is declared with
926 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
927 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
928 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000929 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
930 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000931 IDecl->setInvalidDecl();
932 }
933 }
934 // File scope. C99 6.9.2p2: A declaration of an identifier for and
935 // object that has file scope without an initializer, and without a
936 // storage-class specifier or with the storage-class specifier "static",
937 // constitutes a tentative definition. Note: A tentative definition with
938 // external linkage is valid (C99 6.2.2p5).
Steve Narofffef2f052008-01-18 00:39:39 +0000939 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
940 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff60685462008-01-18 20:40:52 +0000941 const VariableArrayType *VAT = T->getAsVariableArrayType();
942
943 if (VAT && VAT->getSizeExpr() == 0) {
944 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
945 // array to be completed. Don't issue a diagnostic.
946 } else if (T->isIncompleteType()) {
947 // C99 6.9.2p3: If the declaration of an identifier for an object is
948 // a tentative definition and has internal linkage (C99 6.2.2p3), the
949 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +0000950 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
951 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000952 IDecl->setInvalidDecl();
953 }
954 }
Chris Lattner4b009652007-07-25 00:24:17 +0000955 }
956 return NewGroup;
957}
Steve Naroff91b03f72007-08-28 03:03:08 +0000958
959// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000960ParmVarDecl *
Nate Begeman2240f542007-11-13 21:49:48 +0000961Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff434fa8d2007-11-12 03:44:46 +0000962{
Chris Lattner4b009652007-07-25 00:24:17 +0000963 IdentifierInfo *II = PI.Ident;
964 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
965 // Can this happen for params? We already checked that they don't conflict
966 // among each other. Here they can only shadow globals, which is ok.
967 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
968 PI.IdentLoc, FnScope)) {
969
970 }
971
972 // FIXME: Handle storage class (auto, register). No declarator?
973 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000974
975 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
976 // Doing the promotion here has a win and a loss. The win is the type for
977 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
978 // code generator). The loss is the orginal type isn't preserved. For example:
979 //
980 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
981 // int blockvardecl[5];
982 // sizeof(parmvardecl); // size == 4
983 // sizeof(blockvardecl); // size == 20
984 // }
985 //
986 // For expressions, all implicit conversions are captured using the
987 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
988 //
989 // FIXME: If a source translation tool needs to see the original type, then
990 // we need to consider storing both types (in ParmVarDecl)...
991 //
992 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000993 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
994 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000995 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +0000996 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
997 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +0000998 parmDeclType = Context.getPointerType(parmDeclType);
999
1000 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman84079d72007-11-13 22:14:47 +00001001 VarDecl::None, 0, PI.AttrList);
Steve Naroffcae537d2007-08-28 18:45:29 +00001002 if (PI.InvalidType)
1003 New->setInvalidDecl();
1004
Chris Lattner4b009652007-07-25 00:24:17 +00001005 // If this has an identifier, add it to the scope stack.
1006 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001007 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001008 II->setFETokenInfo(New);
1009 FnScope->AddDecl(New);
1010 }
1011
1012 return New;
1013}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001014
Chris Lattnerea148702007-10-09 17:14:05 +00001015Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001016 assert(CurFunctionDecl == 0 && "Function parsing confused");
1017 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1018 "Not a function declarator!");
1019 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1020
1021 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1022 // for a K&R function.
1023 if (!FTI.hasPrototype) {
1024 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1025 if (FTI.ArgInfo[i].TypeInfo == 0) {
1026 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1027 FTI.ArgInfo[i].Ident->getName());
1028 // Implicitly declare the argument as type 'int' for lack of a better
1029 // type.
1030 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1031 }
1032 }
1033
1034 // Since this is a function definition, act as though we have information
1035 // about the arguments.
1036 FTI.hasPrototype = true;
1037 } else {
1038 // FIXME: Diagnose arguments without names in C.
1039
1040 }
1041
1042 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001043
1044 // See if this is a redefinition.
1045 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1046 D.getIdentifierLoc(), GlobalScope);
1047 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1048 if (FD->getBody()) {
1049 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1050 D.getIdentifier()->getName());
1051 Diag(FD->getLocation(), diag::err_previous_definition);
1052 }
1053 }
Chris Lattner4b009652007-07-25 00:24:17 +00001054 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +00001055 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroff1d5bd642008-01-14 20:51:29 +00001056 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner4b009652007-07-25 00:24:17 +00001057 CurFunctionDecl = FD;
1058
1059 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1060 llvm::SmallVector<ParmVarDecl*, 16> Params;
1061
1062 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1063 // no arguments, not a function that takes a single void argument.
1064 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +00001065 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1066 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001067 // empty arg list, don't push any params.
1068 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +00001069 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +00001070 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +00001071 FnBodyScope));
1072 }
Chris Lattner4b009652007-07-25 00:24:17 +00001073 }
1074
1075 FD->setParams(&Params[0], Params.size());
1076
1077 return FD;
1078}
1079
Steve Naroff99ee4302007-11-11 23:20:51 +00001080Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1081 Decl *dcl = static_cast<Decl *>(D);
1082 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1083 FD->setBody((Stmt*)Body);
1084 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001085 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001086 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001087 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001088 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001089 }
Chris Lattner4b009652007-07-25 00:24:17 +00001090 // Verify and clean out per-function state.
1091
1092 // Check goto/label use.
1093 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1094 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1095 // Verify that we have no forward references left. If so, there was a goto
1096 // or address of a label taken, but no definition of it. Label fwd
1097 // definitions are indicated with a null substmt.
1098 if (I->second->getSubStmt() == 0) {
1099 LabelStmt *L = I->second;
1100 // Emit error.
1101 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1102
1103 // At this point, we have gotos that use the bogus label. Stitch it into
1104 // the function body so that they aren't leaked and that the AST is well
1105 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001106 if (Body) {
1107 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1108 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1109 } else {
1110 // The whole function wasn't parsed correctly, just delete this.
1111 delete L;
1112 }
Chris Lattner4b009652007-07-25 00:24:17 +00001113 }
1114 }
1115 LabelMap.clear();
1116
Steve Naroff99ee4302007-11-11 23:20:51 +00001117 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001118}
1119
Chris Lattner4b009652007-07-25 00:24:17 +00001120/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1121/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001122ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1123 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001124 if (getLangOptions().C99) // Extension in C99.
1125 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1126 else // Legal in C90, but warn about it.
1127 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1128
1129 // FIXME: handle stuff like:
1130 // void foo() { extern float X(); }
1131 // void bar() { X(); } <-- implicit decl for X in another scope.
1132
1133 // Set a Declarator for the implicit definition: int foo();
1134 const char *Dummy;
1135 DeclSpec DS;
1136 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1137 Error = Error; // Silence warning.
1138 assert(!Error && "Error setting up implicit decl!");
1139 Declarator D(DS, Declarator::BlockContext);
1140 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1141 D.SetIdentifier(&II, Loc);
1142
1143 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001144 if (Scope *FnS = S->getFnParent())
1145 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001146 while (S->getParent())
1147 S = S->getParent();
1148
Steve Narofff0c31dd2007-09-16 16:16:00 +00001149 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001150}
1151
1152
Chris Lattner82bb4792007-11-14 06:34:38 +00001153TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001154 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001155 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001156 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001157
1158 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001159 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1160 T, LastDeclarator);
1161 if (D.getInvalidType())
1162 NewTD->setInvalidDecl();
1163 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001164}
1165
Steve Naroff0acc9c92007-09-15 18:49:24 +00001166/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001167/// former case, Name will be non-null. In the later case, Name will be null.
1168/// TagType indicates what kind of tag this is. TK indicates whether this is a
1169/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001170Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001171 SourceLocation KWLoc, IdentifierInfo *Name,
1172 SourceLocation NameLoc, AttributeList *Attr) {
1173 // If this is a use of an existing tag, it must have a name.
1174 assert((Name != 0 || TK == TK_Definition) &&
1175 "Nameless record must be a definition!");
1176
1177 Decl::Kind Kind;
1178 switch (TagType) {
1179 default: assert(0 && "Unknown tag type!");
1180 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1181 case DeclSpec::TST_union: Kind = Decl::Union; break;
1182//case DeclSpec::TST_class: Kind = Decl::Class; break;
1183 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1184 }
1185
1186 // If this is a named struct, check to see if there was a previous forward
1187 // declaration or definition.
1188 if (TagDecl *PrevDecl =
1189 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1190 NameLoc, S))) {
1191
1192 // If this is a use of a previous tag, or if the tag is already declared in
1193 // the same scope (so that the definition/declaration completes or
1194 // rementions the tag), reuse the decl.
1195 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1196 // Make sure that this wasn't declared as an enum and now used as a struct
1197 // or something similar.
1198 if (PrevDecl->getKind() != Kind) {
1199 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1200 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1201 }
1202
1203 // If this is a use or a forward declaration, we're good.
1204 if (TK != TK_Definition)
1205 return PrevDecl;
1206
1207 // Diagnose attempts to redefine a tag.
1208 if (PrevDecl->isDefinition()) {
1209 Diag(NameLoc, diag::err_redefinition, Name->getName());
1210 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1211 // If this is a redefinition, recover by making this struct be
1212 // anonymous, which will make any later references get the previous
1213 // definition.
1214 Name = 0;
1215 } else {
1216 // Okay, this is definition of a previously declared or referenced tag.
1217 // Move the location of the decl to be the definition site.
1218 PrevDecl->setLocation(NameLoc);
1219 return PrevDecl;
1220 }
1221 }
1222 // If we get here, this is a definition of a new struct type in a nested
1223 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1224 // type.
1225 }
1226
1227 // If there is an identifier, use the location of the identifier as the
1228 // location of the decl, otherwise use the location of the struct/union
1229 // keyword.
1230 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1231
1232 // Otherwise, if this is the first time we've seen this tag, create the decl.
1233 TagDecl *New;
1234 switch (Kind) {
1235 default: assert(0 && "Unknown tag kind!");
1236 case Decl::Enum:
1237 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1238 // enum X { A, B, C } D; D should chain to X.
1239 New = new EnumDecl(Loc, Name, 0);
1240 // If this is an undefined enum, warn.
1241 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1242 break;
1243 case Decl::Union:
1244 case Decl::Struct:
1245 case Decl::Class:
1246 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1247 // struct X { int A; } D; D should chain to X.
1248 New = new RecordDecl(Kind, Loc, Name, 0);
1249 break;
1250 }
1251
1252 // If this has an identifier, add it to the scope stack.
1253 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001254 // The scope passed in may not be a decl scope. Zip up the scope tree until
1255 // we find one that is.
1256 while ((S->getFlags() & Scope::DeclScope) == 0)
1257 S = S->getParent();
1258
1259 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001260 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001261 Name->setFETokenInfo(New);
1262 S->AddDecl(New);
1263 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001264
Chris Lattner4b009652007-07-25 00:24:17 +00001265 return New;
1266}
1267
Steve Naroff0acc9c92007-09-15 18:49:24 +00001268/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001269/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001270Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001271 SourceLocation DeclStart,
1272 Declarator &D, ExprTy *BitfieldWidth) {
1273 IdentifierInfo *II = D.getIdentifier();
1274 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001275 SourceLocation Loc = DeclStart;
1276 if (II) Loc = D.getIdentifierLoc();
1277
1278 // FIXME: Unnamed fields can be handled in various different ways, for
1279 // example, unnamed unions inject all members into the struct namespace!
1280
1281
1282 if (BitWidth) {
1283 // TODO: Validate.
1284 //printf("WARNING: BITFIELDS IGNORED!\n");
1285
1286 // 6.7.2.1p3
1287 // 6.7.2.1p4
1288
1289 } else {
1290 // Not a bitfield.
1291
1292 // validate II.
1293
1294 }
1295
1296 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001297 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1298 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001299
Chris Lattner4b009652007-07-25 00:24:17 +00001300 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1301 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001302 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1303 Diag(Loc, diag::err_typecheck_illegal_vla,
1304 VAT->getSizeExpr()->getSourceRange());
1305 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001306 }
Chris Lattner4b009652007-07-25 00:24:17 +00001307 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001308 FieldDecl *NewFD;
1309
1310 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001311 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek42730c52008-01-07 19:49:32 +00001312 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1313 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1314 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001315 // FIXME: ivars are currently used to model properties, and
1316 // properties can appear within a protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001317 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1318 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1319 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001320 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001321 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001322
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001323 if (D.getInvalidType() || InvalidDecl)
1324 NewFD->setInvalidDecl();
1325 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001326}
1327
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001328/// TranslateIvarVisibility - Translate visibility from a token ID to an
1329/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001330static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001331TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001332 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001333 case tok::objc_private: return ObjCIvarDecl::Private;
1334 case tok::objc_public: return ObjCIvarDecl::Public;
1335 case tok::objc_protected: return ObjCIvarDecl::Protected;
1336 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001337 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001338 }
1339}
1340
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001341void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001342 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001343 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001344 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001345 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001346 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1347 assert(EnclosingDecl && "missing record or interface decl");
1348 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1349
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001350 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001351 // Diagnose code like:
1352 // struct S { struct S {} X; };
1353 // We discover this when we complete the outer S. Reject and ignore the
1354 // outer S.
1355 Diag(Record->getLocation(), diag::err_nested_redefinition,
1356 Record->getKindName());
1357 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001358 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001359 return;
1360 }
Chris Lattner4b009652007-07-25 00:24:17 +00001361 // Verify that all the fields are okay.
1362 unsigned NumNamedMembers = 0;
1363 llvm::SmallVector<FieldDecl*, 32> RecFields;
1364 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001365
Chris Lattner4b009652007-07-25 00:24:17 +00001366 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001367
Steve Naroff9bb759f2007-09-14 22:20:54 +00001368 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1369 assert(FD && "missing field decl");
1370
1371 // Remember all fields.
1372 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001373
1374 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001375 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001376
Steve Naroffffeaa552007-09-14 23:09:53 +00001377 // If we have visibility info, make sure the AST is set accordingly.
1378 if (visibility)
Ted Kremenek42730c52008-01-07 19:49:32 +00001379 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001380 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001381
Chris Lattner4b009652007-07-25 00:24:17 +00001382 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001383 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001384 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001385 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001386 FD->setInvalidDecl();
1387 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001388 continue;
1389 }
Chris Lattner4b009652007-07-25 00:24:17 +00001390 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1391 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001392 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001393 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001394 FD->setInvalidDecl();
1395 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001396 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001397 }
Chris Lattner4b009652007-07-25 00:24:17 +00001398 if (i != NumFields-1 || // ... that the last member ...
1399 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001400 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001401 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001402 FD->setInvalidDecl();
1403 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001404 continue;
1405 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001406 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001407 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1408 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001409 FD->setInvalidDecl();
1410 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001411 continue;
1412 }
Chris Lattner4b009652007-07-25 00:24:17 +00001413 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001414 if (Record)
1415 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001416 }
Chris Lattner4b009652007-07-25 00:24:17 +00001417 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1418 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001419 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001420 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1421 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001422 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001423 Record->setHasFlexibleArrayMember(true);
1424 } else {
1425 // If this is a struct/class and this is not the last element, reject
1426 // it. Note that GCC supports variable sized arrays in the middle of
1427 // structures.
1428 if (i != NumFields-1) {
1429 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1430 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001431 FD->setInvalidDecl();
1432 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001433 continue;
1434 }
Chris Lattner4b009652007-07-25 00:24:17 +00001435 // We support flexible arrays at the end of structs in other structs
1436 // as an extension.
1437 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1438 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001439 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001440 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001441 }
1442 }
1443 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001444 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001445 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001446 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1447 FD->getName());
1448 FD->setInvalidDecl();
1449 EnclosingDecl->setInvalidDecl();
1450 continue;
1451 }
Chris Lattner4b009652007-07-25 00:24:17 +00001452 // Keep track of the number of named members.
1453 if (IdentifierInfo *II = FD->getIdentifier()) {
1454 // Detect duplicate member names.
1455 if (!FieldIDs.insert(II)) {
1456 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1457 // Find the previous decl.
1458 SourceLocation PrevLoc;
1459 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1460 assert(i != e && "Didn't find previous def!");
1461 if (RecFields[i]->getIdentifier() == II) {
1462 PrevLoc = RecFields[i]->getLocation();
1463 break;
1464 }
1465 }
1466 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001467 FD->setInvalidDecl();
1468 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001469 continue;
1470 }
1471 ++NumNamedMembers;
1472 }
Chris Lattner4b009652007-07-25 00:24:17 +00001473 }
1474
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001476 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001477 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001478 Consumer.HandleTagDeclDefinition(Record);
1479 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001480 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1481 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1482 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1483 else if (ObjCImplementationDecl *IMPDecl =
1484 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001485 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1486 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001487 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001488 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001489 }
Chris Lattner4b009652007-07-25 00:24:17 +00001490}
1491
Steve Naroff0acc9c92007-09-15 18:49:24 +00001492Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001493 DeclTy *lastEnumConst,
1494 SourceLocation IdLoc, IdentifierInfo *Id,
1495 SourceLocation EqualLoc, ExprTy *val) {
1496 theEnumDecl = theEnumDecl; // silence unused warning.
1497 EnumConstantDecl *LastEnumConst =
1498 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1499 Expr *Val = static_cast<Expr*>(val);
1500
Chris Lattnera7549902007-08-26 06:24:45 +00001501 // The scope passed in may not be a decl scope. Zip up the scope tree until
1502 // we find one that is.
1503 while ((S->getFlags() & Scope::DeclScope) == 0)
1504 S = S->getParent();
1505
Chris Lattner4b009652007-07-25 00:24:17 +00001506 // Verify that there isn't already something declared with this name in this
1507 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001508 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1509 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001510 if (S->isDeclScope(PrevDecl)) {
1511 if (isa<EnumConstantDecl>(PrevDecl))
1512 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1513 else
1514 Diag(IdLoc, diag::err_redefinition, Id->getName());
1515 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1516 // FIXME: Don't leak memory: delete Val;
1517 return 0;
1518 }
1519 }
1520
1521 llvm::APSInt EnumVal(32);
1522 QualType EltTy;
1523 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001524 // Make sure to promote the operand type to int.
1525 UsualUnaryConversions(Val);
1526
Chris Lattner4b009652007-07-25 00:24:17 +00001527 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1528 SourceLocation ExpLoc;
1529 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1530 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1531 Id->getName());
1532 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001533 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001534 } else {
1535 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001536 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001537 }
1538
1539 if (!Val) {
1540 if (LastEnumConst) {
1541 // Assign the last value + 1.
1542 EnumVal = LastEnumConst->getInitVal();
1543 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001544
1545 // Check for overflow on increment.
1546 if (EnumVal < LastEnumConst->getInitVal())
1547 Diag(IdLoc, diag::warn_enum_value_overflow);
1548
Chris Lattnere7f53a42007-08-27 17:37:24 +00001549 EltTy = LastEnumConst->getType();
1550 } else {
1551 // First value, set to zero.
1552 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001553 EnumVal.zextOrTrunc(
1554 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001555 }
Chris Lattner4b009652007-07-25 00:24:17 +00001556 }
1557
Chris Lattner4b009652007-07-25 00:24:17 +00001558 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1559 LastEnumConst);
1560
1561 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001562 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001563 Id->setFETokenInfo(New);
1564 S->AddDecl(New);
1565 return New;
1566}
1567
Steve Naroff0acc9c92007-09-15 18:49:24 +00001568void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001569 DeclTy **Elements, unsigned NumElements) {
1570 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1571 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1572
Chris Lattner435c3fd2007-08-28 05:10:31 +00001573 // TODO: If the result value doesn't fit in an int, it must be a long or long
1574 // long value. ISO C does not support this, but GCC does as an extension,
1575 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001576 unsigned IntWidth =
1577 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001578
1579
Chris Lattner206754a2007-08-28 06:15:15 +00001580 // Verify that all the values are okay, compute the size of the values, and
1581 // reverse the list.
1582 unsigned NumNegativeBits = 0;
1583 unsigned NumPositiveBits = 0;
1584
1585 // Keep track of whether all elements have type int.
1586 bool AllElementsInt = true;
1587
Chris Lattner4b009652007-07-25 00:24:17 +00001588 EnumConstantDecl *EltList = 0;
1589 for (unsigned i = 0; i != NumElements; ++i) {
1590 EnumConstantDecl *ECD =
1591 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1592 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001593
1594 // If the enum value doesn't fit in an int, emit an extension warning.
1595 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1596 "Should have promoted value to int");
1597 const llvm::APSInt &InitVal = ECD->getInitVal();
1598 if (InitVal.getBitWidth() > IntWidth) {
1599 llvm::APSInt V(InitVal);
1600 V.trunc(IntWidth);
1601 V.extend(InitVal.getBitWidth());
1602 if (V != InitVal)
1603 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1604 InitVal.toString());
1605 }
Chris Lattner206754a2007-08-28 06:15:15 +00001606
1607 // Keep track of the size of positive and negative values.
1608 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001609 NumPositiveBits = std::max(NumPositiveBits,
1610 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001611 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001612 NumNegativeBits = std::max(NumNegativeBits,
1613 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001614
Chris Lattner206754a2007-08-28 06:15:15 +00001615 // Keep track of whether every enum element has type int (very commmon).
1616 if (AllElementsInt)
1617 AllElementsInt = ECD->getType() == Context.IntTy;
1618
Chris Lattner4b009652007-07-25 00:24:17 +00001619 ECD->setNextDeclarator(EltList);
1620 EltList = ECD;
1621 }
1622
Chris Lattner206754a2007-08-28 06:15:15 +00001623 // Figure out the type that should be used for this enum.
1624 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1625 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001626 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001627
1628 if (NumNegativeBits) {
1629 // If there is a negative value, figure out the smallest integer type (of
1630 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001631 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001632 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001633 BestWidth = IntWidth;
1634 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001635 BestWidth =
1636 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1637
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001638 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001639 BestType = Context.LongTy;
1640 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001641 BestWidth = Context.Target.getLongLongWidth(
1642 Context.getFullLoc(Enum->getLocation()));
1643
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001644 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001645 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1646 BestType = Context.LongLongTy;
1647 }
1648 }
1649 } else {
1650 // If there is no negative value, figure out which of uint, ulong, ulonglong
1651 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001652 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001653 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001654 BestWidth = IntWidth;
1655 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001656 (BestWidth = Context.Target.getLongWidth(
1657 Context.getFullLoc(Enum->getLocation()))))
1658
Chris Lattner206754a2007-08-28 06:15:15 +00001659 BestType = Context.UnsignedLongTy;
1660 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001661 BestWidth =
1662 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1663
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001664 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001665 "How could an initializer get larger than ULL?");
1666 BestType = Context.UnsignedLongLongTy;
1667 }
1668 }
1669
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001670 // Loop over all of the enumerator constants, changing their types to match
1671 // the type of the enum if needed.
1672 for (unsigned i = 0; i != NumElements; ++i) {
1673 EnumConstantDecl *ECD =
1674 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1675 if (!ECD) continue; // Already issued a diagnostic.
1676
1677 // Standard C says the enumerators have int type, but we allow, as an
1678 // extension, the enumerators to be larger than int size. If each
1679 // enumerator value fits in an int, type it as an int, otherwise type it the
1680 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1681 // that X has type 'int', not 'unsigned'.
1682 if (ECD->getType() == Context.IntTy)
1683 continue; // Already int type.
1684
1685 // Determine whether the value fits into an int.
1686 llvm::APSInt InitVal = ECD->getInitVal();
1687 bool FitsInInt;
1688 if (InitVal.isUnsigned() || !InitVal.isNegative())
1689 FitsInInt = InitVal.getActiveBits() < IntWidth;
1690 else
1691 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1692
1693 // If it fits into an integer type, force it. Otherwise force it to match
1694 // the enum decl type.
1695 QualType NewTy;
1696 unsigned NewWidth;
1697 bool NewSign;
1698 if (FitsInInt) {
1699 NewTy = Context.IntTy;
1700 NewWidth = IntWidth;
1701 NewSign = true;
1702 } else if (ECD->getType() == BestType) {
1703 // Already the right type!
1704 continue;
1705 } else {
1706 NewTy = BestType;
1707 NewWidth = BestWidth;
1708 NewSign = BestType->isSignedIntegerType();
1709 }
1710
1711 // Adjust the APSInt value.
1712 InitVal.extOrTrunc(NewWidth);
1713 InitVal.setIsSigned(NewSign);
1714 ECD->setInitVal(InitVal);
1715
1716 // Adjust the Expr initializer and type.
1717 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1718 ECD->setType(NewTy);
1719 }
Chris Lattner206754a2007-08-28 06:15:15 +00001720
Chris Lattner90a018d2007-08-28 18:24:31 +00001721 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001722 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001723}
1724
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001725Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1726 ExprTy *expr) {
1727 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1728
1729 return new FileScopeAsmDecl(Loc, AsmString);
1730}
1731
Chris Lattner806a5f52008-01-12 07:05:38 +00001732Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1733 SourceLocation LBrace,
1734 SourceLocation RBrace,
1735 const char *Lang,
1736 unsigned StrSize,
1737 DeclTy *D) {
1738 LinkageSpecDecl::LanguageIDs Language;
1739 Decl *dcl = static_cast<Decl *>(D);
1740 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1741 Language = LinkageSpecDecl::lang_c;
1742 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1743 Language = LinkageSpecDecl::lang_cxx;
1744 else {
1745 Diag(Loc, diag::err_bad_language);
1746 return 0;
1747 }
1748
1749 // FIXME: Add all the various semantics of linkage specifications
1750 return new LinkageSpecDecl(Loc, Language, dcl);
1751}
1752
Chris Lattner4b009652007-07-25 00:24:17 +00001753void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001754 const char *attrName = rawAttr->getAttributeName()->getName();
1755 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1756
Anders Carlsson5f558b52007-12-19 17:43:24 +00001757 // Normalize the attribute name, __foo__ becomes foo.
1758 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1759 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1760 attrName += 2;
1761 attrLen -= 4;
1762 }
1763
1764 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001765 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1766 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1767 if (!newType.isNull()) // install the new vector type into the decl
1768 vDecl->setType(newType);
1769 }
1770 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1771 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1772 rawAttr);
1773 if (!newType.isNull()) // install the new vector type into the decl
1774 tDecl->setUnderlyingType(newType);
1775 }
Anders Carlsson5f558b52007-12-19 17:43:24 +00001776 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroff82113e32007-07-29 16:33:31 +00001777 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1778 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1779 else
Chris Lattner4b009652007-07-25 00:24:17 +00001780 Diag(rawAttr->getAttributeLoc(),
1781 diag::err_typecheck_ocu_vector_not_typedef);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001782 } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1783 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1784 QualType newType = HandleAddressSpaceTypeAttribute(
1785 tDecl->getUnderlyingType(),
1786 rawAttr);
1787 if (!newType.isNull()) // install the new addr spaced type into the decl
1788 tDecl->setUnderlyingType(newType);
1789 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1790 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1791 rawAttr);
1792 if (!newType.isNull()) // install the new addr spaced type into the decl
1793 vDecl->setType(newType);
1794 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001795 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1796 HandleAlignedAttribute(New, rawAttr);
Chris Lattner4b009652007-07-25 00:24:17 +00001797 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001798
Chris Lattner4b009652007-07-25 00:24:17 +00001799 // FIXME: add other attributes...
1800}
1801
1802void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1803 AttributeList *declarator_postfix) {
1804 while (declspec_prefix) {
1805 HandleDeclAttribute(New, declspec_prefix);
1806 declspec_prefix = declspec_prefix->getNext();
1807 }
1808 while (declarator_postfix) {
1809 HandleDeclAttribute(New, declarator_postfix);
1810 declarator_postfix = declarator_postfix->getNext();
1811 }
1812}
1813
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001814QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType,
1815 AttributeList *rawAttr) {
1816 // check the attribute arugments.
1817 if (rawAttr->getNumArgs() != 1) {
1818 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1819 std::string("1"));
1820 return QualType();
1821 }
1822 Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1823 llvm::APSInt addrSpace(32);
1824 if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1825 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1826 addrSpaceExpr->getSourceRange());
1827 return QualType();
1828 }
1829 unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue());
1830
1831 // Zero is the default memory space, so no qualification is needed
1832 if (addressSpace == 0)
1833 return curType;
1834
1835 // TODO: Should we convert contained types of address space
1836 // qualified types here or or where they directly participate in conversions
1837 // (i.e. elsewhere)
1838
1839 return Context.getASQualType(curType, addressSpace);
1840}
1841
Steve Naroff82113e32007-07-29 16:33:31 +00001842void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1843 AttributeList *rawAttr) {
1844 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001845 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001846 if (rawAttr->getNumArgs() != 1) {
1847 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1848 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001849 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001850 }
1851 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1852 llvm::APSInt vecSize(32);
1853 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1854 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1855 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001856 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001857 }
1858 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1859 // in conjunction with complex types (pointers, arrays, functions, etc.).
1860 Type *canonType = curType.getCanonicalType().getTypePtr();
1861 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1862 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1863 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001864 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001865 }
1866 // unlike gcc's vector_size attribute, the size is specified as the
1867 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001868 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001869
1870 if (vectorSize == 0) {
1871 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1872 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001873 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001874 }
Steve Naroff82113e32007-07-29 16:33:31 +00001875 // Instantiate/Install the vector type, the number of elements is > 0.
1876 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1877 // Remember this typedef decl, we will need it later for diagnostics.
1878 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001879}
1880
1881QualType Sema::HandleVectorTypeAttribute(QualType curType,
1882 AttributeList *rawAttr) {
1883 // check the attribute arugments.
1884 if (rawAttr->getNumArgs() != 1) {
1885 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1886 std::string("1"));
1887 return QualType();
1888 }
1889 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1890 llvm::APSInt vecSize(32);
1891 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1892 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1893 sizeExpr->getSourceRange());
1894 return QualType();
1895 }
1896 // navigate to the base type - we need to provide for vector pointers,
1897 // vector arrays, and functions returning vectors.
1898 Type *canonType = curType.getCanonicalType().getTypePtr();
1899
1900 if (canonType->isPointerType() || canonType->isArrayType() ||
1901 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001902 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001903 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1904 do {
1905 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1906 canonType = PT->getPointeeType().getTypePtr();
1907 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1908 canonType = AT->getElementType().getTypePtr();
1909 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1910 canonType = FT->getResultType().getTypePtr();
1911 } while (canonType->isPointerType() || canonType->isArrayType() ||
1912 canonType->isFunctionType());
1913 */
1914 }
1915 // the base type must be integer or float.
1916 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1917 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1918 curType.getCanonicalType().getAsString());
1919 return QualType();
1920 }
Chris Lattner3496d522007-09-04 02:45:27 +00001921 unsigned typeSize = static_cast<unsigned>(
1922 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001923 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001924 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001925
1926 // the vector size needs to be an integral multiple of the type size.
1927 if (vectorSize % typeSize) {
1928 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1929 sizeExpr->getSourceRange());
1930 return QualType();
1931 }
1932 if (vectorSize == 0) {
1933 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1934 sizeExpr->getSourceRange());
1935 return QualType();
1936 }
1937 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1938 // the number of elements to be a power of two (unlike GCC).
1939 // Instantiate the vector type, the number of elements is > 0.
1940 return Context.getVectorType(curType, vectorSize/typeSize);
1941}
1942
Anders Carlssonc8b44122007-12-19 07:19:40 +00001943void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1944{
1945 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00001946 if (rawAttr->getNumArgs() > 1) {
Anders Carlssonc8b44122007-12-19 07:19:40 +00001947 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1948 std::string("1"));
1949 return;
1950 }
Eli Friedman74820702008-01-30 17:38:42 +00001951
Devang Patela31965b2008-01-30 18:00:07 +00001952 // TODO: We probably need to actually do something with aligned attribute.
Eli Friedman74820702008-01-30 17:38:42 +00001953 if (rawAttr->getNumArgs() == 0)
1954 return;
1955
Anders Carlssonc8b44122007-12-19 07:19:40 +00001956 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1957 llvm::APSInt alignment(32);
1958 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1959 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1960 alignmentExpr->getSourceRange());
1961 return;
1962 }
1963}