blob: 71ba023dcf081604807b8e12e659db79c57058db [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
23#include "clang/Lex/IdentifierTable.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000026#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000028#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner5c0fa302007-09-30 08:31:00 +000032 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
33 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
34 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000035 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
38void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000039 if (S->decl_empty()) return;
40 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
41
Reid Spencer5f016e22007-07-11 17:01:13 +000042 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
43 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000044 Decl *TmpD = static_cast<Decl*>(*I);
45 assert(TmpD && "This decl didn't get pushed??");
46 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
47 assert(D && "This decl isn't a ScopedDecl?");
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049 IdentifierInfo *II = D->getIdentifier();
50 if (!II) continue;
51
52 // Unlink this decl from the identifier. Because the scope contains decls
53 // in an unordered collection, and because we have multiple identifier
54 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
55 if (II->getFETokenInfo<Decl>() == D) {
56 // Normal case, no multiple decls in different namespaces.
57 II->setFETokenInfo(D->getNext());
58 } else {
59 // Scan ahead. There are only three namespaces in C, so this loop can
60 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000061 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000062 while (SomeDecl->getNext() != D) {
63 SomeDecl = SomeDecl->getNext();
64 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
65 }
66 SomeDecl->setNext(D->getNext());
67 }
68
69 // This will have to be revisited for C++: there we want to nest stuff in
70 // namespace decls etc. Even for C, we might want a top-level translation
71 // unit decl or something.
72 if (!CurFunctionDecl)
73 continue;
74
75 // Chain this decl to the containing function, it now owns the memory for
76 // the decl.
77 D->setNext(CurFunctionDecl->getDeclChain());
78 CurFunctionDecl->setDeclChain(D);
79 }
80}
81
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000082/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000083/// return 0 if one not found.
Steve Naroff6a8a9a42007-10-02 20:01:56 +000084ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
85
86 // Scan up the scope chain looking for a decl that matches this identifier
87 // that is in the appropriate namespace. This search should not take long, as
88 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
89 ScopedDecl *IdDecl = NULL;
90 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
91 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
92 IdDecl = D;
93 break;
94 }
95 }
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000096 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
97 IdDecl = 0;
98 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
99}
100
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000101/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
102/// return 0 if one not found.
103ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000104 IdentifierInfo *Id,
105 SourceLocation IdLoc) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000106 // Note that Protocols have their own namespace.
Fariborz Jahanian245f92a2007-10-05 21:01:53 +0000107 ScopedDecl *PrDecl = NULL;
108 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
109 if (D->getIdentifierNamespace() == Decl::IDNS_Protocol) {
110 PrDecl = D;
111 break;
112 }
113 }
114
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000115 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
116 PrDecl = 0;
117 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
118}
119
Reid Spencer5f016e22007-07-11 17:01:13 +0000120/// LookupScopedDecl - Look up the inner-most declaration in the specified
121/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000122ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
123 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 if (II == 0) return 0;
125 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
126
127 // Scan up the scope chain looking for a decl that matches this identifier
128 // that is in the appropriate namespace. This search should not take long, as
129 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000130 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 if (D->getIdentifierNamespace() == NS)
132 return D;
133
134 // If we didn't find a use of this identifier, and if the identifier
135 // corresponds to a compiler builtin, create the decl object for the builtin
136 // now, injecting it into translation unit scope, and return it.
137 if (NS == Decl::IDNS_Ordinary) {
138 // If this is a builtin on some other target, or if this builtin varies
139 // across targets (e.g. in type), emit a diagnostic and mark the translation
140 // unit non-portable for using it.
141 if (II->isNonPortableBuiltin()) {
142 // Only emit this diagnostic once for this builtin.
143 II->setNonPortableBuiltin(false);
144 Context.Target.DiagnoseNonPortability(IdLoc,
145 diag::port_target_builtin_use);
146 }
147 // If this is a builtin on this (or all) targets, create the decl.
148 if (unsigned BuiltinID = II->getBuiltinID())
149 return LazilyCreateBuiltin(II, BuiltinID, S);
150 }
151 return 0;
152}
153
154/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
155/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000156ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 Builtin::ID BID = (Builtin::ID)bid;
158
159 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
160 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000161 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000162
163 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000164 if (Scope *FnS = S->getFnParent())
165 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 while (S->getParent())
167 S = S->getParent();
168 S->AddDecl(New);
169
170 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000171 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 // Scan until we find the last (outermost) decl in the id chain.
173 while (LastDecl->getNext())
174 LastDecl = LastDecl->getNext();
175 // Insert before (outside) it.
176 LastDecl->setNext(New);
177 } else {
178 II->setFETokenInfo(New);
179 }
180 // Make sure clients iterating over decls see this.
181 LastInGroupList.push_back(New);
182
183 return New;
184}
185
186/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
187/// and scope as a previous declaration 'Old'. Figure out how to resolve this
188/// situation, merging decls or emitting diagnostics as appropriate.
189///
Steve Naroff8e74c932007-09-13 21:41:19 +0000190TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 // Verify the old decl was also a typedef.
192 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
193 if (!Old) {
194 Diag(New->getLocation(), diag::err_redefinition_different_kind,
195 New->getName());
196 Diag(OldD->getLocation(), diag::err_previous_definition);
197 return New;
198 }
199
200 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
201 // TODO: This is totally simplistic. It should handle merging functions
202 // together etc, merging extern int X; int X; ...
203 Diag(New->getLocation(), diag::err_redefinition, New->getName());
204 Diag(Old->getLocation(), diag::err_previous_definition);
205 return New;
206}
207
208/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
209/// and scope as a previous declaration 'Old'. Figure out how to resolve this
210/// situation, merging decls or emitting diagnostics as appropriate.
211///
Steve Naroff8e74c932007-09-13 21:41:19 +0000212FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // Verify the old decl was also a function.
214 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
215 if (!Old) {
216 Diag(New->getLocation(), diag::err_redefinition_different_kind,
217 New->getName());
218 Diag(OldD->getLocation(), diag::err_previous_definition);
219 return New;
220 }
221
222 // This is not right, but it's a start. If 'Old' is a function prototype with
223 // the same type as 'New', silently allow this. FIXME: We should link up decl
224 // objects here.
225 if (Old->getBody() == 0 &&
226 Old->getCanonicalType() == New->getCanonicalType()) {
227 return New;
228 }
229
230 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
231 // TODO: This is totally simplistic. It should handle merging functions
232 // together etc, merging extern int X; int X; ...
233 Diag(New->getLocation(), diag::err_redefinition, New->getName());
234 Diag(Old->getLocation(), diag::err_previous_definition);
235 return New;
236}
237
238/// MergeVarDecl - We just parsed a variable 'New' which has the same name
239/// and scope as a previous declaration 'Old'. Figure out how to resolve this
240/// situation, merging decls or emitting diagnostics as appropriate.
241///
242/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
243/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
244///
Steve Naroff8e74c932007-09-13 21:41:19 +0000245VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000246 // Verify the old decl was also a variable.
247 VarDecl *Old = dyn_cast<VarDecl>(OldD);
248 if (!Old) {
249 Diag(New->getLocation(), diag::err_redefinition_different_kind,
250 New->getName());
251 Diag(OldD->getLocation(), diag::err_previous_definition);
252 return New;
253 }
Steve Narofffb22d962007-08-30 01:06:46 +0000254 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
255 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
256 bool OldIsTentative = false;
257
258 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
259 // Handle C "tentative" external object definitions. FIXME: finish!
260 if (!OldFSDecl->getInit() &&
261 (OldFSDecl->getStorageClass() == VarDecl::None ||
262 OldFSDecl->getStorageClass() == VarDecl::Static))
263 OldIsTentative = true;
264 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 // Verify the types match.
266 if (Old->getCanonicalType() != New->getCanonicalType()) {
267 Diag(New->getLocation(), diag::err_redefinition, New->getName());
268 Diag(Old->getLocation(), diag::err_previous_definition);
269 return New;
270 }
271 // We've verified the types match, now check if Old is "extern".
272 if (Old->getStorageClass() != VarDecl::Extern) {
273 Diag(New->getLocation(), diag::err_redefinition, New->getName());
274 Diag(Old->getLocation(), diag::err_previous_definition);
275 }
276 return New;
277}
278
279/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
280/// no declarator (e.g. "struct foo;") is parsed.
281Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
282 // TODO: emit error on 'int;' or 'const enum foo;'.
283 // TODO: emit error on 'typedef int;'
284 // if (!DS.isMissingDeclaratorOk()) Diag(...);
285
286 return 0;
287}
288
Steve Naroff9e8925e2007-09-04 14:36:54 +0000289bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000290 AssignmentCheckResult result;
291 SourceLocation loc = Init->getLocStart();
292 // Get the type before calling CheckSingleAssignmentConstraints(), since
293 // it can promote the expression.
294 QualType rhsType = Init->getType();
295
296 result = CheckSingleAssignmentConstraints(DeclType, Init);
297
298 // decode the result (notice that extensions still return a type).
299 switch (result) {
300 case Compatible:
301 break;
302 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000303 // FIXME: tighten up this check which should allow:
304 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
305 if (rhsType == Context.getPointerType(Context.CharTy))
306 break;
Steve Narofff0090632007-09-02 02:04:30 +0000307 Diag(loc, diag::err_typecheck_assign_incompatible,
308 DeclType.getAsString(), rhsType.getAsString(),
309 Init->getSourceRange());
310 return true;
311 case PointerFromInt:
312 // check for null pointer constant (C99 6.3.2.3p3)
313 if (!Init->isNullPointerConstant(Context)) {
314 Diag(loc, diag::ext_typecheck_assign_pointer_int,
315 DeclType.getAsString(), rhsType.getAsString(),
316 Init->getSourceRange());
317 return true;
318 }
319 break;
320 case IntFromPointer:
321 Diag(loc, diag::ext_typecheck_assign_pointer_int,
322 DeclType.getAsString(), rhsType.getAsString(),
323 Init->getSourceRange());
324 break;
325 case IncompatiblePointer:
326 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
327 DeclType.getAsString(), rhsType.getAsString(),
328 Init->getSourceRange());
329 break;
330 case CompatiblePointerDiscardsQualifiers:
331 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
332 DeclType.getAsString(), rhsType.getAsString(),
333 Init->getSourceRange());
334 break;
335 }
336 return false;
337}
338
Steve Naroff9e8925e2007-09-04 14:36:54 +0000339bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
340 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000341 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000342 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000343
344 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
345 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
346 return true;
347 } else if (CheckSingleInitializer(expr, ElementType)) {
348 return true; // types weren't compatible.
349 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000350 if (savExpr != expr) // The type was promoted, update initializer list.
351 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000352 return false;
353}
354
355void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
356 QualType ElementType, bool isStatic,
357 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000358 for (unsigned i = 0; i < IList->getNumInits(); i++) {
359 Expr *expr = IList->getInit(i);
360
Steve Naroff371227d2007-09-04 02:20:04 +0000361 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
362 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000363 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000364 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
365 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000366 }
Steve Naroff371227d2007-09-04 02:20:04 +0000367 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000368 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000369 }
Steve Naroff371227d2007-09-04 02:20:04 +0000370 nInitializers++;
371 }
372 return;
373}
374
375// FIXME: Doesn't deal with arrays of structures yet.
376void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
377 QualType ElementType, bool isStatic,
378 int &totalInits, bool &hadError) {
379 int maxElementsAtThisLevel = 0;
380 int nInitsAtLevel = 0;
381
382 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
383 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000384 maxElementsAtThisLevel = CAT->getMaximumElements();
385 // Set DeclType, used below to recurse (for multi-dimensional arrays).
386 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000387 } else if (DeclType->isScalarType()) {
388 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
389 IList->getSourceRange());
390 maxElementsAtThisLevel = 1;
391 }
392 // The empty init list "{ }" is treated specially below.
393 unsigned numInits = IList->getNumInits();
394 if (numInits) {
395 for (unsigned i = 0; i < numInits; i++) {
396 Expr *expr = IList->getInit(i);
397
398 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
399 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
400 totalInits, hadError);
401 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000402 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000403 nInitsAtLevel++; // increment the number of initializers at this level.
404 totalInits--; // decrement the total number of initializers.
405
406 // Check if we have space for another initializer.
407 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
408 Diag(expr->getLocStart(), diag::warn_excess_initializers,
409 expr->getSourceRange());
410 }
411 }
412 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
413 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
414 } else {
415 // we have an initializer list with no elements.
416 totalInits -= maxElementsAtThisLevel;
417 if (totalInits < 0)
418 Diag(IList->getLocStart(), diag::warn_excess_initializers,
419 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000420 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000421 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000422}
423
Steve Naroff9e8925e2007-09-04 14:36:54 +0000424bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000425 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000426 if (!InitList)
427 return CheckSingleInitializer(Init, DeclType);
428
Steve Narofff0090632007-09-02 02:04:30 +0000429 // We have an InitListExpr, make sure we set the type.
430 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000431
432 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000433
Steve Naroff38374b02007-09-02 20:30:18 +0000434 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
435 // of unknown size ("[]") or an object type that is not a variable array type.
436 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
437 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000438 if (expr)
439 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
440 expr->getSourceRange());
441
Steve Naroff7cf8c442007-09-04 21:13:33 +0000442 // We have a VariableArrayType with unknown size. Note that only the first
443 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000444 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000445 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
446 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000447 if (!hadError) {
448 // Return a new array type from the number of initializers (C99 6.7.8p22).
449 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000450 ConstVal = numInits;
451 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000452 ArrayType::Normal, 0);
453 }
454 return hadError;
455 }
456 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000457 int maxElements = CAT->getMaximumElements();
458 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
459 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000460 return hadError;
461 }
Steve Naroff371227d2007-09-04 02:20:04 +0000462 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
463 int maxElements = 1;
464 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
465 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000466 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000467 }
468 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000469 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000470}
471
Reid Spencer5f016e22007-07-11 17:01:13 +0000472Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000473Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000474 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 IdentifierInfo *II = D.getIdentifier();
476
Chris Lattnere80a59c2007-07-25 00:24:17 +0000477 // All of these full declarators require an identifier. If it doesn't have
478 // one, the ParsedFreeStandingDeclSpec action should be used.
479 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000480 Diag(D.getDeclSpec().getSourceRange().Begin(),
481 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000482 D.getDeclSpec().getSourceRange(), D.getSourceRange());
483 return 0;
484 }
485
Chris Lattner31e05722007-08-26 06:24:45 +0000486 // The scope passed in may not be a decl scope. Zip up the scope tree until
487 // we find one that is.
488 while ((S->getFlags() & Scope::DeclScope) == 0)
489 S = S->getParent();
490
Reid Spencer5f016e22007-07-11 17:01:13 +0000491 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000492 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
493 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 if (PrevDecl && !S->isDeclScope(PrevDecl))
495 PrevDecl = 0; // If in outer scope, it isn't the same thing.
496
Steve Naroffc752d042007-09-13 18:10:37 +0000497 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000498 bool InvalidDecl = false;
499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
501 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
502 if (!NewTD) return 0;
503
504 // Handle attributes prior to checking for duplicates in MergeVarDecl
505 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
506 D.getAttributes());
507 // Merge the decl with the existing one if appropriate.
508 if (PrevDecl) {
509 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
510 if (NewTD == 0) return 0;
511 }
512 New = NewTD;
513 if (S->getParent() == 0) {
514 // C99 6.7.7p2: If a typedef name specifies a variably modified type
515 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000516 if (const VariableArrayType *VAT =
517 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
518 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
519 VAT->getSizeExpr()->getSourceRange());
520 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 }
522 }
523 } else if (D.isFunctionDeclarator()) {
524 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000525 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000526
Chris Lattner271f1a62007-09-27 15:15:46 +0000527 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 switch (D.getDeclSpec().getStorageClassSpec()) {
529 default: assert(0 && "Unknown storage class!");
530 case DeclSpec::SCS_auto:
531 case DeclSpec::SCS_register:
532 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
533 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000534 InvalidDecl = true;
535 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
537 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
538 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
539 }
540
541 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000542 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 LastDeclarator);
544
545 // Merge the decl with the existing one if appropriate.
546 if (PrevDecl) {
547 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
548 if (NewFD == 0) return 0;
549 }
550 New = NewFD;
551 } else {
552 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000553 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000554
555 VarDecl *NewVD;
556 VarDecl::StorageClass SC;
557 switch (D.getDeclSpec().getStorageClassSpec()) {
558 default: assert(0 && "Unknown storage class!");
559 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
560 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
561 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
562 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
563 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
564 }
565 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 // C99 6.9p2: The storage-class specifiers auto and register shall not
567 // appear in the declaration specifiers in an external declaration.
568 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
569 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
570 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000571 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000574 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000576 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 // Handle attributes prior to checking for duplicates in MergeVarDecl
578 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
579 D.getAttributes());
580
581 // Merge the decl with the existing one if appropriate.
582 if (PrevDecl) {
583 NewVD = MergeVarDecl(NewVD, PrevDecl);
584 if (NewVD == 0) return 0;
585 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 New = NewVD;
587 }
588
589 // If this has an identifier, add it to the scope stack.
590 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000591 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 II->setFETokenInfo(New);
593 S->AddDecl(New);
594 }
595
596 if (S->getParent() == 0)
597 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000598
599 // If any semantic error occurred, mark the decl as invalid.
600 if (D.getInvalidType() || InvalidDecl)
601 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000602
603 return New;
604}
605
Steve Naroffbb204692007-09-12 14:07:44 +0000606void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000607 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000608 Expr *Init = static_cast<Expr *>(init);
609
Steve Naroff410e3e22007-09-12 20:13:48 +0000610 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000611
Steve Naroff410e3e22007-09-12 20:13:48 +0000612 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
613 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000614 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
615 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000616 RealDecl->setInvalidDecl();
617 return;
618 }
Steve Naroffbb204692007-09-12 14:07:44 +0000619 // Get the decls type and save a reference for later, since
620 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000621 QualType DclT = VDecl->getType(), SavT = DclT;
622 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000623 VarDecl::StorageClass SC = BVD->getStorageClass();
624 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000625 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000626 BVD->setInvalidDecl();
627 } else if (!BVD->isInvalidDecl()) {
628 CheckInitializer(Init, DclT, SC == VarDecl::Static);
629 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000630 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000631 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000632 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000633 if (!FVD->isInvalidDecl())
634 CheckInitializer(Init, DclT, true);
635 }
636 // If the type changed, it means we had an incomplete type that was
637 // completed by the initializer. For example:
638 // int ary[] = { 1, 3, 5 };
639 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000640 if (!VDecl->isInvalidDecl() && (DclT != SavT))
641 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000642
643 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000644 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000645 return;
646}
647
Reid Spencer5f016e22007-07-11 17:01:13 +0000648/// The declarators are chained together backwards, reverse the list.
649Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
650 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000651 Decl *GroupDecl = static_cast<Decl*>(group);
652 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000653 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000654
655 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
656 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000657 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000659 else { // reverse the list.
660 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000661 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000662 Group->setNextDeclarator(NewGroup);
663 NewGroup = Group;
664 Group = Next;
665 }
666 }
667 // Perform semantic analysis that depends on having fully processed both
668 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000669 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000670 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
671 if (!IDecl)
672 continue;
673 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
674 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
675 QualType T = IDecl->getType();
676
677 // C99 6.7.5.2p2: If an identifier is declared to be an object with
678 // static storage duration, it shall not have a variable length array.
679 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
680 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
681 if (VLA->getSizeExpr()) {
682 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
683 IDecl->setInvalidDecl();
684 }
685 }
686 }
687 // Block scope. C99 6.7p7: If an identifier for an object is declared with
688 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
689 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
690 if (T->isIncompleteType()) {
691 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
692 T.getAsString());
693 IDecl->setInvalidDecl();
694 }
695 }
696 // File scope. C99 6.9.2p2: A declaration of an identifier for and
697 // object that has file scope without an initializer, and without a
698 // storage-class specifier or with the storage-class specifier "static",
699 // constitutes a tentative definition. Note: A tentative definition with
700 // external linkage is valid (C99 6.2.2p5).
701 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
702 // C99 6.9.2p3: If the declaration of an identifier for an object is
703 // a tentative definition and has internal linkage (C99 6.2.2p3), the
704 // declared type shall not be an incomplete type.
705 if (T->isIncompleteType()) {
706 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
707 T.getAsString());
708 IDecl->setInvalidDecl();
709 }
710 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 }
712 return NewGroup;
713}
Steve Naroffe1223f72007-08-28 03:03:08 +0000714
715// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000716ParmVarDecl *
717Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
718 Scope *FnScope) {
719 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
720
721 IdentifierInfo *II = PI.Ident;
722 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
723 // Can this happen for params? We already checked that they don't conflict
724 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000725 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 PI.IdentLoc, FnScope)) {
727
728 }
729
730 // FIXME: Handle storage class (auto, register). No declarator?
731 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000732
733 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
734 // Doing the promotion here has a win and a loss. The win is the type for
735 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
736 // code generator). The loss is the orginal type isn't preserved. For example:
737 //
738 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
739 // int blockvardecl[5];
740 // sizeof(parmvardecl); // size == 4
741 // sizeof(blockvardecl); // size == 20
742 // }
743 //
744 // For expressions, all implicit conversions are captured using the
745 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
746 //
747 // FIXME: If a source translation tool needs to see the original type, then
748 // we need to consider storing both types (in ParmVarDecl)...
749 //
750 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
751 if (const ArrayType *AT = parmDeclType->getAsArrayType())
752 parmDeclType = Context.getPointerType(AT->getElementType());
753 else if (parmDeclType->isFunctionType())
754 parmDeclType = Context.getPointerType(parmDeclType);
755
756 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000757 VarDecl::None, 0);
758 if (PI.InvalidType)
759 New->setInvalidDecl();
760
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 // If this has an identifier, add it to the scope stack.
762 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000763 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 II->setFETokenInfo(New);
765 FnScope->AddDecl(New);
766 }
767
768 return New;
769}
770
771
772Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
773 assert(CurFunctionDecl == 0 && "Function parsing confused");
774 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
775 "Not a function declarator!");
776 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
777
778 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
779 // for a K&R function.
780 if (!FTI.hasPrototype) {
781 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
782 if (FTI.ArgInfo[i].TypeInfo == 0) {
783 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
784 FTI.ArgInfo[i].Ident->getName());
785 // Implicitly declare the argument as type 'int' for lack of a better
786 // type.
787 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
788 }
789 }
790
791 // Since this is a function definition, act as though we have information
792 // about the arguments.
793 FTI.hasPrototype = true;
794 } else {
795 // FIXME: Diagnose arguments without names in C.
796
797 }
798
799 Scope *GlobalScope = FnBodyScope->getParent();
800
801 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000802 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 CurFunctionDecl = FD;
804
805 // Create Decl objects for each parameter, adding them to the FunctionDecl.
806 llvm::SmallVector<ParmVarDecl*, 16> Params;
807
808 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
809 // no arguments, not a function that takes a single void argument.
810 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
811 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
812 // empty arg list, don't push any params.
813 } else {
814 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
815 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
816 }
817
818 FD->setParams(&Params[0], Params.size());
819
820 return FD;
821}
822
823Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
824 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
825 FD->setBody((Stmt*)Body);
826
827 assert(FD == CurFunctionDecl && "Function parsing confused");
828 CurFunctionDecl = 0;
829
830 // Verify and clean out per-function state.
831
832 // Check goto/label use.
833 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
834 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
835 // Verify that we have no forward references left. If so, there was a goto
836 // or address of a label taken, but no definition of it. Label fwd
837 // definitions are indicated with a null substmt.
838 if (I->second->getSubStmt() == 0) {
839 LabelStmt *L = I->second;
840 // Emit error.
841 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
842
843 // At this point, we have gotos that use the bogus label. Stitch it into
844 // the function body so that they aren't leaked and that the AST is well
845 // formed.
846 L->setSubStmt(new NullStmt(L->getIdentLoc()));
847 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
848 }
849 }
850 LabelMap.clear();
851
852 return FD;
853}
854
855
856/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
857/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000858ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
859 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 if (getLangOptions().C99) // Extension in C99.
861 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
862 else // Legal in C90, but warn about it.
863 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
864
865 // FIXME: handle stuff like:
866 // void foo() { extern float X(); }
867 // void bar() { X(); } <-- implicit decl for X in another scope.
868
869 // Set a Declarator for the implicit definition: int foo();
870 const char *Dummy;
871 DeclSpec DS;
872 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
873 Error = Error; // Silence warning.
874 assert(!Error && "Error setting up implicit decl!");
875 Declarator D(DS, Declarator::BlockContext);
876 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
877 D.SetIdentifier(&II, Loc);
878
879 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000880 if (Scope *FnS = S->getFnParent())
881 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000882 while (S->getParent())
883 S = S->getParent();
884
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000885 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000886}
887
888
889TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000890 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
892
893 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000894 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000895
896 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000897 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
898 T, LastDeclarator);
899 if (D.getInvalidType())
900 NewTD->setInvalidDecl();
901 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000902}
903
Steve Naroff3a165b02007-10-03 21:00:46 +0000904Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000905 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000906 IdentifierInfo *ClassName, SourceLocation ClassLoc,
907 IdentifierInfo *SuperName, SourceLocation SuperLoc,
908 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
909 AttributeList *AttrList) {
910 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000911
912 // Check for another declaration kind with the same name.
913 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
914 ClassLoc, S);
915 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
916 && !isa<ObjcProtocolDecl>(PrevDecl)) {
917 Diag(ClassLoc, diag::err_redefinition_different_kind,
918 ClassName->getName());
919 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
920 }
921
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000922 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000923 if (IDecl) {
924 // Class already seen. Is it a forward declaration?
Steve Naroff768f26e2007-10-02 20:26:23 +0000925 if (!IDecl->isForwardDecl())
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000926 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000927 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000928 IDecl->setForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000929 IDecl->AllocIntfRefProtocols(NumProtocols);
930 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000931 }
932 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000933 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000934
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000935 // Chain & install the interface decl into the identifier.
936 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
937 ClassName->setFETokenInfo(IDecl);
938 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000939
940 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000941 ObjcInterfaceDecl* SuperClassEntry = 0;
942 // Check if a different kind of symbol declared in this scope.
943 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
944 SuperLoc, S);
945 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
946 && !isa<ObjcProtocolDecl>(PrevDecl)) {
947 Diag(SuperLoc, diag::err_redefinition_different_kind,
948 SuperName->getName());
949 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000950 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000951 else {
952 // Check that super class is previously defined
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000953 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000954
Steve Naroff768f26e2007-10-02 20:26:23 +0000955 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000956 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
957 ClassName->getName());
958 }
959 }
960 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000961 }
962
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000963 /// Check then save referenced protocols
964 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000965 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000966 ClassLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +0000967 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000968 Diag(ClassLoc, diag::err_undef_protocolref,
969 ProtocolNames[i]->getName(),
970 ClassName->getName());
971 IDecl->setIntfRefProtocols((int)i, RefPDecl);
972 }
973
Steve Naroff3536b442007-09-06 21:24:23 +0000974 return IDecl;
975}
976
Steve Naroff3a165b02007-10-03 21:00:46 +0000977Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000978 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000979 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
980 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
981 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000982 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000983 if (PDecl) {
984 // Protocol already seen. Better be a forward protocol declaration
Steve Naroff768f26e2007-10-02 20:26:23 +0000985 if (!PDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000986 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
987 ProtocolName->getName());
988 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000989 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000990 PDecl->AllocReferencedProtocols(NumProtoRefs);
991 }
992 }
993 else {
994 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
995 ProtocolName);
Steve Naroff768f26e2007-10-02 20:26:23 +0000996 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000997 // Chain & install the protocol decl into the identifier.
998 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
999 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001000 }
1001
1002 /// Check then save referenced protocols
1003 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001004 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001005 ProtocolLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001006 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001007 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001008 ProtoRefNames[i]->getName(),
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001009 ProtocolName->getName());
1010 PDecl->setReferencedProtocols((int)i, RefPDecl);
1011 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001012
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001013 return PDecl;
1014}
1015
Fariborz Jahanian245f92a2007-10-05 21:01:53 +00001016/// ActOnFindProtocolDeclaration - This routine looks for a previously
1017/// declared protocol and returns it. If not found, issues diagnostic.
1018/// Will build a list of previously protocol declarations found in the list.
1019Action::DeclTy **
1020Sema::ActOnFindProtocolDeclaration(Scope *S,
1021 SourceLocation TypeLoc,
1022 IdentifierInfo **ProtocolId,
1023 unsigned NumProtocols) {
1024 for (unsigned i = 0; i != NumProtocols; ++i) {
1025 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolId[i],
1026 TypeLoc);
1027 if (!PDecl)
1028 Diag(TypeLoc, diag::err_undeclared_protocol,
1029 ProtocolId[i]->getName());
1030 }
1031 return 0;
1032}
1033
Steve Naroff37e58d12007-10-02 22:39:18 +00001034/// ActOnForwardProtocolDeclaration -
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001035/// Scope will always be top level file scope.
1036Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001037Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001038 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001039 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001040
1041 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001042 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, IdentList[i],
1043 AtProtocolLoc);
1044 if (!PDecl) { // Already seen?
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001045 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1046 // Chain & install the protocol decl into the identifier.
1047 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1048 IdentList[i]->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001049 }
1050 // Remember that this needs to be removed when the scope is popped.
1051 S->AddDecl(IdentList[i]);
1052
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001053 Protocols.push_back(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001054 }
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001055 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1056 &Protocols[0], Protocols.size());
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001057}
1058
Steve Naroff3a165b02007-10-03 21:00:46 +00001059Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001060 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001061 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1062 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1063 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1064 ObjcCategoryDecl *CDecl;
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001065 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian60199032007-10-02 17:36:55 +00001066 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001067 CDecl->setClassInterface(IDecl);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001068
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001069 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001070 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001071 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1072 else {
1073 /// Check for duplicate interface declaration for this category
1074 ObjcCategoryDecl *CDeclChain;
1075 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1076 CDeclChain = CDeclChain->getNextClassCategory()) {
1077 if (CDeclChain->getCatName() == CategoryName) {
1078 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1079 CategoryName->getName());
1080 break;
1081 }
1082 }
1083 if (!CDeclChain) {
1084 CDecl->setCatName(CategoryName);
1085 CDecl->insertNextClassCategory();
1086 }
1087 }
1088
1089 /// Check then save referenced protocols
1090 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001091 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001092 CategoryLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001093 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001094 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001095 ProtoRefNames[i]->getName(),
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001096 CategoryName->getName());
1097 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1098 }
1099
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001100 return CDecl;
1101}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001102
Steve Naroff3a165b02007-10-03 21:00:46 +00001103/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001104/// category implementation declaration and build an ObjcCategoryImplDecl
1105/// object.
Steve Naroff3a165b02007-10-03 21:00:46 +00001106Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001107 SourceLocation AtCatImplLoc,
1108 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1109 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001110 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001111 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
1112 ClassName, IDecl,
1113 CatName);
1114 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001115 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001116 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1117 /// TODO: Check that CatName, category name, is not used in another
1118 // implementation.
1119 return CDecl;
1120}
1121
Steve Naroff3a165b02007-10-03 21:00:46 +00001122Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001123 SourceLocation AtClassImplLoc,
1124 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1125 IdentifierInfo *SuperClassname,
1126 SourceLocation SuperClassLoc) {
1127 ObjcInterfaceDecl* IDecl = 0;
1128 // Check for another declaration kind with the same name.
1129 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1130 ClassLoc, S);
1131 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1132 Diag(ClassLoc, diag::err_redefinition_different_kind,
1133 ClassName->getName());
1134 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1135 }
1136 else {
1137 // Is there an interface declaration of this class; if not, warn!
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001138 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001139 if (!IDecl)
1140 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1141 }
1142
1143 // Check that super class name is valid class name
1144 ObjcInterfaceDecl* SDecl = 0;
1145 if (SuperClassname) {
1146 // Check if a different kind of symbol declared in this scope.
1147 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1148 SuperClassLoc, S);
1149 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1150 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1151 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1152 SuperClassname->getName());
1153 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1154 }
1155 else {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001156 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001157 if (!SDecl)
1158 Diag(SuperClassLoc, diag::err_undef_superclass,
1159 SuperClassname->getName(), ClassName->getName());
1160 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1161 // This implementation and its interface do not have the same
1162 // super class.
1163 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1164 SuperClassname->getName());
1165 Diag(SDecl->getLocation(), diag::err_previous_definition);
1166 }
1167 }
1168 }
1169
1170 ObjcImplementationDecl* IMPDecl =
1171 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001172 if (!IDecl) {
1173 // Legacy case of @implementation with no corresponding @interface.
1174 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001175 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001176 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1177 ClassName->setFETokenInfo(IDecl);
1178
1179 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001180
1181 // Check that there is no duplicate implementation of this class.
1182 bool err = false;
1183 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1184 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1185 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1186 err = true;
1187 break;
1188 }
1189 }
1190 if (!err)
1191 Context.setObjcImplementationClass(IMPDecl);
1192
1193 return IMPDecl;
1194}
1195
Steve Naroffa5997c42007-10-02 21:43:37 +00001196void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1197 ObjcIvarDecl **ivars, unsigned numIvars) {
1198 assert(ImpDecl && "missing implementation decl");
1199 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001200 /// 2nd check is added to accomodate case of non-existing @interface decl.
1201 /// (legacy objective-c @implementation decl without an @interface decl).
1202 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroffa5997c42007-10-02 21:43:37 +00001203 return;
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001204 assert(ivars && "missing @implementation ivars");
1205
Steve Naroffa5997c42007-10-02 21:43:37 +00001206 // Check interface's Ivar list against those in the implementation.
1207 // names and types must match.
1208 //
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001209 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1210 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1211 unsigned j = 0;
1212 bool err = false;
1213 while (numIvars > 0 && IntfNumIvars > 0) {
1214 ObjcIvarDecl* ImplIvar = ivars[j];
1215 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1216 assert (ImplIvar && "missing implementation ivar");
1217 assert (ClsIvar && "missing class ivar");
1218 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1219 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1220 ImplIvar->getIdentifier()->getName());
1221 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1222 ClsIvar->getIdentifier()->getName());
1223 }
1224 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1225 // as error.
1226 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1227 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1228 ImplIvar->getIdentifier()->getName());
1229 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1230 ClsIvar->getIdentifier()->getName());
1231 err = true;
1232 break;
1233 }
1234 --numIvars;
1235 --IntfNumIvars;
1236 }
1237 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1238 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1239 diag::err_inconsistant_ivar);
1240
1241}
1242
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001243/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1244/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001245void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001246 bool& IncompleteImpl,
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001247 const llvm::DenseSet<void *>& InsMap,
Chris Lattner85994262007-10-05 20:15:24 +00001248 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001249 // check unimplemented instance methods.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001250 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001251 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
1252 void * cpv = methods[j]->getSelector().getAsOpaquePtr();
1253 if (!InsMap.count(cpv)) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001254 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001255 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1256 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001257 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001258 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001259 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001260 // check unimplemented class methods
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001261 methods = PDecl->getClassMethods();
1262 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001263 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001264 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001265 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1266 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001267 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001268 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001269
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001270 // Check on this protocols's referenced protocols, recursively
1271 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1272 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001273 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001274}
1275
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001276void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1277 ObjcInterfaceDecl* IDecl) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001278 llvm::DenseSet<void *> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001279 // Check and see if instance methods in class interface have been
1280 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001281 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001282 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
1283 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001284
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001285 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001286 methods = IDecl->getInstanceMethods();
1287 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001288 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001289 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001290 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1291 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001292 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001293 }
Chris Lattner85994262007-10-05 20:15:24 +00001294 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001295 // Check and see if class methods in class interface have been
1296 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001297 methods = IMPDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001298 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001299 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001300
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001301 methods = IDecl->getClassMethods();
1302 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001303 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001304 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001305 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1306 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001307 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001308 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001309
1310 // Check the protocol list for unimplemented methods in the @implementation
1311 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001312 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner85994262007-10-05 20:15:24 +00001313 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1314 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1315
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001316 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001317 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1318 IMPDecl->getName());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001319}
1320
1321/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1322/// category interface is implemented in the category @implementation.
1323void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1324 ObjcCategoryDecl *CatClassDecl) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001325 llvm::DenseSet<void *> InsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001326 // Check and see if instance methods in category interface have been
1327 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001328 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001329 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
1330 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001331
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001332 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001333 methods = CatClassDecl->getInstanceMethods();
1334 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001335 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1336 llvm::SmallString<128> buf;
1337 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1338 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001339 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001340 }
Chris Lattner85994262007-10-05 20:15:24 +00001341 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001342 // Check and see if class methods in category interface have been
1343 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001344 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001345 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001346 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001347
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001348 methods = CatClassDecl->getClassMethods();
1349 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001350 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001351 llvm::SmallString<128> buf;
1352 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1353 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001354 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001355 }
1356
1357 // Check the protocol list for unimplemented methods in the @implementation
1358 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001359 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1360 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001361 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001362 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001363 }
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001364 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001365 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001366 CatClassDecl->getCatName()->getName());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001367}
1368
Steve Naroff37e58d12007-10-02 22:39:18 +00001369/// ActOnForwardClassDeclaration -
Steve Naroff3536b442007-09-06 21:24:23 +00001370/// Scope will always be top level file scope.
1371Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001372Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1373 IdentifierInfo **IdentList, unsigned NumElts)
1374{
Chris Lattner7e620722007-10-06 20:08:36 +00001375 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1376
Steve Naroff3536b442007-09-06 21:24:23 +00001377 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner7e620722007-10-06 20:08:36 +00001378 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(IdentList[i]);
1379 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001380 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001381 // Chain & install the interface decl into the identifier.
1382 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1383 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001384 }
Steve Naroff3536b442007-09-06 21:24:23 +00001385 // Remember that this needs to be removed when the scope is popped.
1386 S->AddDecl(IdentList[i]);
Chris Lattner7e620722007-10-06 20:08:36 +00001387
1388 Interfaces.push_back(IDecl);
Steve Naroff3536b442007-09-06 21:24:23 +00001389 }
Chris Lattner7e620722007-10-06 20:08:36 +00001390
1391 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff3536b442007-09-06 21:24:23 +00001392}
1393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394
Steve Naroff08d92e42007-09-15 18:49:24 +00001395/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001396/// former case, Name will be non-null. In the later case, Name will be null.
1397/// TagType indicates what kind of tag this is. TK indicates whether this is a
1398/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001399Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 SourceLocation KWLoc, IdentifierInfo *Name,
1401 SourceLocation NameLoc, AttributeList *Attr) {
1402 // If this is a use of an existing tag, it must have a name.
1403 assert((Name != 0 || TK == TK_Definition) &&
1404 "Nameless record must be a definition!");
1405
1406 Decl::Kind Kind;
1407 switch (TagType) {
1408 default: assert(0 && "Unknown tag type!");
1409 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1410 case DeclSpec::TST_union: Kind = Decl::Union; break;
1411//case DeclSpec::TST_class: Kind = Decl::Class; break;
1412 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1413 }
1414
1415 // If this is a named struct, check to see if there was a previous forward
1416 // declaration or definition.
1417 if (TagDecl *PrevDecl =
1418 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1419 NameLoc, S))) {
1420
1421 // If this is a use of a previous tag, or if the tag is already declared in
1422 // the same scope (so that the definition/declaration completes or
1423 // rementions the tag), reuse the decl.
1424 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1425 // Make sure that this wasn't declared as an enum and now used as a struct
1426 // or something similar.
1427 if (PrevDecl->getKind() != Kind) {
1428 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1429 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1430 }
1431
1432 // If this is a use or a forward declaration, we're good.
1433 if (TK != TK_Definition)
1434 return PrevDecl;
1435
1436 // Diagnose attempts to redefine a tag.
1437 if (PrevDecl->isDefinition()) {
1438 Diag(NameLoc, diag::err_redefinition, Name->getName());
1439 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1440 // If this is a redefinition, recover by making this struct be
1441 // anonymous, which will make any later references get the previous
1442 // definition.
1443 Name = 0;
1444 } else {
1445 // Okay, this is definition of a previously declared or referenced tag.
1446 // Move the location of the decl to be the definition site.
1447 PrevDecl->setLocation(NameLoc);
1448 return PrevDecl;
1449 }
1450 }
1451 // If we get here, this is a definition of a new struct type in a nested
1452 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1453 // type.
1454 }
1455
1456 // If there is an identifier, use the location of the identifier as the
1457 // location of the decl, otherwise use the location of the struct/union
1458 // keyword.
1459 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1460
1461 // Otherwise, if this is the first time we've seen this tag, create the decl.
1462 TagDecl *New;
1463 switch (Kind) {
1464 default: assert(0 && "Unknown tag kind!");
1465 case Decl::Enum:
1466 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1467 // enum X { A, B, C } D; D should chain to X.
1468 New = new EnumDecl(Loc, Name, 0);
1469 // If this is an undefined enum, warn.
1470 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1471 break;
1472 case Decl::Union:
1473 case Decl::Struct:
1474 case Decl::Class:
1475 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1476 // struct X { int A; } D; D should chain to X.
1477 New = new RecordDecl(Kind, Loc, Name, 0);
1478 break;
1479 }
1480
1481 // If this has an identifier, add it to the scope stack.
1482 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001483 // The scope passed in may not be a decl scope. Zip up the scope tree until
1484 // we find one that is.
1485 while ((S->getFlags() & Scope::DeclScope) == 0)
1486 S = S->getParent();
1487
1488 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001489 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 Name->setFETokenInfo(New);
1491 S->AddDecl(New);
1492 }
1493
1494 return New;
1495}
1496
Steve Naroff08d92e42007-09-15 18:49:24 +00001497/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001498/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001499Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001500 SourceLocation DeclStart,
1501 Declarator &D, ExprTy *BitfieldWidth) {
1502 IdentifierInfo *II = D.getIdentifier();
1503 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 SourceLocation Loc = DeclStart;
1505 if (II) Loc = D.getIdentifierLoc();
1506
1507 // FIXME: Unnamed fields can be handled in various different ways, for
1508 // example, unnamed unions inject all members into the struct namespace!
1509
1510
1511 if (BitWidth) {
1512 // TODO: Validate.
1513 //printf("WARNING: BITFIELDS IGNORED!\n");
1514
1515 // 6.7.2.1p3
1516 // 6.7.2.1p4
1517
1518 } else {
1519 // Not a bitfield.
1520
1521 // validate II.
1522
1523 }
1524
1525 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001526 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1527 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001528
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1530 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001531 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1532 Diag(Loc, diag::err_typecheck_illegal_vla,
1533 VAT->getSizeExpr()->getSourceRange());
1534 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001537 FieldDecl *NewFD;
1538
1539 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001540 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001541 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001542 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001543 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001544 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001545 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001546
Steve Naroff5912a352007-08-28 20:14:24 +00001547 if (D.getInvalidType() || InvalidDecl)
1548 NewFD->setInvalidDecl();
1549 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001550}
1551
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001552/// TranslateIvarVisibility - Translate visibility from a token ID to an
1553/// AST enum value.
1554static ObjcIvarDecl::AccessControl
1555TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001556 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001557 case tok::objc_private: return ObjcIvarDecl::Private;
1558 case tok::objc_public: return ObjcIvarDecl::Public;
1559 case tok::objc_protected: return ObjcIvarDecl::Protected;
1560 case tok::objc_package: return ObjcIvarDecl::Package;
1561 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001562 }
1563}
1564
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001565void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001566 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001567 DeclTy **Fields, unsigned NumFields,
1568 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001569 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1570 assert(EnclosingDecl && "missing record or interface decl");
1571 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1572
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001573 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 // Diagnose code like:
1575 // struct S { struct S {} X; };
1576 // We discover this when we complete the outer S. Reject and ignore the
1577 // outer S.
1578 Diag(Record->getLocation(), diag::err_nested_redefinition,
1579 Record->getKindName());
1580 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001581 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 return;
1583 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 // Verify that all the fields are okay.
1585 unsigned NumNamedMembers = 0;
1586 llvm::SmallVector<FieldDecl*, 32> RecFields;
1587 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001588
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001590
Steve Naroff74216642007-09-14 22:20:54 +00001591 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1592 assert(FD && "missing field decl");
1593
1594 // Remember all fields.
1595 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001596
1597 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001598 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001599
Steve Narofff13271f2007-09-14 23:09:53 +00001600 // If we have visibility info, make sure the AST is set accordingly.
1601 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001602 cast<ObjcIvarDecl>(FD)->setAccessControl(
1603 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001604
Reid Spencer5f016e22007-07-11 17:01:13 +00001605 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001606 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001607 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001608 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001609 FD->setInvalidDecl();
1610 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 continue;
1612 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1614 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001615 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001616 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001617 FD->setInvalidDecl();
1618 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001619 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001620 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 if (i != NumFields-1 || // ... that the last member ...
1622 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001623 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001625 FD->setInvalidDecl();
1626 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001627 continue;
1628 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001629 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1631 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001632 FD->setInvalidDecl();
1633 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 continue;
1635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001636 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001637 if (Record)
1638 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1641 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001642 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1644 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001645 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001646 Record->setHasFlexibleArrayMember(true);
1647 } else {
1648 // If this is a struct/class and this is not the last element, reject
1649 // it. Note that GCC supports variable sized arrays in the middle of
1650 // structures.
1651 if (i != NumFields-1) {
1652 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1653 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001654 FD->setInvalidDecl();
1655 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001656 continue;
1657 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // We support flexible arrays at the end of structs in other structs
1659 // as an extension.
1660 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1661 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001662 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001663 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 }
1665 }
1666 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 // Keep track of the number of named members.
1668 if (IdentifierInfo *II = FD->getIdentifier()) {
1669 // Detect duplicate member names.
1670 if (!FieldIDs.insert(II)) {
1671 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1672 // Find the previous decl.
1673 SourceLocation PrevLoc;
1674 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1675 assert(i != e && "Didn't find previous def!");
1676 if (RecFields[i]->getIdentifier() == II) {
1677 PrevLoc = RecFields[i]->getLocation();
1678 break;
1679 }
1680 }
1681 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001682 FD->setInvalidDecl();
1683 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 continue;
1685 }
1686 ++NumNamedMembers;
1687 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 }
1689
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001691 if (Record)
1692 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001693 else {
1694 ObjcIvarDecl **ClsFields =
1695 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001696 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1697 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1698 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1699 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1700 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001701 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001702 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1703 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroffa5997c42007-10-02 21:43:37 +00001704 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001705 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001706 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001707}
1708
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001709/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1710/// returns true, or false, accordingly.
1711/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1712bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1713 const ObjcMethodDecl *PrevMethod) {
1714 if (Method->getMethodType().getCanonicalType() !=
1715 PrevMethod->getMethodType().getCanonicalType())
1716 return false;
1717 for (int i = 0; i < Method->getNumParams(); i++) {
1718 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1719 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1720 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1721 return false;
1722 }
1723 return true;
1724}
1725
Steve Naroff3a165b02007-10-03 21:00:46 +00001726void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *ClassDecl,
1727 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001728 // FIXME: Fix this when we can handle methods declared in protocols.
1729 // See Parser::ParseObjCAtProtocolDeclaration
1730 if (!ClassDecl)
1731 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001732 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1733 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001734
1735 llvm::DenseMap<void *, const ObjcMethodDecl*> InsMap;
1736 llvm::DenseMap<void *, const ObjcMethodDecl*> ClsMap;
1737
1738 bool isClassDeclaration =
1739 (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))
1740 || isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl)));
1741
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001742 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001743 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001744 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1745 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001746 if (Method->isInstance()) {
1747 if (isClassDeclaration) {
1748 /// Check for instance method of the same name with incompatible types
1749 const ObjcMethodDecl *&PrevMethod =
1750 InsMap[Method->getSelector().getAsOpaquePtr()];
1751 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1752 llvm::SmallString<128> buf;
1753 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1754 Method->getSelector().getName(buf));
1755 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1756 }
1757 else {
1758 insMethods.push_back(Method);
1759 InsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1760 }
1761 }
1762 else
1763 insMethods.push_back(Method);
1764 }
1765 else {
1766 if (isClassDeclaration) {
1767 /// Check for class method of the same name with incompatible types
1768 const ObjcMethodDecl *&PrevMethod =
1769 ClsMap[Method->getSelector().getAsOpaquePtr()];
1770 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1771 llvm::SmallString<128> buf;
1772 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1773 Method->getSelector().getName(buf));
1774 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1775 }
1776 else {
1777 clsMethods.push_back(Method);
1778 ClsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1779 }
1780 }
1781 else
1782 clsMethods.push_back(Method);
1783 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001784 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001785 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1786 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1787 static_cast<Decl*>(ClassDecl));
1788 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1789 &clsMethods[0], clsMethods.size());
1790 }
1791 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1792 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1793 static_cast<Decl*>(ClassDecl));
1794 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1795 &clsMethods[0], clsMethods.size());
1796 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001797 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1798 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1799 static_cast<Decl*>(ClassDecl));
1800 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1801 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001802 }
1803 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1804 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1805 static_cast<Decl*>(ClassDecl));
1806 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1807 &clsMethods[0], clsMethods.size());
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001808 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImplClass->getIdentifier());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001809 if (IDecl)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001810 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001811 }
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001812 else {
1813 ObjcCategoryImplDecl* CatImplClass = dyn_cast<ObjcCategoryImplDecl>(
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001814 static_cast<Decl*>(ClassDecl));
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001815 if (CatImplClass) {
1816 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1817 &clsMethods[0], clsMethods.size());
1818 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1819 // Find category interface decl and then check that all methods declared
1820 // in this interface is implemented in the category @implementation.
1821 if (IDecl) {
1822 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1823 Categories; Categories = Categories->getNextClassCategory()) {
1824 if (Categories->getCatName() == CatImplClass->getObjcCatName()) {
1825 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1826 break;
1827 }
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001828 }
1829 }
1830 }
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001831 else
1832 assert(0 && "Sema::ActOnAddMethodsToObjcDecl(): Unknown DeclTy");
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001833 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001834}
1835
Steve Naroff37e58d12007-10-02 22:39:18 +00001836Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001837 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001838 // optional arguments. The number of types/arguments is obtained
1839 // from the Sel.getNumArgs().
1840 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1841 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001842 llvm::SmallVector<ParmVarDecl*, 16> Params;
1843
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001844 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001845 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001846 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001847 QualType::getFromOpaquePtr(ArgTypes[i]),
1848 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001849 Params.push_back(Param);
1850 }
1851 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001852 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1853 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001854 MethodType == tok::minus,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001855 MethodDeclKind == tok::objc_optional ?
1856 ObjcMethodDecl::Optional :
1857 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001858 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001859 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001860}
1861
Steve Naroff08d92e42007-09-15 18:49:24 +00001862Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 DeclTy *lastEnumConst,
1864 SourceLocation IdLoc, IdentifierInfo *Id,
1865 SourceLocation EqualLoc, ExprTy *val) {
1866 theEnumDecl = theEnumDecl; // silence unused warning.
1867 EnumConstantDecl *LastEnumConst =
1868 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1869 Expr *Val = static_cast<Expr*>(val);
1870
Chris Lattner31e05722007-08-26 06:24:45 +00001871 // The scope passed in may not be a decl scope. Zip up the scope tree until
1872 // we find one that is.
1873 while ((S->getFlags() & Scope::DeclScope) == 0)
1874 S = S->getParent();
1875
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 // Verify that there isn't already something declared with this name in this
1877 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001878 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1879 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 if (S->isDeclScope(PrevDecl)) {
1881 if (isa<EnumConstantDecl>(PrevDecl))
1882 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1883 else
1884 Diag(IdLoc, diag::err_redefinition, Id->getName());
1885 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1886 // FIXME: Don't leak memory: delete Val;
1887 return 0;
1888 }
1889 }
1890
1891 llvm::APSInt EnumVal(32);
1892 QualType EltTy;
1893 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001894 // Make sure to promote the operand type to int.
1895 UsualUnaryConversions(Val);
1896
Reid Spencer5f016e22007-07-11 17:01:13 +00001897 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1898 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001899 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1901 Id->getName());
1902 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001903 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001904 } else {
1905 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001906 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001907 }
1908
1909 if (!Val) {
1910 if (LastEnumConst) {
1911 // Assign the last value + 1.
1912 EnumVal = LastEnumConst->getInitVal();
1913 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001914
1915 // Check for overflow on increment.
1916 if (EnumVal < LastEnumConst->getInitVal())
1917 Diag(IdLoc, diag::warn_enum_value_overflow);
1918
Chris Lattnerb7416f92007-08-27 17:37:24 +00001919 EltTy = LastEnumConst->getType();
1920 } else {
1921 // First value, set to zero.
1922 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001923 EnumVal.zextOrTrunc(
1924 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001925 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 }
1927
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1929 LastEnumConst);
1930
1931 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001932 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 Id->setFETokenInfo(New);
1934 S->AddDecl(New);
1935 return New;
1936}
1937
Steve Naroff08d92e42007-09-15 18:49:24 +00001938void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 DeclTy **Elements, unsigned NumElements) {
1940 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1941 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1942
Chris Lattnere37f0be2007-08-28 05:10:31 +00001943 // TODO: If the result value doesn't fit in an int, it must be a long or long
1944 // long value. ISO C does not support this, but GCC does as an extension,
1945 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001946 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001947
1948
Chris Lattnerac609682007-08-28 06:15:15 +00001949 // Verify that all the values are okay, compute the size of the values, and
1950 // reverse the list.
1951 unsigned NumNegativeBits = 0;
1952 unsigned NumPositiveBits = 0;
1953
1954 // Keep track of whether all elements have type int.
1955 bool AllElementsInt = true;
1956
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 EnumConstantDecl *EltList = 0;
1958 for (unsigned i = 0; i != NumElements; ++i) {
1959 EnumConstantDecl *ECD =
1960 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1961 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001962
1963 // If the enum value doesn't fit in an int, emit an extension warning.
1964 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1965 "Should have promoted value to int");
1966 const llvm::APSInt &InitVal = ECD->getInitVal();
1967 if (InitVal.getBitWidth() > IntWidth) {
1968 llvm::APSInt V(InitVal);
1969 V.trunc(IntWidth);
1970 V.extend(InitVal.getBitWidth());
1971 if (V != InitVal)
1972 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1973 InitVal.toString());
1974 }
Chris Lattnerac609682007-08-28 06:15:15 +00001975
1976 // Keep track of the size of positive and negative values.
1977 if (InitVal.isUnsigned() || !InitVal.isNegative())
1978 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1979 else
1980 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001981
Chris Lattnerac609682007-08-28 06:15:15 +00001982 // Keep track of whether every enum element has type int (very commmon).
1983 if (AllElementsInt)
1984 AllElementsInt = ECD->getType() == Context.IntTy;
1985
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 ECD->setNextDeclarator(EltList);
1987 EltList = ECD;
1988 }
1989
Chris Lattnerac609682007-08-28 06:15:15 +00001990 // Figure out the type that should be used for this enum.
1991 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1992 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001993 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001994
1995 if (NumNegativeBits) {
1996 // If there is a negative value, figure out the smallest integer type (of
1997 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001998 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001999 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002000 BestWidth = IntWidth;
2001 } else {
2002 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
2003 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002004 BestType = Context.LongTy;
2005 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002006 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
2007 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002008 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2009 BestType = Context.LongLongTy;
2010 }
2011 }
2012 } else {
2013 // If there is no negative value, figure out which of uint, ulong, ulonglong
2014 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002015 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002016 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002017 BestWidth = IntWidth;
2018 } else if (NumPositiveBits <=
2019 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00002020 BestType = Context.UnsignedLongTy;
2021 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002022 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
2023 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002024 "How could an initializer get larger than ULL?");
2025 BestType = Context.UnsignedLongLongTy;
2026 }
2027 }
2028
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002029 // Loop over all of the enumerator constants, changing their types to match
2030 // the type of the enum if needed.
2031 for (unsigned i = 0; i != NumElements; ++i) {
2032 EnumConstantDecl *ECD =
2033 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2034 if (!ECD) continue; // Already issued a diagnostic.
2035
2036 // Standard C says the enumerators have int type, but we allow, as an
2037 // extension, the enumerators to be larger than int size. If each
2038 // enumerator value fits in an int, type it as an int, otherwise type it the
2039 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2040 // that X has type 'int', not 'unsigned'.
2041 if (ECD->getType() == Context.IntTy)
2042 continue; // Already int type.
2043
2044 // Determine whether the value fits into an int.
2045 llvm::APSInt InitVal = ECD->getInitVal();
2046 bool FitsInInt;
2047 if (InitVal.isUnsigned() || !InitVal.isNegative())
2048 FitsInInt = InitVal.getActiveBits() < IntWidth;
2049 else
2050 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2051
2052 // If it fits into an integer type, force it. Otherwise force it to match
2053 // the enum decl type.
2054 QualType NewTy;
2055 unsigned NewWidth;
2056 bool NewSign;
2057 if (FitsInInt) {
2058 NewTy = Context.IntTy;
2059 NewWidth = IntWidth;
2060 NewSign = true;
2061 } else if (ECD->getType() == BestType) {
2062 // Already the right type!
2063 continue;
2064 } else {
2065 NewTy = BestType;
2066 NewWidth = BestWidth;
2067 NewSign = BestType->isSignedIntegerType();
2068 }
2069
2070 // Adjust the APSInt value.
2071 InitVal.extOrTrunc(NewWidth);
2072 InitVal.setIsSigned(NewSign);
2073 ECD->setInitVal(InitVal);
2074
2075 // Adjust the Expr initializer and type.
2076 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2077 ECD->setType(NewTy);
2078 }
Chris Lattnerac609682007-08-28 06:15:15 +00002079
Chris Lattnere00b18c2007-08-28 18:24:31 +00002080 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00002081}
2082
2083void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2084 if (!current) return;
2085
2086 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2087 // remember this in the LastInGroupList list.
2088 if (last)
2089 LastInGroupList.push_back((Decl*)last);
2090}
2091
2092void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2093 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2094 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2095 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2096 if (!newType.isNull()) // install the new vector type into the decl
2097 vDecl->setType(newType);
2098 }
2099 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2100 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2101 rawAttr);
2102 if (!newType.isNull()) // install the new vector type into the decl
2103 tDecl->setUnderlyingType(newType);
2104 }
2105 }
Steve Naroff73322922007-07-18 18:00:27 +00002106 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002107 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2108 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2109 else
Steve Naroff73322922007-07-18 18:00:27 +00002110 Diag(rawAttr->getAttributeLoc(),
2111 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002112 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002113 // FIXME: add other attributes...
2114}
2115
2116void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2117 AttributeList *declarator_postfix) {
2118 while (declspec_prefix) {
2119 HandleDeclAttribute(New, declspec_prefix);
2120 declspec_prefix = declspec_prefix->getNext();
2121 }
2122 while (declarator_postfix) {
2123 HandleDeclAttribute(New, declarator_postfix);
2124 declarator_postfix = declarator_postfix->getNext();
2125 }
2126}
2127
Steve Naroffbea0b342007-07-29 16:33:31 +00002128void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2129 AttributeList *rawAttr) {
2130 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002131 // check the attribute arugments.
2132 if (rawAttr->getNumArgs() != 1) {
2133 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2134 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002135 return;
Steve Naroff73322922007-07-18 18:00:27 +00002136 }
2137 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2138 llvm::APSInt vecSize(32);
2139 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2140 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2141 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002142 return;
Steve Naroff73322922007-07-18 18:00:27 +00002143 }
2144 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2145 // in conjunction with complex types (pointers, arrays, functions, etc.).
2146 Type *canonType = curType.getCanonicalType().getTypePtr();
2147 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2148 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2149 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002150 return;
Steve Naroff73322922007-07-18 18:00:27 +00002151 }
2152 // unlike gcc's vector_size attribute, the size is specified as the
2153 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002154 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002155
2156 if (vectorSize == 0) {
2157 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2158 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002159 return;
Steve Naroff73322922007-07-18 18:00:27 +00002160 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002161 // Instantiate/Install the vector type, the number of elements is > 0.
2162 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2163 // Remember this typedef decl, we will need it later for diagnostics.
2164 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002165}
2166
Reid Spencer5f016e22007-07-11 17:01:13 +00002167QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002168 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 // check the attribute arugments.
2170 if (rawAttr->getNumArgs() != 1) {
2171 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2172 std::string("1"));
2173 return QualType();
2174 }
2175 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2176 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002177 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002178 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2179 sizeExpr->getSourceRange());
2180 return QualType();
2181 }
2182 // navigate to the base type - we need to provide for vector pointers,
2183 // vector arrays, and functions returning vectors.
2184 Type *canonType = curType.getCanonicalType().getTypePtr();
2185
Steve Naroff73322922007-07-18 18:00:27 +00002186 if (canonType->isPointerType() || canonType->isArrayType() ||
2187 canonType->isFunctionType()) {
2188 assert(1 && "HandleVector(): Complex type construction unimplemented");
2189 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2190 do {
2191 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2192 canonType = PT->getPointeeType().getTypePtr();
2193 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2194 canonType = AT->getElementType().getTypePtr();
2195 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2196 canonType = FT->getResultType().getTypePtr();
2197 } while (canonType->isPointerType() || canonType->isArrayType() ||
2198 canonType->isFunctionType());
2199 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002200 }
2201 // the base type must be integer or float.
2202 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2203 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2204 curType.getCanonicalType().getAsString());
2205 return QualType();
2206 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002207 unsigned typeSize = static_cast<unsigned>(
2208 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002210 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002211
2212 // the vector size needs to be an integral multiple of the type size.
2213 if (vectorSize % typeSize) {
2214 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2215 sizeExpr->getSourceRange());
2216 return QualType();
2217 }
2218 if (vectorSize == 0) {
2219 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2220 sizeExpr->getSourceRange());
2221 return QualType();
2222 }
2223 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2224 // the number of elements to be a power of two (unlike GCC).
2225 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002226 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002227}
2228