blob: c427a81306733366d99d2f49b9cbe5850e1be3fd [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
Steve Naroff63c9c432008-02-11 02:42:07 +0000530 // If the record is invalid, it's members can't be trusted.
531 // FIXME: I'd like to "fix" this at a higher level. That is, we should
532 // never get here if the struct decl is invalid. Considering a
533 // change to Type::isIncompleteType(). Until this happens, the
534 // following check is certainly better than crashing.
Steve Naroffee467032008-02-11 00:06:17 +0000535 if (structDecl->isInvalidDecl())
536 return true;
537
Steve Narofff3cb5142008-01-25 00:51:06 +0000538 // If structDecl is a forward declaration, this loop won't do anything;
539 // That's okay, because an error should get printed out elsewhere. It
540 // might be worthwhile to skip over the rest of the initializer, though.
541 int numMembers = structDecl->getNumMembers() -
542 structDecl->hasFlexibleArrayMember();
543 for (int i = 0; i < numMembers; i++) {
544 // Don't attempt to go past the end of the init list
545 if (startIndex >= IList->getNumInits())
546 break;
547 FieldDecl * curField = structDecl->getMember(i);
548 if (!curField->getIdentifier()) {
549 // Don't initialize unnamed fields, e.g. "int : 20;"
550 continue;
551 }
552 QualType fieldType = curField->getType();
553 Expr* expr = IList->getInit(startIndex);
554 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
555 unsigned newStart = 0;
556 hadError |= CheckInitializerListTypes(SubInitList, fieldType,
557 true, newStart);
558 ++startIndex;
559 } else {
560 hadError |= CheckInitializerListTypes(IList, fieldType,
561 false, startIndex);
562 }
563 if (DeclType->isUnionType())
564 break;
565 }
566 // FIXME: Implement flexible array initialization GCC extension (it's a
567 // really messy extension to implement, unfortunately...the necessary
568 // information isn't actually even here!)
569 }
570 } else if (DeclType->isArrayType()) {
571 // Check for the special-case of initializing an array with a string.
572 if (startIndex < IList->getNumInits()) {
573 if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
574 DeclType)) {
575 CheckStringLiteralInit(lit, DeclType);
576 ++startIndex;
577 if (topLevel && startIndex < IList->getNumInits()) {
578 // We have leftover initializers; warn
579 Diag(IList->getInit(startIndex)->getLocStart(),
580 diag::err_excess_initializers_in_char_array_initializer,
581 IList->getInit(startIndex)->getSourceRange());
582 }
583 return false;
584 }
585 }
586 int maxElements;
587 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
588 // FIXME: use a proper constant
589 maxElements = 0x7FFFFFFF;
590 // Check for VLAs; in standard C it would be possible to check this
591 // earlier, but I don't know where clang accepts VLAs (gcc accepts
592 // them in all sorts of strange places).
593 if (const Expr *expr = VAT->getSizeExpr()) {
594 Diag(expr->getLocStart(), diag::err_variable_object_no_init,
595 expr->getSourceRange());
596 hadError = true;
597 }
598 } else {
599 const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
600 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
601 }
602 QualType elementType = DeclType->getAsArrayType()->getElementType();
603 int numElements = 0;
604 for (int i = 0; i < maxElements; ++i, ++numElements) {
605 // Don't attempt to go past the end of the init list
606 if (startIndex >= IList->getNumInits())
607 break;
608 Expr* expr = IList->getInit(startIndex);
609 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
610 unsigned newIndex = 0;
611 hadError |= CheckInitializerListTypes(SubInitList, elementType,
612 true, newIndex);
613 ++startIndex;
614 } else {
615 hadError |= CheckInitializerListTypes(IList, elementType,
616 false, startIndex);
617 }
618 }
619 if (DeclType->getAsVariableArrayType()) {
620 // If this is an incomplete array type, the actual type needs to
621 // be calculated here
622 if (numElements == 0) {
623 // Sizing an array implicitly to zero is not allowed
624 // (It could in theory be allowed, but it doesn't really matter.)
625 Diag(IList->getLocStart(),
626 diag::err_at_least_one_initializer_needed_to_size_array);
627 hadError = true;
628 } else {
629 llvm::APSInt ConstVal(32);
630 ConstVal = numElements;
631 DeclType = Context.getConstantArrayType(elementType, ConstVal,
632 ArrayType::Normal, 0);
633 }
634 }
635 } else {
636 assert(0 && "Aggregate that isn't a function or array?!");
637 }
638 } else {
639 // In C, all types are either scalars or aggregates, but
640 // additional handling is needed here for C++ (and possibly others?).
641 assert(0 && "Unsupported initializer type");
642 }
643
644 // If this init list is a base list, we set the type; an initializer doesn't
645 // fundamentally have a type, but this makes the ASTs a bit easier to read
646 if (topLevel)
647 IList->setType(DeclType);
648
649 if (topLevel && startIndex < IList->getNumInits()) {
650 // We have leftover initializers; warn
651 Diag(IList->getInit(startIndex)->getLocStart(),
652 diag::warn_excess_initializers,
653 IList->getInit(startIndex)->getSourceRange());
654 }
655 return hadError;
656}
657
658bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroff8e9337f2008-01-21 23:53:58 +0000659 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
660 // of unknown size ("[]") or an object type that is not a variable array type.
661 if (const VariableArrayType *VAT = DeclType->getAsVariablyModifiedType())
662 return Diag(VAT->getSizeExpr()->getLocStart(),
663 diag::err_variable_object_no_init,
664 VAT->getSizeExpr()->getSourceRange());
665
Steve Naroffcb69fb72007-12-10 22:44:33 +0000666 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
667 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000668 // FIXME: Handle wide strings
669 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
670 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000671
672 if (DeclType->isArrayType())
673 return Diag(Init->getLocStart(),
674 diag::err_array_init_list_required,
675 Init->getSourceRange());
676
Steve Narofff0b23542008-01-10 22:15:12 +0000677 return CheckSingleInitializer(Init, DeclType);
Steve Naroffcb69fb72007-12-10 22:44:33 +0000678 }
Steve Narofff3cb5142008-01-25 00:51:06 +0000679 unsigned newIndex = 0;
680 return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
Steve Naroffe14e5542007-09-02 02:04:30 +0000681}
682
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000683Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000684Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000685 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000686 IdentifierInfo *II = D.getIdentifier();
687
688 // All of these full declarators require an identifier. If it doesn't have
689 // one, the ParsedFreeStandingDeclSpec action should be used.
690 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000691 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000692 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000693 D.getDeclSpec().getSourceRange(), D.getSourceRange());
694 return 0;
695 }
696
Chris Lattnera7549902007-08-26 06:24:45 +0000697 // The scope passed in may not be a decl scope. Zip up the scope tree until
698 // we find one that is.
699 while ((S->getFlags() & Scope::DeclScope) == 0)
700 S = S->getParent();
701
Chris Lattner4b009652007-07-25 00:24:17 +0000702 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000703 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
704 D.getIdentifierLoc(), S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000705 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000706 bool InvalidDecl = false;
707
Chris Lattner82bb4792007-11-14 06:34:38 +0000708 QualType R = GetTypeForDeclarator(D, S);
709 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
710
Chris Lattner4b009652007-07-25 00:24:17 +0000711 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner82bb4792007-11-14 06:34:38 +0000712 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000713 if (!NewTD) return 0;
714
715 // Handle attributes prior to checking for duplicates in MergeVarDecl
716 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
717 D.getAttributes());
Steve Narofff8a09432008-01-09 23:34:55 +0000718 // Merge the decl with the existing one if appropriate. If the decl is
719 // in an outer scope, it isn't the same thing.
720 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000721 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
722 if (NewTD == 0) return 0;
723 }
724 New = NewTD;
725 if (S->getParent() == 0) {
726 // C99 6.7.7p2: If a typedef name specifies a variably modified type
727 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000728 if (const VariableArrayType *VAT =
729 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
730 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
731 VAT->getSizeExpr()->getSourceRange());
732 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000733 }
734 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000735 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000736 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000737 switch (D.getDeclSpec().getStorageClassSpec()) {
738 default: assert(0 && "Unknown storage class!");
739 case DeclSpec::SCS_auto:
740 case DeclSpec::SCS_register:
741 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
742 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000743 InvalidDecl = true;
744 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000745 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
746 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
747 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000748 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000749 }
750
751 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000752 D.getDeclSpec().isInlineSpecified(),
Nate Begeman84079d72007-11-13 22:14:47 +0000753 LastDeclarator,
754 D.getDeclSpec().getAttributes());
755
756 // Transfer ownership of DeclSpec attributes to FunctionDecl
757 D.getDeclSpec().clearAttributes();
Chris Lattner4b009652007-07-25 00:24:17 +0000758
Steve Narofff8a09432008-01-09 23:34:55 +0000759 // Merge the decl with the existing one if appropriate. Since C functions
760 // are in a flat namespace, make sure we consider decls in outer scopes.
Chris Lattner4b009652007-07-25 00:24:17 +0000761 if (PrevDecl) {
762 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
763 if (NewFD == 0) return 0;
764 }
765 New = NewFD;
766 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +0000767 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000768 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
769 D.getIdentifier()->getName());
770 InvalidDecl = true;
771 }
Chris Lattner4b009652007-07-25 00:24:17 +0000772
773 VarDecl *NewVD;
774 VarDecl::StorageClass SC;
775 switch (D.getDeclSpec().getStorageClassSpec()) {
776 default: assert(0 && "Unknown storage class!");
Steve Naroff1cbb2762008-01-25 22:14:40 +0000777 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
778 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
779 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
780 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
781 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
782 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000783 }
784 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000785 // C99 6.9p2: The storage-class specifiers auto and register shall not
786 // appear in the declaration specifiers in an external declaration.
787 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
788 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
789 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000790 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000791 }
Chris Lattner4b009652007-07-25 00:24:17 +0000792 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000793 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000794 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000795 }
Chris Lattner4b009652007-07-25 00:24:17 +0000796 // Handle attributes prior to checking for duplicates in MergeVarDecl
797 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
798 D.getAttributes());
799
Steve Narofff8a09432008-01-09 23:34:55 +0000800 // Merge the decl with the existing one if appropriate. If the decl is
801 // in an outer scope, it isn't the same thing.
802 if (PrevDecl && S->isDeclScope(PrevDecl)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000803 NewVD = MergeVarDecl(NewVD, PrevDecl);
804 if (NewVD == 0) return 0;
805 }
Chris Lattner4b009652007-07-25 00:24:17 +0000806 New = NewVD;
807 }
808
809 // If this has an identifier, add it to the scope stack.
810 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000811 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000812 II->setFETokenInfo(New);
813 S->AddDecl(New);
814 }
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000815 // If any semantic error occurred, mark the decl as invalid.
816 if (D.getInvalidType() || InvalidDecl)
817 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000818
819 return New;
820}
821
Steve Narofff0b23542008-01-10 22:15:12 +0000822bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
823 SourceLocation loc;
824 // FIXME: Remove the isReference check and handle assignment to a reference.
825 if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
826 assert(loc.isValid() && "isConstantExpr didn't return a loc!");
827 Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
828 return true;
829 }
830 return false;
831}
832
Steve Naroff6a0e2092007-09-12 14:07:44 +0000833void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000834 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000835 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000836 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000837
Chris Lattnerf31a2fb2007-10-19 20:10:30 +0000838 // If there is no declaration, there was an error parsing it. Just ignore
839 // the initializer.
840 if (RealDecl == 0) {
841 delete Init;
842 return;
843 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000844
Steve Naroff420d0f52007-09-12 20:13:48 +0000845 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
846 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000847 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
848 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000849 RealDecl->setInvalidDecl();
850 return;
851 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000852 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +0000853 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000854 QualType DclT = VDecl->getType(), SavT = DclT;
855 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000856 VarDecl::StorageClass SC = BVD->getStorageClass();
857 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000858 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000859 BVD->setInvalidDecl();
860 } else if (!BVD->isInvalidDecl()) {
Steve Narofff3cb5142008-01-25 00:51:06 +0000861 if (CheckInitializerTypes(Init, DclT))
862 BVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000863 if (SC == VarDecl::Static) // C99 6.7.8p4.
864 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000865 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000866 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000867 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000868 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000869 if (!FVD->isInvalidDecl())
Steve Narofff3cb5142008-01-25 00:51:06 +0000870 if (CheckInitializerTypes(Init, DclT))
871 FVD->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +0000872
873 // C99 6.7.8p4. All file scoped initializers need to be constant.
874 CheckForConstantInitializer(Init, DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000875 }
876 // If the type changed, it means we had an incomplete type that was
877 // completed by the initializer. For example:
878 // int ary[] = { 1, 3, 5 };
879 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +0000880 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000881 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +0000882 Init->setType(DclT);
883 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000884
885 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000886 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000887 return;
888}
889
Chris Lattner4b009652007-07-25 00:24:17 +0000890/// The declarators are chained together backwards, reverse the list.
891Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
892 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000893 Decl *GroupDecl = static_cast<Decl*>(group);
894 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000895 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000896
897 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
898 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000899 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000900 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000901 else { // reverse the list.
902 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000903 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000904 Group->setNextDeclarator(NewGroup);
905 NewGroup = Group;
906 Group = Next;
907 }
908 }
909 // Perform semantic analysis that depends on having fully processed both
910 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000911 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000912 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
913 if (!IDecl)
914 continue;
915 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
916 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
917 QualType T = IDecl->getType();
918
919 // C99 6.7.5.2p2: If an identifier is declared to be an object with
920 // static storage duration, it shall not have a variable length array.
921 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
922 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
923 if (VLA->getSizeExpr()) {
924 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
925 IDecl->setInvalidDecl();
926 }
927 }
928 }
929 // Block scope. C99 6.7p7: If an identifier for an object is declared with
930 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
931 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
932 if (T->isIncompleteType()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +0000933 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
934 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000935 IDecl->setInvalidDecl();
936 }
937 }
938 // File scope. C99 6.9.2p2: A declaration of an identifier for and
939 // object that has file scope without an initializer, and without a
940 // storage-class specifier or with the storage-class specifier "static",
941 // constitutes a tentative definition. Note: A tentative definition with
942 // external linkage is valid (C99 6.2.2p5).
Steve Narofffef2f052008-01-18 00:39:39 +0000943 if (FVD && !FVD->getInit() && (FVD->getStorageClass() == VarDecl::Static ||
944 FVD->getStorageClass() == VarDecl::None)) {
Steve Naroff60685462008-01-18 20:40:52 +0000945 const VariableArrayType *VAT = T->getAsVariableArrayType();
946
947 if (VAT && VAT->getSizeExpr() == 0) {
948 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
949 // array to be completed. Don't issue a diagnostic.
950 } else if (T->isIncompleteType()) {
951 // C99 6.9.2p3: If the declaration of an identifier for an object is
952 // a tentative definition and has internal linkage (C99 6.2.2p3), the
953 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +0000954 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
955 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +0000956 IDecl->setInvalidDecl();
957 }
958 }
Chris Lattner4b009652007-07-25 00:24:17 +0000959 }
960 return NewGroup;
961}
Steve Naroff91b03f72007-08-28 03:03:08 +0000962
963// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000964ParmVarDecl *
Nate Begeman2240f542007-11-13 21:49:48 +0000965Sema::ActOnParamDeclarator(struct DeclaratorChunk::ParamInfo &PI, Scope *FnScope)
Steve Naroff434fa8d2007-11-12 03:44:46 +0000966{
Chris Lattner4b009652007-07-25 00:24:17 +0000967 IdentifierInfo *II = PI.Ident;
968 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
969 // Can this happen for params? We already checked that they don't conflict
970 // among each other. Here they can only shadow globals, which is ok.
971 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
972 PI.IdentLoc, FnScope)) {
973
974 }
975
976 // FIXME: Handle storage class (auto, register). No declarator?
977 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000978
979 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
980 // Doing the promotion here has a win and a loss. The win is the type for
981 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
982 // code generator). The loss is the orginal type isn't preserved. For example:
983 //
984 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
985 // int blockvardecl[5];
986 // sizeof(parmvardecl); // size == 4
987 // sizeof(blockvardecl); // size == 20
988 // }
989 //
990 // For expressions, all implicit conversions are captured using the
991 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
992 //
993 // FIXME: If a source translation tool needs to see the original type, then
994 // we need to consider storing both types (in ParmVarDecl)...
995 //
996 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
Chris Lattnerc08564a2008-01-02 22:50:48 +0000997 if (const ArrayType *AT = parmDeclType->getAsArrayType()) {
998 // int x[restrict 4] -> int *restrict
Steve Naroff94cd93f2007-08-07 22:44:21 +0000999 parmDeclType = Context.getPointerType(AT->getElementType());
Chris Lattnerc08564a2008-01-02 22:50:48 +00001000 parmDeclType = parmDeclType.getQualifiedType(AT->getIndexTypeQualifier());
1001 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001002 parmDeclType = Context.getPointerType(parmDeclType);
1003
1004 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Nate Begeman84079d72007-11-13 22:14:47 +00001005 VarDecl::None, 0, PI.AttrList);
Steve Naroffcae537d2007-08-28 18:45:29 +00001006 if (PI.InvalidType)
1007 New->setInvalidDecl();
1008
Chris Lattner4b009652007-07-25 00:24:17 +00001009 // If this has an identifier, add it to the scope stack.
1010 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001011 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001012 II->setFETokenInfo(New);
1013 FnScope->AddDecl(New);
1014 }
1015
1016 return New;
1017}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001018
Chris Lattnerea148702007-10-09 17:14:05 +00001019Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +00001020 assert(CurFunctionDecl == 0 && "Function parsing confused");
1021 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1022 "Not a function declarator!");
1023 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1024
1025 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1026 // for a K&R function.
1027 if (!FTI.hasPrototype) {
1028 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1029 if (FTI.ArgInfo[i].TypeInfo == 0) {
1030 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1031 FTI.ArgInfo[i].Ident->getName());
1032 // Implicitly declare the argument as type 'int' for lack of a better
1033 // type.
1034 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
1035 }
1036 }
1037
1038 // Since this is a function definition, act as though we have information
1039 // about the arguments.
1040 FTI.hasPrototype = true;
1041 } else {
1042 // FIXME: Diagnose arguments without names in C.
1043
1044 }
1045
1046 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001047
1048 // See if this is a redefinition.
1049 ScopedDecl *PrevDcl = LookupScopedDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
1050 D.getIdentifierLoc(), GlobalScope);
1051 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(PrevDcl)) {
1052 if (FD->getBody()) {
1053 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1054 D.getIdentifier()->getName());
1055 Diag(FD->getLocation(), diag::err_previous_definition);
1056 }
1057 }
Chris Lattner4b009652007-07-25 00:24:17 +00001058 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +00001059 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Steve Naroff1d5bd642008-01-14 20:51:29 +00001060 assert(FD != 0 && "ActOnDeclarator() didn't return a FunctionDecl");
Chris Lattner4b009652007-07-25 00:24:17 +00001061 CurFunctionDecl = FD;
1062
1063 // Create Decl objects for each parameter, adding them to the FunctionDecl.
1064 llvm::SmallVector<ParmVarDecl*, 16> Params;
1065
1066 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
1067 // no arguments, not a function that takes a single void argument.
1068 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnereee2f2b2007-11-28 18:51:29 +00001069 !QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo).getQualifiers() &&
1070 QualType::getFromOpaquePtr(FTI.ArgInfo[0].TypeInfo)->isVoidType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001071 // empty arg list, don't push any params.
1072 } else {
Steve Naroff434fa8d2007-11-12 03:44:46 +00001073 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Nate Begeman2240f542007-11-13 21:49:48 +00001074 Params.push_back(ActOnParamDeclarator(D.getTypeObject(0).Fun.ArgInfo[i],
Steve Naroff434fa8d2007-11-12 03:44:46 +00001075 FnBodyScope));
1076 }
Chris Lattner4b009652007-07-25 00:24:17 +00001077 }
1078
1079 FD->setParams(&Params[0], Params.size());
1080
1081 return FD;
1082}
1083
Steve Naroff99ee4302007-11-11 23:20:51 +00001084Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1085 Decl *dcl = static_cast<Decl *>(D);
1086 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
1087 FD->setBody((Stmt*)Body);
1088 assert(FD == CurFunctionDecl && "Function parsing confused");
Steve Naroff8ba51142007-12-13 18:18:56 +00001089 CurFunctionDecl = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001090 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001091 MD->setBody((Stmt*)Body);
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001092 CurMethodDecl = 0;
Steve Naroff8ba51142007-12-13 18:18:56 +00001093 }
Chris Lattner4b009652007-07-25 00:24:17 +00001094 // Verify and clean out per-function state.
1095
1096 // Check goto/label use.
1097 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1098 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1099 // Verify that we have no forward references left. If so, there was a goto
1100 // or address of a label taken, but no definition of it. Label fwd
1101 // definitions are indicated with a null substmt.
1102 if (I->second->getSubStmt() == 0) {
1103 LabelStmt *L = I->second;
1104 // Emit error.
1105 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1106
1107 // At this point, we have gotos that use the bogus label. Stitch it into
1108 // the function body so that they aren't leaked and that the AST is well
1109 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001110 if (Body) {
1111 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1112 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1113 } else {
1114 // The whole function wasn't parsed correctly, just delete this.
1115 delete L;
1116 }
Chris Lattner4b009652007-07-25 00:24:17 +00001117 }
1118 }
1119 LabelMap.clear();
1120
Steve Naroff99ee4302007-11-11 23:20:51 +00001121 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001122}
1123
Chris Lattner4b009652007-07-25 00:24:17 +00001124/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1125/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001126ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1127 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +00001128 if (getLangOptions().C99) // Extension in C99.
1129 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
1130 else // Legal in C90, but warn about it.
1131 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1132
1133 // FIXME: handle stuff like:
1134 // void foo() { extern float X(); }
1135 // void bar() { X(); } <-- implicit decl for X in another scope.
1136
1137 // Set a Declarator for the implicit definition: int foo();
1138 const char *Dummy;
1139 DeclSpec DS;
1140 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1141 Error = Error; // Silence warning.
1142 assert(!Error && "Error setting up implicit decl!");
1143 Declarator D(DS, Declarator::BlockContext);
1144 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1145 D.SetIdentifier(&II, Loc);
1146
1147 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +00001148 if (Scope *FnS = S->getFnParent())
1149 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +00001150 while (S->getParent())
1151 S = S->getParent();
1152
Steve Narofff0c31dd2007-09-16 16:16:00 +00001153 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
1156
Chris Lattner82bb4792007-11-14 06:34:38 +00001157TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00001158 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00001159 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001160 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00001161
1162 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001163 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
1164 T, LastDeclarator);
1165 if (D.getInvalidType())
1166 NewTD->setInvalidDecl();
1167 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00001168}
1169
Steve Naroff0acc9c92007-09-15 18:49:24 +00001170/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001171/// former case, Name will be non-null. In the later case, Name will be null.
1172/// TagType indicates what kind of tag this is. TK indicates whether this is a
1173/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001174Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001175 SourceLocation KWLoc, IdentifierInfo *Name,
1176 SourceLocation NameLoc, AttributeList *Attr) {
1177 // If this is a use of an existing tag, it must have a name.
1178 assert((Name != 0 || TK == TK_Definition) &&
1179 "Nameless record must be a definition!");
1180
1181 Decl::Kind Kind;
1182 switch (TagType) {
1183 default: assert(0 && "Unknown tag type!");
1184 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1185 case DeclSpec::TST_union: Kind = Decl::Union; break;
1186//case DeclSpec::TST_class: Kind = Decl::Class; break;
1187 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1188 }
1189
1190 // If this is a named struct, check to see if there was a previous forward
1191 // declaration or definition.
1192 if (TagDecl *PrevDecl =
1193 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1194 NameLoc, S))) {
1195
1196 // If this is a use of a previous tag, or if the tag is already declared in
1197 // the same scope (so that the definition/declaration completes or
1198 // rementions the tag), reuse the decl.
1199 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1200 // Make sure that this wasn't declared as an enum and now used as a struct
1201 // or something similar.
1202 if (PrevDecl->getKind() != Kind) {
1203 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1204 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1205 }
1206
1207 // If this is a use or a forward declaration, we're good.
1208 if (TK != TK_Definition)
1209 return PrevDecl;
1210
1211 // Diagnose attempts to redefine a tag.
1212 if (PrevDecl->isDefinition()) {
1213 Diag(NameLoc, diag::err_redefinition, Name->getName());
1214 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1215 // If this is a redefinition, recover by making this struct be
1216 // anonymous, which will make any later references get the previous
1217 // definition.
1218 Name = 0;
1219 } else {
1220 // Okay, this is definition of a previously declared or referenced tag.
1221 // Move the location of the decl to be the definition site.
1222 PrevDecl->setLocation(NameLoc);
1223 return PrevDecl;
1224 }
1225 }
1226 // If we get here, this is a definition of a new struct type in a nested
1227 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1228 // type.
1229 }
1230
1231 // If there is an identifier, use the location of the identifier as the
1232 // location of the decl, otherwise use the location of the struct/union
1233 // keyword.
1234 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1235
1236 // Otherwise, if this is the first time we've seen this tag, create the decl.
1237 TagDecl *New;
1238 switch (Kind) {
1239 default: assert(0 && "Unknown tag kind!");
1240 case Decl::Enum:
1241 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1242 // enum X { A, B, C } D; D should chain to X.
1243 New = new EnumDecl(Loc, Name, 0);
1244 // If this is an undefined enum, warn.
1245 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1246 break;
1247 case Decl::Union:
1248 case Decl::Struct:
1249 case Decl::Class:
1250 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1251 // struct X { int A; } D; D should chain to X.
1252 New = new RecordDecl(Kind, Loc, Name, 0);
1253 break;
1254 }
1255
1256 // If this has an identifier, add it to the scope stack.
1257 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001258 // The scope passed in may not be a decl scope. Zip up the scope tree until
1259 // we find one that is.
1260 while ((S->getFlags() & Scope::DeclScope) == 0)
1261 S = S->getParent();
1262
1263 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001264 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001265 Name->setFETokenInfo(New);
1266 S->AddDecl(New);
1267 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00001268
Chris Lattner4b009652007-07-25 00:24:17 +00001269 return New;
1270}
1271
Steve Naroff0acc9c92007-09-15 18:49:24 +00001272/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001273/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001274Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001275 SourceLocation DeclStart,
1276 Declarator &D, ExprTy *BitfieldWidth) {
1277 IdentifierInfo *II = D.getIdentifier();
1278 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001279 SourceLocation Loc = DeclStart;
1280 if (II) Loc = D.getIdentifierLoc();
1281
1282 // FIXME: Unnamed fields can be handled in various different ways, for
1283 // example, unnamed unions inject all members into the struct namespace!
1284
1285
1286 if (BitWidth) {
1287 // TODO: Validate.
1288 //printf("WARNING: BITFIELDS IGNORED!\n");
1289
1290 // 6.7.2.1p3
1291 // 6.7.2.1p4
1292
1293 } else {
1294 // Not a bitfield.
1295
1296 // validate II.
1297
1298 }
1299
1300 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001301 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1302 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001303
Chris Lattner4b009652007-07-25 00:24:17 +00001304 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1305 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001306 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1307 Diag(Loc, diag::err_typecheck_illegal_vla,
1308 VAT->getSizeExpr()->getSourceRange());
1309 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001310 }
Chris Lattner4b009652007-07-25 00:24:17 +00001311 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001312 FieldDecl *NewFD;
1313
1314 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Devang Patelf616a242007-11-01 16:29:56 +00001315 NewFD = new FieldDecl(Loc, II, T, BitWidth);
Ted Kremenek42730c52008-01-07 19:49:32 +00001316 else if (isa<ObjCInterfaceDecl>(static_cast<Decl *>(TagDecl)) ||
1317 isa<ObjCImplementationDecl>(static_cast<Decl *>(TagDecl)) ||
1318 isa<ObjCCategoryDecl>(static_cast<Decl *>(TagDecl)) ||
Steve Naroff4fbfb452007-11-14 14:15:31 +00001319 // FIXME: ivars are currently used to model properties, and
1320 // properties can appear within a protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00001321 // See corresponding FIXME in DeclObjC.h:ObjCPropertyDecl.
1322 isa<ObjCProtocolDecl>(static_cast<Decl *>(TagDecl)))
1323 NewFD = new ObjCIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001324 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001325 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001326
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001327 if (D.getInvalidType() || InvalidDecl)
1328 NewFD->setInvalidDecl();
1329 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001330}
1331
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001332/// TranslateIvarVisibility - Translate visibility from a token ID to an
1333/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00001334static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001335TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001336 switch (ivarVisibility) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001337 case tok::objc_private: return ObjCIvarDecl::Private;
1338 case tok::objc_public: return ObjCIvarDecl::Public;
1339 case tok::objc_protected: return ObjCIvarDecl::Protected;
1340 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001341 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001342 }
1343}
1344
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001345void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001346 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001347 DeclTy **Fields, unsigned NumFields,
Steve Naroff1a7fa7b2007-10-29 21:38:07 +00001348 SourceLocation LBrac, SourceLocation RBrac,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001349 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001350 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1351 assert(EnclosingDecl && "missing record or interface decl");
1352 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1353
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001354 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001355 // Diagnose code like:
1356 // struct S { struct S {} X; };
1357 // We discover this when we complete the outer S. Reject and ignore the
1358 // outer S.
1359 Diag(Record->getLocation(), diag::err_nested_redefinition,
1360 Record->getKindName());
1361 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001362 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001363 return;
1364 }
Chris Lattner4b009652007-07-25 00:24:17 +00001365 // Verify that all the fields are okay.
1366 unsigned NumNamedMembers = 0;
1367 llvm::SmallVector<FieldDecl*, 32> RecFields;
1368 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001369
Chris Lattner4b009652007-07-25 00:24:17 +00001370 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001371
Steve Naroff9bb759f2007-09-14 22:20:54 +00001372 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1373 assert(FD && "missing field decl");
1374
1375 // Remember all fields.
1376 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001377
1378 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001379 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001380
Steve Naroffffeaa552007-09-14 23:09:53 +00001381 // If we have visibility info, make sure the AST is set accordingly.
1382 if (visibility)
Ted Kremenek42730c52008-01-07 19:49:32 +00001383 cast<ObjCIvarDecl>(FD)->setAccessControl(
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001384 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001387 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001388 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001389 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001390 FD->setInvalidDecl();
1391 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001392 continue;
1393 }
Chris Lattner4b009652007-07-25 00:24:17 +00001394 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1395 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001396 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001397 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001398 FD->setInvalidDecl();
1399 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001400 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001401 }
Chris Lattner4b009652007-07-25 00:24:17 +00001402 if (i != NumFields-1 || // ... that the last member ...
1403 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001404 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001405 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001406 FD->setInvalidDecl();
1407 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001408 continue;
1409 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001410 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001411 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1412 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001413 FD->setInvalidDecl();
1414 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001415 continue;
1416 }
Chris Lattner4b009652007-07-25 00:24:17 +00001417 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001418 if (Record)
1419 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001420 }
Chris Lattner4b009652007-07-25 00:24:17 +00001421 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1422 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001423 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001424 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1425 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001426 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001427 Record->setHasFlexibleArrayMember(true);
1428 } else {
1429 // If this is a struct/class and this is not the last element, reject
1430 // it. Note that GCC supports variable sized arrays in the middle of
1431 // structures.
1432 if (i != NumFields-1) {
1433 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1434 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001435 FD->setInvalidDecl();
1436 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001437 continue;
1438 }
Chris Lattner4b009652007-07-25 00:24:17 +00001439 // We support flexible arrays at the end of structs in other structs
1440 // as an extension.
1441 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1442 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001443 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001444 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001445 }
1446 }
1447 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001448 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00001449 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001450 Diag(FD->getLocation(), diag::err_statically_allocated_object,
1451 FD->getName());
1452 FD->setInvalidDecl();
1453 EnclosingDecl->setInvalidDecl();
1454 continue;
1455 }
Chris Lattner4b009652007-07-25 00:24:17 +00001456 // Keep track of the number of named members.
1457 if (IdentifierInfo *II = FD->getIdentifier()) {
1458 // Detect duplicate member names.
1459 if (!FieldIDs.insert(II)) {
1460 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1461 // Find the previous decl.
1462 SourceLocation PrevLoc;
1463 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1464 assert(i != e && "Didn't find previous def!");
1465 if (RecFields[i]->getIdentifier() == II) {
1466 PrevLoc = RecFields[i]->getLocation();
1467 break;
1468 }
1469 }
1470 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001471 FD->setInvalidDecl();
1472 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001473 continue;
1474 }
1475 ++NumNamedMembers;
1476 }
Chris Lattner4b009652007-07-25 00:24:17 +00001477 }
1478
Chris Lattner4b009652007-07-25 00:24:17 +00001479 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00001480 if (Record) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001481 Record->defineBody(&RecFields[0], RecFields.size());
Chris Lattner33aad6e2008-02-06 00:51:33 +00001482 Consumer.HandleTagDeclDefinition(Record);
1483 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00001484 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
1485 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
1486 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
1487 else if (ObjCImplementationDecl *IMPDecl =
1488 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001489 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
1490 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00001491 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001492 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001493 }
Chris Lattner4b009652007-07-25 00:24:17 +00001494}
1495
Steve Naroff0acc9c92007-09-15 18:49:24 +00001496Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001497 DeclTy *lastEnumConst,
1498 SourceLocation IdLoc, IdentifierInfo *Id,
1499 SourceLocation EqualLoc, ExprTy *val) {
1500 theEnumDecl = theEnumDecl; // silence unused warning.
1501 EnumConstantDecl *LastEnumConst =
1502 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1503 Expr *Val = static_cast<Expr*>(val);
1504
Chris Lattnera7549902007-08-26 06:24:45 +00001505 // The scope passed in may not be a decl scope. Zip up the scope tree until
1506 // we find one that is.
1507 while ((S->getFlags() & Scope::DeclScope) == 0)
1508 S = S->getParent();
1509
Chris Lattner4b009652007-07-25 00:24:17 +00001510 // Verify that there isn't already something declared with this name in this
1511 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001512 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1513 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001514 if (S->isDeclScope(PrevDecl)) {
1515 if (isa<EnumConstantDecl>(PrevDecl))
1516 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1517 else
1518 Diag(IdLoc, diag::err_redefinition, Id->getName());
1519 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1520 // FIXME: Don't leak memory: delete Val;
1521 return 0;
1522 }
1523 }
1524
1525 llvm::APSInt EnumVal(32);
1526 QualType EltTy;
1527 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001528 // Make sure to promote the operand type to int.
1529 UsualUnaryConversions(Val);
1530
Chris Lattner4b009652007-07-25 00:24:17 +00001531 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1532 SourceLocation ExpLoc;
1533 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1534 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1535 Id->getName());
1536 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001537 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001538 } else {
1539 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001540 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001541 }
1542
1543 if (!Val) {
1544 if (LastEnumConst) {
1545 // Assign the last value + 1.
1546 EnumVal = LastEnumConst->getInitVal();
1547 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001548
1549 // Check for overflow on increment.
1550 if (EnumVal < LastEnumConst->getInitVal())
1551 Diag(IdLoc, diag::warn_enum_value_overflow);
1552
Chris Lattnere7f53a42007-08-27 17:37:24 +00001553 EltTy = LastEnumConst->getType();
1554 } else {
1555 // First value, set to zero.
1556 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001557 EnumVal.zextOrTrunc(
1558 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001559 }
Chris Lattner4b009652007-07-25 00:24:17 +00001560 }
1561
Chris Lattner4b009652007-07-25 00:24:17 +00001562 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1563 LastEnumConst);
1564
1565 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001566 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001567 Id->setFETokenInfo(New);
1568 S->AddDecl(New);
1569 return New;
1570}
1571
Steve Naroff0acc9c92007-09-15 18:49:24 +00001572void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001573 DeclTy **Elements, unsigned NumElements) {
1574 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1575 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1576
Chris Lattner435c3fd2007-08-28 05:10:31 +00001577 // TODO: If the result value doesn't fit in an int, it must be a long or long
1578 // long value. ISO C does not support this, but GCC does as an extension,
1579 // emit a warning.
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001580 unsigned IntWidth =
1581 Context.Target.getIntWidth(Context.getFullLoc(Enum->getLocation()));
Chris Lattner435c3fd2007-08-28 05:10:31 +00001582
1583
Chris Lattner206754a2007-08-28 06:15:15 +00001584 // Verify that all the values are okay, compute the size of the values, and
1585 // reverse the list.
1586 unsigned NumNegativeBits = 0;
1587 unsigned NumPositiveBits = 0;
1588
1589 // Keep track of whether all elements have type int.
1590 bool AllElementsInt = true;
1591
Chris Lattner4b009652007-07-25 00:24:17 +00001592 EnumConstantDecl *EltList = 0;
1593 for (unsigned i = 0; i != NumElements; ++i) {
1594 EnumConstantDecl *ECD =
1595 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1596 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001597
1598 // If the enum value doesn't fit in an int, emit an extension warning.
1599 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1600 "Should have promoted value to int");
1601 const llvm::APSInt &InitVal = ECD->getInitVal();
1602 if (InitVal.getBitWidth() > IntWidth) {
1603 llvm::APSInt V(InitVal);
1604 V.trunc(IntWidth);
1605 V.extend(InitVal.getBitWidth());
1606 if (V != InitVal)
1607 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1608 InitVal.toString());
1609 }
Chris Lattner206754a2007-08-28 06:15:15 +00001610
1611 // Keep track of the size of positive and negative values.
1612 if (InitVal.isUnsigned() || !InitVal.isNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00001613 NumPositiveBits = std::max(NumPositiveBits,
1614 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00001615 else
Chris Lattneraff63f02008-01-14 21:47:29 +00001616 NumNegativeBits = std::max(NumNegativeBits,
1617 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001618
Chris Lattner206754a2007-08-28 06:15:15 +00001619 // Keep track of whether every enum element has type int (very commmon).
1620 if (AllElementsInt)
1621 AllElementsInt = ECD->getType() == Context.IntTy;
1622
Chris Lattner4b009652007-07-25 00:24:17 +00001623 ECD->setNextDeclarator(EltList);
1624 EltList = ECD;
1625 }
1626
Chris Lattner206754a2007-08-28 06:15:15 +00001627 // Figure out the type that should be used for this enum.
1628 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1629 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001630 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001631
1632 if (NumNegativeBits) {
1633 // If there is a negative value, figure out the smallest integer type (of
1634 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001635 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001636 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001637 BestWidth = IntWidth;
1638 } else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001639 BestWidth =
1640 Context.Target.getLongWidth(Context.getFullLoc(Enum->getLocation()));
1641
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001642 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001643 BestType = Context.LongTy;
1644 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001645 BestWidth = Context.Target.getLongLongWidth(
1646 Context.getFullLoc(Enum->getLocation()));
1647
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001648 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001649 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1650 BestType = Context.LongLongTy;
1651 }
1652 }
1653 } else {
1654 // If there is no negative value, figure out which of uint, ulong, ulonglong
1655 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001656 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001657 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001658 BestWidth = IntWidth;
1659 } else if (NumPositiveBits <=
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001660 (BestWidth = Context.Target.getLongWidth(
1661 Context.getFullLoc(Enum->getLocation()))))
1662
Chris Lattner206754a2007-08-28 06:15:15 +00001663 BestType = Context.UnsignedLongTy;
1664 else {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001665 BestWidth =
1666 Context.Target.getLongLongWidth(Context.getFullLoc(Enum->getLocation()));
1667
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001668 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001669 "How could an initializer get larger than ULL?");
1670 BestType = Context.UnsignedLongLongTy;
1671 }
1672 }
1673
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001674 // Loop over all of the enumerator constants, changing their types to match
1675 // the type of the enum if needed.
1676 for (unsigned i = 0; i != NumElements; ++i) {
1677 EnumConstantDecl *ECD =
1678 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1679 if (!ECD) continue; // Already issued a diagnostic.
1680
1681 // Standard C says the enumerators have int type, but we allow, as an
1682 // extension, the enumerators to be larger than int size. If each
1683 // enumerator value fits in an int, type it as an int, otherwise type it the
1684 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1685 // that X has type 'int', not 'unsigned'.
1686 if (ECD->getType() == Context.IntTy)
1687 continue; // Already int type.
1688
1689 // Determine whether the value fits into an int.
1690 llvm::APSInt InitVal = ECD->getInitVal();
1691 bool FitsInInt;
1692 if (InitVal.isUnsigned() || !InitVal.isNegative())
1693 FitsInInt = InitVal.getActiveBits() < IntWidth;
1694 else
1695 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1696
1697 // If it fits into an integer type, force it. Otherwise force it to match
1698 // the enum decl type.
1699 QualType NewTy;
1700 unsigned NewWidth;
1701 bool NewSign;
1702 if (FitsInInt) {
1703 NewTy = Context.IntTy;
1704 NewWidth = IntWidth;
1705 NewSign = true;
1706 } else if (ECD->getType() == BestType) {
1707 // Already the right type!
1708 continue;
1709 } else {
1710 NewTy = BestType;
1711 NewWidth = BestWidth;
1712 NewSign = BestType->isSignedIntegerType();
1713 }
1714
1715 // Adjust the APSInt value.
1716 InitVal.extOrTrunc(NewWidth);
1717 InitVal.setIsSigned(NewSign);
1718 ECD->setInitVal(InitVal);
1719
1720 // Adjust the Expr initializer and type.
1721 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1722 ECD->setType(NewTy);
1723 }
Chris Lattner206754a2007-08-28 06:15:15 +00001724
Chris Lattner90a018d2007-08-28 18:24:31 +00001725 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00001726 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00001727}
1728
Anders Carlsson4f7f4412008-02-08 00:33:21 +00001729Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
1730 ExprTy *expr) {
1731 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
1732
1733 return new FileScopeAsmDecl(Loc, AsmString);
1734}
1735
Chris Lattner806a5f52008-01-12 07:05:38 +00001736Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
1737 SourceLocation LBrace,
1738 SourceLocation RBrace,
1739 const char *Lang,
1740 unsigned StrSize,
1741 DeclTy *D) {
1742 LinkageSpecDecl::LanguageIDs Language;
1743 Decl *dcl = static_cast<Decl *>(D);
1744 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1745 Language = LinkageSpecDecl::lang_c;
1746 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1747 Language = LinkageSpecDecl::lang_cxx;
1748 else {
1749 Diag(Loc, diag::err_bad_language);
1750 return 0;
1751 }
1752
1753 // FIXME: Add all the various semantics of linkage specifications
1754 return new LinkageSpecDecl(Loc, Language, dcl);
1755}
1756
Chris Lattner4b009652007-07-25 00:24:17 +00001757void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
Anders Carlsson28e34e32007-12-19 06:16:30 +00001758 const char *attrName = rawAttr->getAttributeName()->getName();
1759 unsigned attrLen = rawAttr->getAttributeName()->getLength();
1760
Anders Carlsson5f558b52007-12-19 17:43:24 +00001761 // Normalize the attribute name, __foo__ becomes foo.
1762 if (attrLen > 4 && attrName[0] == '_' && attrName[1] == '_' &&
1763 attrName[attrLen - 2] == '_' && attrName[attrLen - 1] == '_') {
1764 attrName += 2;
1765 attrLen -= 4;
1766 }
1767
1768 if (attrLen == 11 && !memcmp(attrName, "vector_size", 11)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001769 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1770 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1771 if (!newType.isNull()) // install the new vector type into the decl
1772 vDecl->setType(newType);
1773 }
1774 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1775 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1776 rawAttr);
1777 if (!newType.isNull()) // install the new vector type into the decl
1778 tDecl->setUnderlyingType(newType);
1779 }
Anders Carlsson5f558b52007-12-19 17:43:24 +00001780 } else if (attrLen == 15 && !memcmp(attrName, "ocu_vector_type", 15)) {
Steve Naroff82113e32007-07-29 16:33:31 +00001781 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1782 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1783 else
Chris Lattner4b009652007-07-25 00:24:17 +00001784 Diag(rawAttr->getAttributeLoc(),
1785 diag::err_typecheck_ocu_vector_not_typedef);
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001786 } else if (attrLen == 13 && !memcmp(attrName, "address_space", 13)) {
1787 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1788 QualType newType = HandleAddressSpaceTypeAttribute(
1789 tDecl->getUnderlyingType(),
1790 rawAttr);
1791 if (!newType.isNull()) // install the new addr spaced type into the decl
1792 tDecl->setUnderlyingType(newType);
1793 } else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1794 QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
1795 rawAttr);
1796 if (!newType.isNull()) // install the new addr spaced type into the decl
1797 vDecl->setType(newType);
1798 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001799 } else if (attrLen == 7 && !memcmp(attrName, "aligned", 7)) {
1800 HandleAlignedAttribute(New, rawAttr);
Chris Lattner4b009652007-07-25 00:24:17 +00001801 }
Anders Carlssonc8b44122007-12-19 07:19:40 +00001802
Chris Lattner4b009652007-07-25 00:24:17 +00001803 // FIXME: add other attributes...
1804}
1805
1806void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1807 AttributeList *declarator_postfix) {
1808 while (declspec_prefix) {
1809 HandleDeclAttribute(New, declspec_prefix);
1810 declspec_prefix = declspec_prefix->getNext();
1811 }
1812 while (declarator_postfix) {
1813 HandleDeclAttribute(New, declarator_postfix);
1814 declarator_postfix = declarator_postfix->getNext();
1815 }
1816}
1817
Christopher Lamb2a72bb32008-02-04 02:31:56 +00001818QualType Sema::HandleAddressSpaceTypeAttribute(QualType curType,
1819 AttributeList *rawAttr) {
1820 // check the attribute arugments.
1821 if (rawAttr->getNumArgs() != 1) {
1822 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1823 std::string("1"));
1824 return QualType();
1825 }
1826 Expr *addrSpaceExpr = static_cast<Expr *>(rawAttr->getArg(0));
1827 llvm::APSInt addrSpace(32);
1828 if (!addrSpaceExpr->isIntegerConstantExpr(addrSpace, Context)) {
1829 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_address_space_not_int,
1830 addrSpaceExpr->getSourceRange());
1831 return QualType();
1832 }
1833 unsigned addressSpace = static_cast<unsigned>(addrSpace.getZExtValue());
1834
1835 // Zero is the default memory space, so no qualification is needed
1836 if (addressSpace == 0)
1837 return curType;
1838
1839 // TODO: Should we convert contained types of address space
1840 // qualified types here or or where they directly participate in conversions
1841 // (i.e. elsewhere)
1842
1843 return Context.getASQualType(curType, addressSpace);
1844}
1845
Steve Naroff82113e32007-07-29 16:33:31 +00001846void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1847 AttributeList *rawAttr) {
1848 QualType curType = tDecl->getUnderlyingType();
Anders Carlssonc8b44122007-12-19 07:19:40 +00001849 // check the attribute arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001850 if (rawAttr->getNumArgs() != 1) {
1851 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1852 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00001853 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001854 }
1855 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1856 llvm::APSInt vecSize(32);
1857 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1858 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1859 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001860 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001861 }
1862 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1863 // in conjunction with complex types (pointers, arrays, functions, etc.).
1864 Type *canonType = curType.getCanonicalType().getTypePtr();
1865 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1866 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1867 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00001868 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001869 }
1870 // unlike gcc's vector_size attribute, the size is specified as the
1871 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00001872 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00001873
1874 if (vectorSize == 0) {
1875 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1876 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00001877 return;
Chris Lattner4b009652007-07-25 00:24:17 +00001878 }
Steve Naroff82113e32007-07-29 16:33:31 +00001879 // Instantiate/Install the vector type, the number of elements is > 0.
1880 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1881 // Remember this typedef decl, we will need it later for diagnostics.
1882 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001883}
1884
1885QualType Sema::HandleVectorTypeAttribute(QualType curType,
1886 AttributeList *rawAttr) {
1887 // check the attribute arugments.
1888 if (rawAttr->getNumArgs() != 1) {
1889 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1890 std::string("1"));
1891 return QualType();
1892 }
1893 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1894 llvm::APSInt vecSize(32);
1895 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1896 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1897 sizeExpr->getSourceRange());
1898 return QualType();
1899 }
1900 // navigate to the base type - we need to provide for vector pointers,
1901 // vector arrays, and functions returning vectors.
1902 Type *canonType = curType.getCanonicalType().getTypePtr();
1903
1904 if (canonType->isPointerType() || canonType->isArrayType() ||
1905 canonType->isFunctionType()) {
Chris Lattner5b5e1982007-12-19 05:38:06 +00001906 assert(0 && "HandleVector(): Complex type construction unimplemented");
Chris Lattner4b009652007-07-25 00:24:17 +00001907 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
1908 do {
1909 if (PointerType *PT = dyn_cast<PointerType>(canonType))
1910 canonType = PT->getPointeeType().getTypePtr();
1911 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
1912 canonType = AT->getElementType().getTypePtr();
1913 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
1914 canonType = FT->getResultType().getTypePtr();
1915 } while (canonType->isPointerType() || canonType->isArrayType() ||
1916 canonType->isFunctionType());
1917 */
1918 }
1919 // the base type must be integer or float.
1920 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1921 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1922 curType.getCanonicalType().getAsString());
1923 return QualType();
1924 }
Chris Lattner3496d522007-09-04 02:45:27 +00001925 unsigned typeSize = static_cast<unsigned>(
1926 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00001927 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00001928 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00001929
1930 // the vector size needs to be an integral multiple of the type size.
1931 if (vectorSize % typeSize) {
1932 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
1933 sizeExpr->getSourceRange());
1934 return QualType();
1935 }
1936 if (vectorSize == 0) {
1937 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1938 sizeExpr->getSourceRange());
1939 return QualType();
1940 }
1941 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
1942 // the number of elements to be a power of two (unlike GCC).
1943 // Instantiate the vector type, the number of elements is > 0.
1944 return Context.getVectorType(curType, vectorSize/typeSize);
1945}
1946
Anders Carlssonc8b44122007-12-19 07:19:40 +00001947void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
1948{
1949 // check the attribute arguments.
Eli Friedman74820702008-01-30 17:38:42 +00001950 if (rawAttr->getNumArgs() > 1) {
Anders Carlssonc8b44122007-12-19 07:19:40 +00001951 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1952 std::string("1"));
1953 return;
1954 }
Eli Friedman74820702008-01-30 17:38:42 +00001955
Devang Patela31965b2008-01-30 18:00:07 +00001956 // TODO: We probably need to actually do something with aligned attribute.
Eli Friedman74820702008-01-30 17:38:42 +00001957 if (rawAttr->getNumArgs() == 0)
1958 return;
1959
Anders Carlssonc8b44122007-12-19 07:19:40 +00001960 Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
1961 llvm::APSInt alignment(32);
1962 if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
1963 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1964 alignmentExpr->getSourceRange());
1965 return;
1966 }
1967}