blob: 4fc6f78fbed242cbffc73eb350a05e2b156a020c [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff3fafa102007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroffc39ca262007-09-18 23:55:05 +000025#include "llvm/ADT/SmallString.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian67907bd2007-10-05 18:00:57 +000027#include "llvm/ADT/DenseSet.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29
Chris Lattner4b009652007-07-25 00:24:17 +000030Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner3c9e4da2007-09-30 08:31:00 +000031 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
32 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
33 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000034 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000035}
36
Steve Naroff9637a9b2007-10-09 22:01:59 +000037void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +000038 if (S->decl_empty()) return;
39 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
40
Chris Lattner4b009652007-07-25 00:24:17 +000041 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
42 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +000043 Decl *TmpD = static_cast<Decl*>(*I);
44 assert(TmpD && "This decl didn't get pushed??");
45 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
46 assert(D && "This decl isn't a ScopedDecl?");
47
Chris Lattner4b009652007-07-25 00:24:17 +000048 IdentifierInfo *II = D->getIdentifier();
49 if (!II) continue;
50
51 // Unlink this decl from the identifier. Because the scope contains decls
52 // in an unordered collection, and because we have multiple identifier
53 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
54 if (II->getFETokenInfo<Decl>() == D) {
55 // Normal case, no multiple decls in different namespaces.
56 II->setFETokenInfo(D->getNext());
57 } else {
58 // Scan ahead. There are only three namespaces in C, so this loop can
59 // never execute more than 3 times.
Steve Naroffd21bc0d2007-09-13 18:10:37 +000060 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Chris Lattner4b009652007-07-25 00:24:17 +000061 while (SomeDecl->getNext() != D) {
62 SomeDecl = SomeDecl->getNext();
63 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
64 }
65 SomeDecl->setNext(D->getNext());
66 }
67
68 // This will have to be revisited for C++: there we want to nest stuff in
69 // namespace decls etc. Even for C, we might want a top-level translation
70 // unit decl or something.
71 if (!CurFunctionDecl)
72 continue;
73
74 // Chain this decl to the containing function, it now owns the memory for
75 // the decl.
76 D->setNext(CurFunctionDecl->getDeclChain());
77 CurFunctionDecl->setDeclChain(D);
78 }
79}
80
Fariborz Jahaniandd243ef2007-09-29 17:04:06 +000081/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +000082/// return 0 if one not found.
Steve Narofffa465d12007-10-02 20:01:56 +000083ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
84
85 // Scan up the scope chain looking for a decl that matches this identifier
86 // that is in the appropriate namespace. This search should not take long, as
87 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
88 ScopedDecl *IdDecl = NULL;
89 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
90 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
91 IdDecl = D;
92 break;
93 }
94 }
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +000095 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
96 IdDecl = 0;
97 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
98}
99
Chris Lattner4b009652007-07-25 00:24:17 +0000100/// LookupScopedDecl - Look up the inner-most declaration in the specified
101/// namespace.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000102ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
103 SourceLocation IdLoc, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000104 if (II == 0) return 0;
105 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
106
107 // Scan up the scope chain looking for a decl that matches this identifier
108 // that is in the appropriate namespace. This search should not take long, as
109 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000110 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Chris Lattner4b009652007-07-25 00:24:17 +0000111 if (D->getIdentifierNamespace() == NS)
112 return D;
113
114 // If we didn't find a use of this identifier, and if the identifier
115 // corresponds to a compiler builtin, create the decl object for the builtin
116 // now, injecting it into translation unit scope, and return it.
117 if (NS == Decl::IDNS_Ordinary) {
118 // If this is a builtin on some other target, or if this builtin varies
119 // across targets (e.g. in type), emit a diagnostic and mark the translation
120 // unit non-portable for using it.
121 if (II->isNonPortableBuiltin()) {
122 // Only emit this diagnostic once for this builtin.
123 II->setNonPortableBuiltin(false);
124 Context.Target.DiagnoseNonPortability(IdLoc,
125 diag::port_target_builtin_use);
126 }
127 // If this is a builtin on this (or all) targets, create the decl.
128 if (unsigned BuiltinID = II->getBuiltinID())
129 return LazilyCreateBuiltin(II, BuiltinID, S);
130 }
131 return 0;
132}
133
134/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
135/// lazily create a decl for it.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000136ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000137 Builtin::ID BID = (Builtin::ID)bid;
138
139 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
140 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner987058a2007-08-26 04:02:13 +0000141 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000142
143 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000144 if (Scope *FnS = S->getFnParent())
145 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000146 while (S->getParent())
147 S = S->getParent();
148 S->AddDecl(New);
149
150 // Add this decl to the end of the identifier info.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000151 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000152 // Scan until we find the last (outermost) decl in the id chain.
153 while (LastDecl->getNext())
154 LastDecl = LastDecl->getNext();
155 // Insert before (outside) it.
156 LastDecl->setNext(New);
157 } else {
158 II->setFETokenInfo(New);
159 }
160 // Make sure clients iterating over decls see this.
161 LastInGroupList.push_back(New);
162
163 return New;
164}
165
166/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
167/// and scope as a previous declaration 'Old'. Figure out how to resolve this
168/// situation, merging decls or emitting diagnostics as appropriate.
169///
Steve Naroffcb597472007-09-13 21:41:19 +0000170TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000171 // Verify the old decl was also a typedef.
172 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
173 if (!Old) {
174 Diag(New->getLocation(), diag::err_redefinition_different_kind,
175 New->getName());
176 Diag(OldD->getLocation(), diag::err_previous_definition);
177 return New;
178 }
179
180 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
181 // TODO: This is totally simplistic. It should handle merging functions
182 // together etc, merging extern int X; int X; ...
183 Diag(New->getLocation(), diag::err_redefinition, New->getName());
184 Diag(Old->getLocation(), diag::err_previous_definition);
185 return New;
186}
187
188/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
189/// and scope as a previous declaration 'Old'. Figure out how to resolve this
190/// situation, merging decls or emitting diagnostics as appropriate.
191///
Steve Naroffcb597472007-09-13 21:41:19 +0000192FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000193 // Verify the old decl was also a function.
194 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
195 if (!Old) {
196 Diag(New->getLocation(), diag::err_redefinition_different_kind,
197 New->getName());
198 Diag(OldD->getLocation(), diag::err_previous_definition);
199 return New;
200 }
201
202 // This is not right, but it's a start. If 'Old' is a function prototype with
203 // the same type as 'New', silently allow this. FIXME: We should link up decl
204 // objects here.
205 if (Old->getBody() == 0 &&
206 Old->getCanonicalType() == New->getCanonicalType()) {
207 return New;
208 }
209
210 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
211 // TODO: This is totally simplistic. It should handle merging functions
212 // together etc, merging extern int X; int X; ...
213 Diag(New->getLocation(), diag::err_redefinition, New->getName());
214 Diag(Old->getLocation(), diag::err_previous_definition);
215 return New;
216}
217
218/// MergeVarDecl - We just parsed a variable 'New' which has the same name
219/// and scope as a previous declaration 'Old'. Figure out how to resolve this
220/// situation, merging decls or emitting diagnostics as appropriate.
221///
222/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
223/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
224///
Steve Naroffcb597472007-09-13 21:41:19 +0000225VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000226 // Verify the old decl was also a variable.
227 VarDecl *Old = dyn_cast<VarDecl>(OldD);
228 if (!Old) {
229 Diag(New->getLocation(), diag::err_redefinition_different_kind,
230 New->getName());
231 Diag(OldD->getLocation(), diag::err_previous_definition);
232 return New;
233 }
Steve Naroff83c13012007-08-30 01:06:46 +0000234 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
235 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
236 bool OldIsTentative = false;
237
238 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
239 // Handle C "tentative" external object definitions. FIXME: finish!
240 if (!OldFSDecl->getInit() &&
241 (OldFSDecl->getStorageClass() == VarDecl::None ||
242 OldFSDecl->getStorageClass() == VarDecl::Static))
243 OldIsTentative = true;
244 }
Chris Lattner4b009652007-07-25 00:24:17 +0000245 // Verify the types match.
246 if (Old->getCanonicalType() != New->getCanonicalType()) {
247 Diag(New->getLocation(), diag::err_redefinition, New->getName());
248 Diag(Old->getLocation(), diag::err_previous_definition);
249 return New;
250 }
251 // We've verified the types match, now check if Old is "extern".
252 if (Old->getStorageClass() != VarDecl::Extern) {
253 Diag(New->getLocation(), diag::err_redefinition, New->getName());
254 Diag(Old->getLocation(), diag::err_previous_definition);
255 }
256 return New;
257}
258
259/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
260/// no declarator (e.g. "struct foo;") is parsed.
261Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
262 // TODO: emit error on 'int;' or 'const enum foo;'.
263 // TODO: emit error on 'typedef int;'
264 // if (!DS.isMissingDeclaratorOk()) Diag(...);
265
266 return 0;
267}
268
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000269bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000270 AssignmentCheckResult result;
271 SourceLocation loc = Init->getLocStart();
272 // Get the type before calling CheckSingleAssignmentConstraints(), since
273 // it can promote the expression.
274 QualType rhsType = Init->getType();
275
276 result = CheckSingleAssignmentConstraints(DeclType, Init);
277
278 // decode the result (notice that extensions still return a type).
279 switch (result) {
280 case Compatible:
281 break;
282 case Incompatible:
Steve Naroff9091f3f2007-09-02 15:34:30 +0000283 // FIXME: tighten up this check which should allow:
284 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
285 if (rhsType == Context.getPointerType(Context.CharTy))
286 break;
Steve Naroffe14e5542007-09-02 02:04:30 +0000287 Diag(loc, diag::err_typecheck_assign_incompatible,
288 DeclType.getAsString(), rhsType.getAsString(),
289 Init->getSourceRange());
290 return true;
291 case PointerFromInt:
292 // check for null pointer constant (C99 6.3.2.3p3)
293 if (!Init->isNullPointerConstant(Context)) {
294 Diag(loc, diag::ext_typecheck_assign_pointer_int,
295 DeclType.getAsString(), rhsType.getAsString(),
296 Init->getSourceRange());
297 return true;
298 }
299 break;
300 case IntFromPointer:
301 Diag(loc, diag::ext_typecheck_assign_pointer_int,
302 DeclType.getAsString(), rhsType.getAsString(),
303 Init->getSourceRange());
304 break;
305 case IncompatiblePointer:
306 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
307 DeclType.getAsString(), rhsType.getAsString(),
308 Init->getSourceRange());
309 break;
310 case CompatiblePointerDiscardsQualifiers:
311 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
312 DeclType.getAsString(), rhsType.getAsString(),
313 Init->getSourceRange());
314 break;
315 }
316 return false;
317}
318
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000319bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
320 bool isStatic, QualType ElementType) {
Steve Naroff509d0b52007-09-04 02:20:04 +0000321 SourceLocation loc;
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000322 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff509d0b52007-09-04 02:20:04 +0000323
324 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
325 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
326 return true;
327 } else if (CheckSingleInitializer(expr, ElementType)) {
328 return true; // types weren't compatible.
329 }
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000330 if (savExpr != expr) // The type was promoted, update initializer list.
331 IList->setInit(slot, expr);
Steve Naroff509d0b52007-09-04 02:20:04 +0000332 return false;
333}
334
335void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
336 QualType ElementType, bool isStatic,
337 int &nInitializers, bool &hadError) {
Steve Naroff9091f3f2007-09-02 15:34:30 +0000338 for (unsigned i = 0; i < IList->getNumInits(); i++) {
339 Expr *expr = IList->getInit(i);
340
Steve Naroff509d0b52007-09-04 02:20:04 +0000341 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
342 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000343 int maxElements = CAT->getMaximumElements();
Steve Naroff509d0b52007-09-04 02:20:04 +0000344 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
345 maxElements, hadError);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000346 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000347 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000348 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff9091f3f2007-09-02 15:34:30 +0000349 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000350 nInitializers++;
351 }
352 return;
353}
354
355// FIXME: Doesn't deal with arrays of structures yet.
356void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
357 QualType ElementType, bool isStatic,
358 int &totalInits, bool &hadError) {
359 int maxElementsAtThisLevel = 0;
360 int nInitsAtLevel = 0;
361
362 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
363 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff4f910992007-09-04 21:13:33 +0000364 maxElementsAtThisLevel = CAT->getMaximumElements();
365 // Set DeclType, used below to recurse (for multi-dimensional arrays).
366 DeclType = CAT->getElementType();
Steve Naroff509d0b52007-09-04 02:20:04 +0000367 } else if (DeclType->isScalarType()) {
368 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
369 IList->getSourceRange());
370 maxElementsAtThisLevel = 1;
371 }
372 // The empty init list "{ }" is treated specially below.
373 unsigned numInits = IList->getNumInits();
374 if (numInits) {
375 for (unsigned i = 0; i < numInits; i++) {
376 Expr *expr = IList->getInit(i);
377
378 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
379 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
380 totalInits, hadError);
381 } else {
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000382 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff509d0b52007-09-04 02:20:04 +0000383 nInitsAtLevel++; // increment the number of initializers at this level.
384 totalInits--; // decrement the total number of initializers.
385
386 // Check if we have space for another initializer.
387 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
388 Diag(expr->getLocStart(), diag::warn_excess_initializers,
389 expr->getSourceRange());
390 }
391 }
392 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
393 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
394 } else {
395 // we have an initializer list with no elements.
396 totalInits -= maxElementsAtThisLevel;
397 if (totalInits < 0)
398 Diag(IList->getLocStart(), diag::warn_excess_initializers,
399 IList->getSourceRange());
Steve Naroff9091f3f2007-09-02 15:34:30 +0000400 }
Steve Naroff1c9de712007-09-03 01:24:23 +0000401 return;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000402}
403
Steve Naroffe6a8c9b2007-09-04 14:36:54 +0000404bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000405 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroff1c9de712007-09-03 01:24:23 +0000406 if (!InitList)
407 return CheckSingleInitializer(Init, DeclType);
408
Steve Naroffe14e5542007-09-02 02:04:30 +0000409 // We have an InitListExpr, make sure we set the type.
410 Init->setType(DeclType);
Steve Naroff1c9de712007-09-03 01:24:23 +0000411
412 bool hadError = false;
Steve Naroff9091f3f2007-09-02 15:34:30 +0000413
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000414 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
415 // of unknown size ("[]") or an object type that is not a variable array type.
416 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
417 Expr *expr = VAT->getSizeExpr();
Steve Naroff1c9de712007-09-03 01:24:23 +0000418 if (expr)
419 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
420 expr->getSourceRange());
421
Steve Naroff4f910992007-09-04 21:13:33 +0000422 // We have a VariableArrayType with unknown size. Note that only the first
423 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff509d0b52007-09-04 02:20:04 +0000424 int numInits = 0;
Steve Naroff4f910992007-09-04 21:13:33 +0000425 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
426 isStatic, numInits, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000427 if (!hadError) {
428 // Return a new array type from the number of initializers (C99 6.7.8p22).
429 llvm::APSInt ConstVal(32);
Steve Naroff509d0b52007-09-04 02:20:04 +0000430 ConstVal = numInits;
431 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroff1c9de712007-09-03 01:24:23 +0000432 ArrayType::Normal, 0);
433 }
434 return hadError;
435 }
436 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff4f910992007-09-04 21:13:33 +0000437 int maxElements = CAT->getMaximumElements();
438 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
439 isStatic, maxElements, hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000440 return hadError;
441 }
Steve Naroff509d0b52007-09-04 02:20:04 +0000442 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
443 int maxElements = 1;
444 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
445 hadError);
Steve Naroff1c9de712007-09-03 01:24:23 +0000446 return hadError;
Steve Naroff7c9d72d2007-09-02 20:30:18 +0000447 }
448 // FIXME: Handle struct/union types.
Steve Naroff1c9de712007-09-03 01:24:23 +0000449 return hadError;
Steve Naroffe14e5542007-09-02 02:04:30 +0000450}
451
Chris Lattner4b009652007-07-25 00:24:17 +0000452Sema::DeclTy *
Steve Naroff0acc9c92007-09-15 18:49:24 +0000453Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000454 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000455 IdentifierInfo *II = D.getIdentifier();
456
457 // All of these full declarators require an identifier. If it doesn't have
458 // one, the ParsedFreeStandingDeclSpec action should be used.
459 if (II == 0) {
Chris Lattner87492f42007-08-28 06:17:15 +0000460 Diag(D.getDeclSpec().getSourceRange().Begin(),
461 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000462 D.getDeclSpec().getSourceRange(), D.getSourceRange());
463 return 0;
464 }
465
Chris Lattnera7549902007-08-26 06:24:45 +0000466 // The scope passed in may not be a decl scope. Zip up the scope tree until
467 // we find one that is.
468 while ((S->getFlags() & Scope::DeclScope) == 0)
469 S = S->getParent();
470
Chris Lattner4b009652007-07-25 00:24:17 +0000471 // See if this is a redefinition of a variable in the same scope.
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000472 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
473 D.getIdentifierLoc(), S);
Chris Lattner4b009652007-07-25 00:24:17 +0000474 if (PrevDecl && !S->isDeclScope(PrevDecl))
475 PrevDecl = 0; // If in outer scope, it isn't the same thing.
476
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000477 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000478 bool InvalidDecl = false;
479
Chris Lattner4b009652007-07-25 00:24:17 +0000480 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Chris Lattner4b009652007-07-25 00:24:17 +0000481 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
482 if (!NewTD) return 0;
483
484 // Handle attributes prior to checking for duplicates in MergeVarDecl
485 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
486 D.getAttributes());
487 // Merge the decl with the existing one if appropriate.
488 if (PrevDecl) {
489 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
490 if (NewTD == 0) return 0;
491 }
492 New = NewTD;
493 if (S->getParent() == 0) {
494 // C99 6.7.7p2: If a typedef name specifies a variably modified type
495 // then it shall have block scope.
Steve Naroff5eb879b2007-08-31 17:20:07 +0000496 if (const VariableArrayType *VAT =
497 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
498 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
499 VAT->getSizeExpr()->getSourceRange());
500 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000501 }
502 }
503 } else if (D.isFunctionDeclarator()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000504 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000505 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000506
Chris Lattner265c8172007-09-27 15:15:46 +0000507 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000508 switch (D.getDeclSpec().getStorageClassSpec()) {
509 default: assert(0 && "Unknown storage class!");
510 case DeclSpec::SCS_auto:
511 case DeclSpec::SCS_register:
512 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
513 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000514 InvalidDecl = true;
515 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000516 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
517 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
518 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
519 }
520
521 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner987058a2007-08-26 04:02:13 +0000522 D.getDeclSpec().isInlineSpecified(),
Chris Lattner4b009652007-07-25 00:24:17 +0000523 LastDeclarator);
524
525 // Merge the decl with the existing one if appropriate.
526 if (PrevDecl) {
527 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
528 if (NewFD == 0) return 0;
529 }
530 New = NewFD;
531 } else {
532 QualType R = GetTypeForDeclarator(D, S);
Steve Naroffcae537d2007-08-28 18:45:29 +0000533 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000534
535 VarDecl *NewVD;
536 VarDecl::StorageClass SC;
537 switch (D.getDeclSpec().getStorageClassSpec()) {
538 default: assert(0 && "Unknown storage class!");
539 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
540 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
541 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
542 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
543 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
544 }
545 if (S->getParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000546 // C99 6.9p2: The storage-class specifiers auto and register shall not
547 // appear in the declaration specifiers in an external declaration.
548 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
549 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
550 R.getAsString());
Steve Naroffcae537d2007-08-28 18:45:29 +0000551 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000552 }
Chris Lattner4b009652007-07-25 00:24:17 +0000553 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +0000554 } else {
Chris Lattner4b009652007-07-25 00:24:17 +0000555 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroffcae537d2007-08-28 18:45:29 +0000556 }
Chris Lattner4b009652007-07-25 00:24:17 +0000557 // Handle attributes prior to checking for duplicates in MergeVarDecl
558 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
559 D.getAttributes());
560
561 // Merge the decl with the existing one if appropriate.
562 if (PrevDecl) {
563 NewVD = MergeVarDecl(NewVD, PrevDecl);
564 if (NewVD == 0) return 0;
565 }
Chris Lattner4b009652007-07-25 00:24:17 +0000566 New = NewVD;
567 }
568
569 // If this has an identifier, add it to the scope stack.
570 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000571 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000572 II->setFETokenInfo(New);
573 S->AddDecl(New);
574 }
575
576 if (S->getParent() == 0)
577 AddTopLevelDecl(New, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000578
579 // If any semantic error occurred, mark the decl as invalid.
580 if (D.getInvalidType() || InvalidDecl)
581 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +0000582
583 return New;
584}
585
Steve Naroff6a0e2092007-09-12 14:07:44 +0000586void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +0000587 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000588 Expr *Init = static_cast<Expr *>(init);
589
Steve Naroff420d0f52007-09-12 20:13:48 +0000590 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +0000591
Steve Naroff420d0f52007-09-12 20:13:48 +0000592 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
593 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +0000594 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
595 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +0000596 RealDecl->setInvalidDecl();
597 return;
598 }
Steve Naroff6a0e2092007-09-12 14:07:44 +0000599 // Get the decls type and save a reference for later, since
600 // CheckInitializer may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +0000601 QualType DclT = VDecl->getType(), SavT = DclT;
602 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000603 VarDecl::StorageClass SC = BVD->getStorageClass();
604 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +0000605 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000606 BVD->setInvalidDecl();
607 } else if (!BVD->isInvalidDecl()) {
608 CheckInitializer(Init, DclT, SC == VarDecl::Static);
609 }
Steve Naroff420d0f52007-09-12 20:13:48 +0000610 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000611 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +0000612 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000613 if (!FVD->isInvalidDecl())
614 CheckInitializer(Init, DclT, true);
615 }
616 // If the type changed, it means we had an incomplete type that was
617 // completed by the initializer. For example:
618 // int ary[] = { 1, 3, 5 };
619 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff420d0f52007-09-12 20:13:48 +0000620 if (!VDecl->isInvalidDecl() && (DclT != SavT))
621 VDecl->setType(DclT);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000622
623 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +0000624 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +0000625 return;
626}
627
Chris Lattner4b009652007-07-25 00:24:17 +0000628/// The declarators are chained together backwards, reverse the list.
629Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
630 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000631 Decl *GroupDecl = static_cast<Decl*>(group);
632 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +0000633 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +0000634
635 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
636 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000637 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +0000638 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +0000639 else { // reverse the list.
640 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000641 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +0000642 Group->setNextDeclarator(NewGroup);
643 NewGroup = Group;
644 Group = Next;
645 }
646 }
647 // Perform semantic analysis that depends on having fully processed both
648 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +0000649 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +0000650 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
651 if (!IDecl)
652 continue;
653 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
654 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
655 QualType T = IDecl->getType();
656
657 // C99 6.7.5.2p2: If an identifier is declared to be an object with
658 // static storage duration, it shall not have a variable length array.
659 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
660 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
661 if (VLA->getSizeExpr()) {
662 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
663 IDecl->setInvalidDecl();
664 }
665 }
666 }
667 // Block scope. C99 6.7p7: If an identifier for an object is declared with
668 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
669 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
670 if (T->isIncompleteType()) {
671 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
672 T.getAsString());
673 IDecl->setInvalidDecl();
674 }
675 }
676 // File scope. C99 6.9.2p2: A declaration of an identifier for and
677 // object that has file scope without an initializer, and without a
678 // storage-class specifier or with the storage-class specifier "static",
679 // constitutes a tentative definition. Note: A tentative definition with
680 // external linkage is valid (C99 6.2.2p5).
681 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
682 // C99 6.9.2p3: If the declaration of an identifier for an object is
683 // a tentative definition and has internal linkage (C99 6.2.2p3), the
684 // declared type shall not be an incomplete type.
685 if (T->isIncompleteType()) {
686 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
687 T.getAsString());
688 IDecl->setInvalidDecl();
689 }
690 }
Chris Lattner4b009652007-07-25 00:24:17 +0000691 }
692 return NewGroup;
693}
Steve Naroff91b03f72007-08-28 03:03:08 +0000694
695// Called from Sema::ParseStartOfFunctionDef().
Chris Lattner4b009652007-07-25 00:24:17 +0000696ParmVarDecl *
697Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
698 Scope *FnScope) {
699 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
700
701 IdentifierInfo *II = PI.Ident;
702 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
703 // Can this happen for params? We already checked that they don't conflict
704 // among each other. Here they can only shadow globals, which is ok.
705 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
706 PI.IdentLoc, FnScope)) {
707
708 }
709
710 // FIXME: Handle storage class (auto, register). No declarator?
711 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff94cd93f2007-08-07 22:44:21 +0000712
713 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
714 // Doing the promotion here has a win and a loss. The win is the type for
715 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
716 // code generator). The loss is the orginal type isn't preserved. For example:
717 //
718 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
719 // int blockvardecl[5];
720 // sizeof(parmvardecl); // size == 4
721 // sizeof(blockvardecl); // size == 20
722 // }
723 //
724 // For expressions, all implicit conversions are captured using the
725 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
726 //
727 // FIXME: If a source translation tool needs to see the original type, then
728 // we need to consider storing both types (in ParmVarDecl)...
729 //
730 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
731 if (const ArrayType *AT = parmDeclType->getAsArrayType())
732 parmDeclType = Context.getPointerType(AT->getElementType());
733 else if (parmDeclType->isFunctionType())
734 parmDeclType = Context.getPointerType(parmDeclType);
735
736 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroffcae537d2007-08-28 18:45:29 +0000737 VarDecl::None, 0);
738 if (PI.InvalidType)
739 New->setInvalidDecl();
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741 // If this has an identifier, add it to the scope stack.
742 if (II) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000743 New->setNext(II->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +0000744 II->setFETokenInfo(New);
745 FnScope->AddDecl(New);
746 }
747
748 return New;
749}
750
751
Chris Lattnerea148702007-10-09 17:14:05 +0000752Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000753 assert(CurFunctionDecl == 0 && "Function parsing confused");
754 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
755 "Not a function declarator!");
756 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
757
758 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
759 // for a K&R function.
760 if (!FTI.hasPrototype) {
761 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
762 if (FTI.ArgInfo[i].TypeInfo == 0) {
763 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
764 FTI.ArgInfo[i].Ident->getName());
765 // Implicitly declare the argument as type 'int' for lack of a better
766 // type.
767 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
768 }
769 }
770
771 // Since this is a function definition, act as though we have information
772 // about the arguments.
773 FTI.hasPrototype = true;
774 } else {
775 // FIXME: Diagnose arguments without names in C.
776
777 }
778
779 Scope *GlobalScope = FnBodyScope->getParent();
780
781 FunctionDecl *FD =
Steve Naroff0acc9c92007-09-15 18:49:24 +0000782 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Chris Lattner4b009652007-07-25 00:24:17 +0000783 CurFunctionDecl = FD;
784
785 // Create Decl objects for each parameter, adding them to the FunctionDecl.
786 llvm::SmallVector<ParmVarDecl*, 16> Params;
787
788 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
789 // no arguments, not a function that takes a single void argument.
790 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
791 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
792 // empty arg list, don't push any params.
793 } else {
794 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
795 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
796 }
797
798 FD->setParams(&Params[0], Params.size());
799
800 return FD;
801}
802
Chris Lattnerea148702007-10-09 17:14:05 +0000803Sema::DeclTy *Sema::ActOnFunctionDefBody(DeclTy *D, StmtTy *Body) {
Chris Lattner4b009652007-07-25 00:24:17 +0000804 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
805 FD->setBody((Stmt*)Body);
806
807 assert(FD == CurFunctionDecl && "Function parsing confused");
808 CurFunctionDecl = 0;
809
810 // Verify and clean out per-function state.
811
812 // Check goto/label use.
813 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
814 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
815 // Verify that we have no forward references left. If so, there was a goto
816 // or address of a label taken, but no definition of it. Label fwd
817 // definitions are indicated with a null substmt.
818 if (I->second->getSubStmt() == 0) {
819 LabelStmt *L = I->second;
820 // Emit error.
821 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
822
823 // At this point, we have gotos that use the bogus label. Stitch it into
824 // the function body so that they aren't leaked and that the AST is well
825 // formed.
826 L->setSubStmt(new NullStmt(L->getIdentLoc()));
827 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
828 }
829 }
830 LabelMap.clear();
831
832 return FD;
833}
834
835
836/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
837/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +0000838ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
839 IdentifierInfo &II, Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000840 if (getLangOptions().C99) // Extension in C99.
841 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
842 else // Legal in C90, but warn about it.
843 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
844
845 // FIXME: handle stuff like:
846 // void foo() { extern float X(); }
847 // void bar() { X(); } <-- implicit decl for X in another scope.
848
849 // Set a Declarator for the implicit definition: int foo();
850 const char *Dummy;
851 DeclSpec DS;
852 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
853 Error = Error; // Silence warning.
854 assert(!Error && "Error setting up implicit decl!");
855 Declarator D(DS, Declarator::BlockContext);
856 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
857 D.SetIdentifier(&II, Loc);
858
859 // Find translation-unit scope to insert this function into.
Chris Lattnera7549902007-08-26 06:24:45 +0000860 if (Scope *FnS = S->getFnParent())
861 S = FnS->getParent(); // Skip all scopes in a function at once.
Chris Lattner4b009652007-07-25 00:24:17 +0000862 while (S->getParent())
863 S = S->getParent();
864
Steve Narofff0c31dd2007-09-16 16:16:00 +0000865 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Chris Lattner4b009652007-07-25 00:24:17 +0000866}
867
868
869TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff2591e1b2007-09-13 23:52:58 +0000870 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +0000871 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
872
873 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000874 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +0000875
876 // Scope manipulation handled by caller.
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000877 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
878 T, LastDeclarator);
879 if (D.getInvalidType())
880 NewTD->setInvalidDecl();
881 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +0000882}
883
Steve Naroff415c1832007-10-10 17:32:04 +0000884Sema::DeclTy *Sema::ActOnStartClassInterface(
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000885 SourceLocation AtInterfaceLoc,
Steve Naroff81f1bba2007-09-06 21:24:23 +0000886 IdentifierInfo *ClassName, SourceLocation ClassLoc,
887 IdentifierInfo *SuperName, SourceLocation SuperLoc,
888 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
889 AttributeList *AttrList) {
890 assert(ClassName && "Missing class identifier");
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000891
892 // Check for another declaration kind with the same name.
893 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
Steve Naroff415c1832007-10-10 17:32:04 +0000894 ClassLoc, TUScope);
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000895 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000896 Diag(ClassLoc, diag::err_redefinition_different_kind,
897 ClassName->getName());
898 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
899 }
900
Steve Narofffa465d12007-10-02 20:01:56 +0000901 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000902 if (IDecl) {
903 // Class already seen. Is it a forward declaration?
Steve Narofff4bc79a2007-10-02 20:26:23 +0000904 if (!IDecl->isForwardDecl())
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000905 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianac775832007-09-22 00:01:35 +0000906 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000907 IDecl->setForwardDecl(false);
Fariborz Jahanianac775832007-09-22 00:01:35 +0000908 IDecl->AllocIntfRefProtocols(NumProtocols);
909 }
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000910 }
911 else {
Fariborz Jahanianac775832007-09-22 00:01:35 +0000912 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000913
Fariborz Jahaniana5f40402007-09-20 20:26:44 +0000914 // Chain & install the interface decl into the identifier.
915 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
916 ClassName->setFETokenInfo(IDecl);
917 }
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000918
919 if (SuperName) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000920 ObjcInterfaceDecl* SuperClassEntry = 0;
921 // Check if a different kind of symbol declared in this scope.
922 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
Steve Naroff415c1832007-10-10 17:32:04 +0000923 SuperLoc, TUScope);
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000924 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000925 Diag(SuperLoc, diag::err_redefinition_different_kind,
926 SuperName->getName());
927 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000928 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000929 else {
930 // Check that super class is previously defined
Steve Narofffa465d12007-10-02 20:01:56 +0000931 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000932
Steve Narofff4bc79a2007-10-02 20:26:23 +0000933 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +0000934 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
935 ClassName->getName());
936 }
937 }
938 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian0b59d9c2007-09-20 17:54:07 +0000939 }
940
Fariborz Jahanianac775832007-09-22 00:01:35 +0000941 /// Check then save referenced protocols
942 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000943 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtocolNames[i]];
Steve Narofff4bc79a2007-10-02 20:26:23 +0000944 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianac775832007-09-22 00:01:35 +0000945 Diag(ClassLoc, diag::err_undef_protocolref,
946 ProtocolNames[i]->getName(),
947 ClassName->getName());
948 IDecl->setIntfRefProtocols((int)i, RefPDecl);
949 }
950
Steve Naroff81f1bba2007-09-06 21:24:23 +0000951 return IDecl;
952}
953
Steve Naroff415c1832007-10-10 17:32:04 +0000954Sema::DeclTy *Sema::ActOnStartProtocolInterface(
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000955 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000956 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
957 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
958 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000959 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolName];
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000960 if (PDecl) {
961 // Protocol already seen. Better be a forward protocol declaration
Steve Narofff4bc79a2007-10-02 20:26:23 +0000962 if (!PDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000963 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
964 ProtocolName->getName());
965 else {
Steve Narofff4bc79a2007-10-02 20:26:23 +0000966 PDecl->setForwardDecl(false);
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000967 PDecl->AllocReferencedProtocols(NumProtoRefs);
968 }
969 }
970 else {
971 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
972 ProtocolName);
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000973 ObjcProtocols[ProtocolName] = PDecl;
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000974 }
975
976 /// Check then save referenced protocols
977 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000978 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
Steve Narofff4bc79a2007-10-02 20:26:23 +0000979 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000980 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +0000981 ProtoRefNames[i]->getName(),
Fariborz Jahanianc716c942007-09-21 15:40:54 +0000982 ProtocolName->getName());
983 PDecl->setReferencedProtocols((int)i, RefPDecl);
984 }
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000985
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +0000986 return PDecl;
987}
988
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +0000989/// ActOnFindProtocolDeclaration - This routine looks for a previously
990/// declared protocol and returns it. If not found, issues diagnostic.
991/// Will build a list of previously protocol declarations found in the list.
992Action::DeclTy **
Steve Naroff415c1832007-10-10 17:32:04 +0000993Sema::ActOnFindProtocolDeclaration(SourceLocation TypeLoc,
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +0000994 IdentifierInfo **ProtocolId,
995 unsigned NumProtocols) {
996 for (unsigned i = 0; i != NumProtocols; ++i) {
Fariborz Jahanianac142de2007-10-09 18:03:53 +0000997 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolId[i]];
Fariborz Jahaniana096e1d2007-10-05 21:01:53 +0000998 if (!PDecl)
999 Diag(TypeLoc, diag::err_undeclared_protocol,
1000 ProtocolId[i]->getName());
1001 }
1002 return 0;
1003}
1004
Steve Naroffb4dfe362007-10-02 22:39:18 +00001005/// ActOnForwardProtocolDeclaration -
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001006Action::DeclTy *
Steve Naroff415c1832007-10-10 17:32:04 +00001007Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001008 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001009 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001010
1011 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner680f7052007-10-07 07:05:08 +00001012 IdentifierInfo *P = IdentList[i];
Fariborz Jahanianac142de2007-10-09 18:03:53 +00001013 ObjcProtocolDecl *PDecl = ObjcProtocols[P];
Chris Lattner680f7052007-10-07 07:05:08 +00001014 if (!PDecl) { // Not already seen?
1015 // FIXME: Pass in the location of the identifier!
1016 PDecl = new ObjcProtocolDecl(AtProtocolLoc, 0, P, true);
Fariborz Jahanianac142de2007-10-09 18:03:53 +00001017 ObjcProtocols[P] = PDecl;
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001018 }
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001019
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001020 Protocols.push_back(PDecl);
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001021 }
Chris Lattner6b1ed8d2007-10-06 20:05:59 +00001022 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1023 &Protocols[0], Protocols.size());
Fariborz Jahanianc716c942007-09-21 15:40:54 +00001024}
1025
Steve Naroff415c1832007-10-10 17:32:04 +00001026Sema::DeclTy *Sema::ActOnStartCategoryInterface(
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001027 SourceLocation AtInterfaceLoc,
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001028 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1029 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1030 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
Chris Lattner910435b2007-10-06 22:53:46 +00001031 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianb3240c72007-10-09 17:05:22 +00001032
Fariborz Jahanianac775832007-09-22 00:01:35 +00001033 /// Check that class of this category is already completely declared.
Fariborz Jahanian1c4c35e2007-10-08 16:07:03 +00001034 if (!IDecl || IDecl->isForwardDecl()) {
Fariborz Jahanianac775832007-09-22 00:01:35 +00001035 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
Fariborz Jahanianb3240c72007-10-09 17:05:22 +00001036 return 0;
Fariborz Jahanian1c4c35e2007-10-08 16:07:03 +00001037 }
Fariborz Jahanianc53cc702007-10-09 18:22:59 +00001038 ObjcCategoryDecl *CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs,
1039 CategoryName);
1040 CDecl->setClassInterface(IDecl);
1041 /// Check for duplicate interface declaration for this category
1042 ObjcCategoryDecl *CDeclChain;
1043 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1044 CDeclChain = CDeclChain->getNextClassCategory()) {
1045 if (CDeclChain->getIdentifier() == CategoryName) {
1046 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1047 CategoryName->getName());
1048 break;
Fariborz Jahanianac775832007-09-22 00:01:35 +00001049 }
Fariborz Jahanianac775832007-09-22 00:01:35 +00001050 }
Fariborz Jahanianc53cc702007-10-09 18:22:59 +00001051 if (!CDeclChain)
1052 CDecl->insertNextClassCategory();
1053
Fariborz Jahanianac775832007-09-22 00:01:35 +00001054 /// Check then save referenced protocols
1055 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanianac142de2007-10-09 18:03:53 +00001056 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
Fariborz Jahanian1c4c35e2007-10-08 16:07:03 +00001057 if (!RefPDecl || RefPDecl->isForwardDecl()) {
Fariborz Jahanianac775832007-09-22 00:01:35 +00001058 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001059 ProtoRefNames[i]->getName(),
Fariborz Jahanianac775832007-09-22 00:01:35 +00001060 CategoryName->getName());
Fariborz Jahanian1c4c35e2007-10-08 16:07:03 +00001061 }
Fariborz Jahanianac775832007-09-22 00:01:35 +00001062 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1063 }
1064
Fariborz Jahanianb3240c72007-10-09 17:05:22 +00001065 return CDecl;
Fariborz Jahanianf25220e2007-09-18 20:26:58 +00001066}
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001067
Steve Naroff25aace82007-10-03 21:00:46 +00001068/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001069/// category implementation declaration and build an ObjcCategoryImplDecl
1070/// object.
Steve Naroff415c1832007-10-10 17:32:04 +00001071Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001072 SourceLocation AtCatImplLoc,
1073 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1074 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Narofffa465d12007-10-02 20:01:56 +00001075 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001076 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
Chris Lattner79b00842007-10-06 23:12:31 +00001077 CatName, IDecl);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001078 /// Check that class of this category is already completely declared.
Steve Narofff4bc79a2007-10-02 20:26:23 +00001079 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001080 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1081 /// TODO: Check that CatName, category name, is not used in another
1082 // implementation.
1083 return CDecl;
1084}
1085
Steve Naroff415c1832007-10-10 17:32:04 +00001086Sema::DeclTy *Sema::ActOnStartClassImplementation(
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001087 SourceLocation AtClassImplLoc,
1088 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1089 IdentifierInfo *SuperClassname,
1090 SourceLocation SuperClassLoc) {
1091 ObjcInterfaceDecl* IDecl = 0;
1092 // Check for another declaration kind with the same name.
1093 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
Steve Naroff415c1832007-10-10 17:32:04 +00001094 ClassLoc, TUScope);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001095 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1096 Diag(ClassLoc, diag::err_redefinition_different_kind,
1097 ClassName->getName());
1098 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1099 }
1100 else {
1101 // Is there an interface declaration of this class; if not, warn!
Steve Narofffa465d12007-10-02 20:01:56 +00001102 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001103 if (!IDecl)
1104 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1105 }
1106
1107 // Check that super class name is valid class name
1108 ObjcInterfaceDecl* SDecl = 0;
1109 if (SuperClassname) {
1110 // Check if a different kind of symbol declared in this scope.
1111 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
Steve Naroff415c1832007-10-10 17:32:04 +00001112 SuperClassLoc, TUScope);
Fariborz Jahanianac142de2007-10-09 18:03:53 +00001113 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001114 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1115 SuperClassname->getName());
1116 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1117 }
1118 else {
Steve Narofffa465d12007-10-02 20:01:56 +00001119 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001120 if (!SDecl)
1121 Diag(SuperClassLoc, diag::err_undef_superclass,
1122 SuperClassname->getName(), ClassName->getName());
1123 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1124 // This implementation and its interface do not have the same
1125 // super class.
1126 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1127 SuperClassname->getName());
1128 Diag(SDecl->getLocation(), diag::err_previous_definition);
1129 }
1130 }
1131 }
1132
1133 ObjcImplementationDecl* IMPDecl =
1134 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001135 if (!IDecl) {
1136 // Legacy case of @implementation with no corresponding @interface.
1137 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001138 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian1c0eedb2007-09-25 21:00:20 +00001139 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1140 ClassName->setFETokenInfo(IDecl);
1141
1142 }
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001143
1144 // Check that there is no duplicate implementation of this class.
Chris Lattnera7a191c2007-10-07 01:13:46 +00001145 if (!ObjcImplementations.insert(ClassName))
1146 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001147
1148 return IMPDecl;
1149}
1150
Steve Naroff89529b12007-10-02 21:43:37 +00001151void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1152 ObjcIvarDecl **ivars, unsigned numIvars) {
1153 assert(ImpDecl && "missing implementation decl");
1154 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001155 /// 2nd check is added to accomodate case of non-existing @interface decl.
1156 /// (legacy objective-c @implementation decl without an @interface decl).
1157 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroff89529b12007-10-02 21:43:37 +00001158 return;
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001159 assert(ivars && "missing @implementation ivars");
1160
Steve Naroff89529b12007-10-02 21:43:37 +00001161 // Check interface's Ivar list against those in the implementation.
1162 // names and types must match.
1163 //
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001164 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1165 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1166 unsigned j = 0;
1167 bool err = false;
1168 while (numIvars > 0 && IntfNumIvars > 0) {
1169 ObjcIvarDecl* ImplIvar = ivars[j];
1170 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1171 assert (ImplIvar && "missing implementation ivar");
1172 assert (ClsIvar && "missing class ivar");
1173 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1174 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1175 ImplIvar->getIdentifier()->getName());
1176 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1177 ClsIvar->getIdentifier()->getName());
1178 }
1179 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1180 // as error.
1181 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1182 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1183 ImplIvar->getIdentifier()->getName());
1184 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1185 ClsIvar->getIdentifier()->getName());
1186 err = true;
1187 break;
1188 }
1189 --numIvars;
1190 --IntfNumIvars;
1191 }
1192 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1193 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1194 diag::err_inconsistant_ivar);
1195
1196}
1197
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001198/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1199/// Declared in protocol, and those referenced by it.
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001200void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001201 bool& IncompleteImpl,
Steve Naroff7711ee32007-10-08 21:05:34 +00001202 const llvm::DenseSet<Selector> &InsMap,
Chris Lattner48ed6f82007-10-05 20:15:24 +00001203 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001204 // check unimplemented instance methods.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001205 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001206 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
Steve Naroff7711ee32007-10-08 21:05:34 +00001207 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001208 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001209 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001210 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001211 }
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001212 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001213 // check unimplemented class methods
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001214 methods = PDecl->getClassMethods();
1215 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001216 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001217 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001218 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001219 IncompleteImpl = true;
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001220 }
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001221
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001222 // Check on this protocols's referenced protocols, recursively
1223 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1224 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001225 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001226}
1227
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001228void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1229 ObjcInterfaceDecl* IDecl) {
Steve Naroff7711ee32007-10-08 21:05:34 +00001230 llvm::DenseSet<Selector> InsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001231 // Check and see if instance methods in class interface have been
1232 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001233 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001234 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
Steve Naroff7711ee32007-10-08 21:05:34 +00001235 InsMap.insert(methods[i]->getSelector());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001236
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001237 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001238 methods = IDecl->getInstanceMethods();
1239 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroff7711ee32007-10-08 21:05:34 +00001240 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001241 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001242 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001243 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001244 }
Chris Lattner48ed6f82007-10-05 20:15:24 +00001245 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001246 // Check and see if class methods in class interface have been
1247 // implemented in the implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001248 methods = IMPDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001249 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001250 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001251
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001252 methods = IDecl->getClassMethods();
1253 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001254 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanianf7cf3a62007-09-29 17:14:55 +00001255 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001256 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001257 IncompleteImpl = true;
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001258 }
Fariborz Jahanian5975f772007-09-28 17:40:07 +00001259
1260 // Check the protocol list for unimplemented methods in the @implementation
1261 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001262 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner48ed6f82007-10-05 20:15:24 +00001263 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1264 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1265
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001266 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001267 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1268 IMPDecl->getName());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001269}
1270
1271/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1272/// category interface is implemented in the category @implementation.
1273void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1274 ObjcCategoryDecl *CatClassDecl) {
Steve Naroff7711ee32007-10-08 21:05:34 +00001275 llvm::DenseSet<Selector> InsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001276 // Check and see if instance methods in category interface have been
1277 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001278 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001279 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
Steve Naroff7711ee32007-10-08 21:05:34 +00001280 InsMap.insert(methods[i]->getSelector());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001281
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001282 bool IncompleteImpl = false;
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001283 methods = CatClassDecl->getInstanceMethods();
1284 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Steve Naroff7711ee32007-10-08 21:05:34 +00001285 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001286 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001287 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001288 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001289 }
Chris Lattner48ed6f82007-10-05 20:15:24 +00001290 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001291 // Check and see if class methods in category interface have been
1292 // implemented in its implementation class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001293 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001294 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001295 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001296
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001297 methods = CatClassDecl->getClassMethods();
1298 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner48ed6f82007-10-05 20:15:24 +00001299 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001300 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001301 methods[j]->getSelector().getName());
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001302 IncompleteImpl = true;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001303 }
1304
1305 // Check the protocol list for unimplemented methods in the @implementation
1306 // class.
Fariborz Jahanian1c095a72007-10-02 22:05:16 +00001307 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1308 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001309 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001310 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001311 }
Fariborz Jahaniand3952f32007-10-02 20:06:01 +00001312 if (IncompleteImpl)
Fariborz Jahanianfa601d52007-10-04 00:22:33 +00001313 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Chris Lattner910435b2007-10-06 22:53:46 +00001314 CatClassDecl->getName());
Fariborz Jahanian1e4e82f2007-09-27 18:57:03 +00001315}
1316
Steve Naroffb4dfe362007-10-02 22:39:18 +00001317/// ActOnForwardClassDeclaration -
Steve Naroff81f1bba2007-09-06 21:24:23 +00001318Action::DeclTy *
Steve Naroff415c1832007-10-10 17:32:04 +00001319Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Steve Naroffb4dfe362007-10-02 22:39:18 +00001320 IdentifierInfo **IdentList, unsigned NumElts)
1321{
Chris Lattner2443d912007-10-06 20:08:36 +00001322 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1323
Steve Naroff81f1bba2007-09-06 21:24:23 +00001324 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner2443d912007-10-06 20:08:36 +00001325 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(IdentList[i]);
1326 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianac775832007-09-22 00:01:35 +00001327 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001328 // Chain & install the interface decl into the identifier.
1329 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1330 IdentList[i]->setFETokenInfo(IDecl);
Chris Lattner680f7052007-10-07 07:05:08 +00001331
1332 // Remember that this needs to be removed when the scope is popped.
Steve Naroff415c1832007-10-10 17:32:04 +00001333 TUScope->AddDecl(IDecl);
Fariborz Jahaniana5f40402007-09-20 20:26:44 +00001334 }
Chris Lattner2443d912007-10-06 20:08:36 +00001335
1336 Interfaces.push_back(IDecl);
Steve Naroff81f1bba2007-09-06 21:24:23 +00001337 }
Chris Lattner2443d912007-10-06 20:08:36 +00001338
1339 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff81f1bba2007-09-06 21:24:23 +00001340}
1341
Chris Lattner4b009652007-07-25 00:24:17 +00001342
Steve Naroff0acc9c92007-09-15 18:49:24 +00001343/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00001344/// former case, Name will be non-null. In the later case, Name will be null.
1345/// TagType indicates what kind of tag this is. TK indicates whether this is a
1346/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001347Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00001348 SourceLocation KWLoc, IdentifierInfo *Name,
1349 SourceLocation NameLoc, AttributeList *Attr) {
1350 // If this is a use of an existing tag, it must have a name.
1351 assert((Name != 0 || TK == TK_Definition) &&
1352 "Nameless record must be a definition!");
1353
1354 Decl::Kind Kind;
1355 switch (TagType) {
1356 default: assert(0 && "Unknown tag type!");
1357 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1358 case DeclSpec::TST_union: Kind = Decl::Union; break;
1359//case DeclSpec::TST_class: Kind = Decl::Class; break;
1360 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1361 }
1362
1363 // If this is a named struct, check to see if there was a previous forward
1364 // declaration or definition.
1365 if (TagDecl *PrevDecl =
1366 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1367 NameLoc, S))) {
1368
1369 // If this is a use of a previous tag, or if the tag is already declared in
1370 // the same scope (so that the definition/declaration completes or
1371 // rementions the tag), reuse the decl.
1372 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1373 // Make sure that this wasn't declared as an enum and now used as a struct
1374 // or something similar.
1375 if (PrevDecl->getKind() != Kind) {
1376 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1377 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1378 }
1379
1380 // If this is a use or a forward declaration, we're good.
1381 if (TK != TK_Definition)
1382 return PrevDecl;
1383
1384 // Diagnose attempts to redefine a tag.
1385 if (PrevDecl->isDefinition()) {
1386 Diag(NameLoc, diag::err_redefinition, Name->getName());
1387 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1388 // If this is a redefinition, recover by making this struct be
1389 // anonymous, which will make any later references get the previous
1390 // definition.
1391 Name = 0;
1392 } else {
1393 // Okay, this is definition of a previously declared or referenced tag.
1394 // Move the location of the decl to be the definition site.
1395 PrevDecl->setLocation(NameLoc);
1396 return PrevDecl;
1397 }
1398 }
1399 // If we get here, this is a definition of a new struct type in a nested
1400 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1401 // type.
1402 }
1403
1404 // If there is an identifier, use the location of the identifier as the
1405 // location of the decl, otherwise use the location of the struct/union
1406 // keyword.
1407 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1408
1409 // Otherwise, if this is the first time we've seen this tag, create the decl.
1410 TagDecl *New;
1411 switch (Kind) {
1412 default: assert(0 && "Unknown tag kind!");
1413 case Decl::Enum:
1414 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1415 // enum X { A, B, C } D; D should chain to X.
1416 New = new EnumDecl(Loc, Name, 0);
1417 // If this is an undefined enum, warn.
1418 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1419 break;
1420 case Decl::Union:
1421 case Decl::Struct:
1422 case Decl::Class:
1423 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1424 // struct X { int A; } D; D should chain to X.
1425 New = new RecordDecl(Kind, Loc, Name, 0);
1426 break;
1427 }
1428
1429 // If this has an identifier, add it to the scope stack.
1430 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00001431 // The scope passed in may not be a decl scope. Zip up the scope tree until
1432 // we find one that is.
1433 while ((S->getFlags() & Scope::DeclScope) == 0)
1434 S = S->getParent();
1435
1436 // Add it to the decl chain.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001437 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001438 Name->setFETokenInfo(New);
1439 S->AddDecl(New);
1440 }
1441
1442 return New;
1443}
1444
Steve Naroff0acc9c92007-09-15 18:49:24 +00001445/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00001446/// to create a FieldDecl object for it.
Steve Naroff0acc9c92007-09-15 18:49:24 +00001447Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001448 SourceLocation DeclStart,
1449 Declarator &D, ExprTy *BitfieldWidth) {
1450 IdentifierInfo *II = D.getIdentifier();
1451 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00001452 SourceLocation Loc = DeclStart;
1453 if (II) Loc = D.getIdentifierLoc();
1454
1455 // FIXME: Unnamed fields can be handled in various different ways, for
1456 // example, unnamed unions inject all members into the struct namespace!
1457
1458
1459 if (BitWidth) {
1460 // TODO: Validate.
1461 //printf("WARNING: BITFIELDS IGNORED!\n");
1462
1463 // 6.7.2.1p3
1464 // 6.7.2.1p4
1465
1466 } else {
1467 // Not a bitfield.
1468
1469 // validate II.
1470
1471 }
1472
1473 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001474 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1475 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00001476
Chris Lattner4b009652007-07-25 00:24:17 +00001477 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1478 // than a variably modified type.
Steve Naroff5eb879b2007-08-31 17:20:07 +00001479 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1480 Diag(Loc, diag::err_typecheck_illegal_vla,
1481 VAT->getSizeExpr()->getSourceRange());
1482 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001483 }
Chris Lattner4b009652007-07-25 00:24:17 +00001484 // FIXME: Chain fielddecls together.
Steve Naroff75494892007-09-11 21:17:26 +00001485 FieldDecl *NewFD;
1486
1487 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001488 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianc091b5d2007-09-25 18:38:09 +00001489 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001490 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Naroffdc1ad762007-09-14 02:20:46 +00001491 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff75494892007-09-11 21:17:26 +00001492 else
Steve Naroff0acc9c92007-09-15 18:49:24 +00001493 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff75494892007-09-11 21:17:26 +00001494
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001495 if (D.getInvalidType() || InvalidDecl)
1496 NewFD->setInvalidDecl();
1497 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00001498}
1499
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001500/// TranslateIvarVisibility - Translate visibility from a token ID to an
1501/// AST enum value.
1502static ObjcIvarDecl::AccessControl
1503TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00001504 switch (ivarVisibility) {
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001505 case tok::objc_private: return ObjcIvarDecl::Private;
1506 case tok::objc_public: return ObjcIvarDecl::Public;
1507 case tok::objc_protected: return ObjcIvarDecl::Protected;
1508 case tok::objc_package: return ObjcIvarDecl::Package;
1509 default: assert(false && "Unknown visitibility kind");
Steve Naroffffeaa552007-09-14 23:09:53 +00001510 }
1511}
1512
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00001513void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001514 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00001515 DeclTy **Fields, unsigned NumFields,
1516 tok::ObjCKeywordKind *visibility) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001517 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1518 assert(EnclosingDecl && "missing record or interface decl");
1519 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1520
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001521 if (Record && Record->isDefinition()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001522 // Diagnose code like:
1523 // struct S { struct S {} X; };
1524 // We discover this when we complete the outer S. Reject and ignore the
1525 // outer S.
1526 Diag(Record->getLocation(), diag::err_nested_redefinition,
1527 Record->getKindName());
1528 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001529 Record->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001530 return;
1531 }
Chris Lattner4b009652007-07-25 00:24:17 +00001532 // Verify that all the fields are okay.
1533 unsigned NumNamedMembers = 0;
1534 llvm::SmallVector<FieldDecl*, 32> RecFields;
1535 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00001536
Chris Lattner4b009652007-07-25 00:24:17 +00001537 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001538
Steve Naroff9bb759f2007-09-14 22:20:54 +00001539 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1540 assert(FD && "missing field decl");
1541
1542 // Remember all fields.
1543 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00001544
1545 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00001546 Type *FDTy = FD->getType().getTypePtr();
Chris Lattner4b009652007-07-25 00:24:17 +00001547
Steve Naroffffeaa552007-09-14 23:09:53 +00001548 // If we have visibility info, make sure the AST is set accordingly.
1549 if (visibility)
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00001550 cast<ObjcIvarDecl>(FD)->setAccessControl(
1551 TranslateIvarVisibility(visibility[i]));
Steve Naroffffeaa552007-09-14 23:09:53 +00001552
Chris Lattner4b009652007-07-25 00:24:17 +00001553 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00001554 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00001555 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00001556 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001557 FD->setInvalidDecl();
1558 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001559 continue;
1560 }
Chris Lattner4b009652007-07-25 00:24:17 +00001561 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1562 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001563 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001564 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001565 FD->setInvalidDecl();
1566 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001567 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001568 }
Chris Lattner4b009652007-07-25 00:24:17 +00001569 if (i != NumFields-1 || // ... that the last member ...
1570 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00001571 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00001572 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001573 FD->setInvalidDecl();
1574 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001575 continue;
1576 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001577 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00001578 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1579 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001580 FD->setInvalidDecl();
1581 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001582 continue;
1583 }
Chris Lattner4b009652007-07-25 00:24:17 +00001584 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001585 if (Record)
1586 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001587 }
Chris Lattner4b009652007-07-25 00:24:17 +00001588 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1589 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00001590 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001591 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1592 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001593 if (Record && Record->getKind() == Decl::Union) {
Chris Lattner4b009652007-07-25 00:24:17 +00001594 Record->setHasFlexibleArrayMember(true);
1595 } else {
1596 // If this is a struct/class and this is not the last element, reject
1597 // it. Note that GCC supports variable sized arrays in the middle of
1598 // structures.
1599 if (i != NumFields-1) {
1600 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1601 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00001602 FD->setInvalidDecl();
1603 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001604 continue;
1605 }
Chris Lattner4b009652007-07-25 00:24:17 +00001606 // We support flexible arrays at the end of structs in other structs
1607 // as an extension.
1608 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1609 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001610 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001611 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001612 }
1613 }
1614 }
Chris Lattner4b009652007-07-25 00:24:17 +00001615 // Keep track of the number of named members.
1616 if (IdentifierInfo *II = FD->getIdentifier()) {
1617 // Detect duplicate member names.
1618 if (!FieldIDs.insert(II)) {
1619 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1620 // Find the previous decl.
1621 SourceLocation PrevLoc;
1622 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1623 assert(i != e && "Didn't find previous def!");
1624 if (RecFields[i]->getIdentifier() == II) {
1625 PrevLoc = RecFields[i]->getLocation();
1626 break;
1627 }
1628 }
1629 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00001630 FD->setInvalidDecl();
1631 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001632 continue;
1633 }
1634 ++NumNamedMembers;
1635 }
Chris Lattner4b009652007-07-25 00:24:17 +00001636 }
1637
Chris Lattner4b009652007-07-25 00:24:17 +00001638 // Okay, we successfully defined 'Record'.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00001639 if (Record)
1640 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001641 else {
1642 ObjcIvarDecl **ClsFields =
1643 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001644 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1645 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1646 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1647 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1648 ObjcImplementationDecl* IMPDecl =
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001649 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001650 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1651 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroff89529b12007-10-02 21:43:37 +00001652 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00001653 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00001654 }
Chris Lattner4b009652007-07-25 00:24:17 +00001655}
1656
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001657/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1658/// returns true, or false, accordingly.
1659/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1660bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1661 const ObjcMethodDecl *PrevMethod) {
1662 if (Method->getMethodType().getCanonicalType() !=
1663 PrevMethod->getMethodType().getCanonicalType())
1664 return false;
1665 for (int i = 0; i < Method->getNumParams(); i++) {
1666 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1667 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1668 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1669 return false;
1670 }
1671 return true;
1672}
1673
Chris Lattner910435b2007-10-06 22:53:46 +00001674void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *classDecl,
Steve Naroff25aace82007-10-03 21:00:46 +00001675 DeclTy **allMethods, unsigned allNum) {
Chris Lattner910435b2007-10-06 22:53:46 +00001676 Decl *ClassDecl = static_cast<Decl *>(classDecl);
1677
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001678 // FIXME: Fix this when we can handle methods declared in protocols.
1679 // See Parser::ParseObjCAtProtocolDeclaration
1680 if (!ClassDecl)
1681 return;
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001682 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1683 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001684
Steve Naroff7711ee32007-10-08 21:05:34 +00001685 llvm::DenseMap<Selector, const ObjcMethodDecl*> InsMap;
1686 llvm::DenseMap<Selector, const ObjcMethodDecl*> ClsMap;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001687
1688 bool isClassDeclaration =
Chris Lattner910435b2007-10-06 22:53:46 +00001689 (isa<ObjcInterfaceDecl>(ClassDecl) || isa<ObjcCategoryDecl>(ClassDecl));
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001690
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001691 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001692 ObjcMethodDecl *Method =
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001693 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1694 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001695 if (Method->isInstance()) {
1696 if (isClassDeclaration) {
1697 /// Check for instance method of the same name with incompatible types
Steve Naroff7711ee32007-10-08 21:05:34 +00001698 const ObjcMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001699 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001700 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001701 Method->getSelector().getName());
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001702 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1703 }
1704 else {
1705 insMethods.push_back(Method);
Steve Naroff7711ee32007-10-08 21:05:34 +00001706 InsMap[Method->getSelector()] = Method;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001707 }
1708 }
1709 else
1710 insMethods.push_back(Method);
1711 }
1712 else {
1713 if (isClassDeclaration) {
1714 /// Check for class method of the same name with incompatible types
Steve Naroff7711ee32007-10-08 21:05:34 +00001715 const ObjcMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001716 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001717 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattner64610dd2007-10-07 01:33:16 +00001718 Method->getSelector().getName());
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001719 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1720 }
1721 else {
1722 clsMethods.push_back(Method);
Steve Naroff7711ee32007-10-08 21:05:34 +00001723 ClsMap[Method->getSelector()] = Method;
Fariborz Jahanian67907bd2007-10-05 18:00:57 +00001724 }
1725 }
1726 else
1727 clsMethods.push_back(Method);
1728 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001729 }
Chris Lattner910435b2007-10-06 22:53:46 +00001730
1731 if (ObjcInterfaceDecl *I = dyn_cast<ObjcInterfaceDecl>(ClassDecl)) {
1732 I->ObjcAddMethods(&insMethods[0], insMethods.size(),
1733 &clsMethods[0], clsMethods.size());
1734 } else if (ObjcProtocolDecl *P = dyn_cast<ObjcProtocolDecl>(ClassDecl)) {
1735 P->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1736 &clsMethods[0], clsMethods.size());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001737 }
Chris Lattner910435b2007-10-06 22:53:46 +00001738 else if (ObjcCategoryDecl *C = dyn_cast<ObjcCategoryDecl>(ClassDecl)) {
1739 C->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1740 &clsMethods[0], clsMethods.size());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001741 }
Chris Lattner910435b2007-10-06 22:53:46 +00001742 else if (ObjcImplementationDecl *IC =
1743 dyn_cast<ObjcImplementationDecl>(ClassDecl)) {
1744 IC->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1745 &clsMethods[0], clsMethods.size());
1746 if (ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1747 ImplMethodsVsClassMethods(IC, IDecl);
1748 } else {
1749 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(ClassDecl);
1750 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1751 &clsMethods[0], clsMethods.size());
1752 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1753 // Find category interface decl and then check that all methods declared
1754 // in this interface is implemented in the category @implementation.
1755 if (IDecl) {
1756 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1757 Categories; Categories = Categories->getNextClassCategory()) {
Chris Lattner79b00842007-10-06 23:12:31 +00001758 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
Chris Lattner910435b2007-10-06 22:53:46 +00001759 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1760 break;
Fariborz Jahaniana91aa322007-10-02 16:38:50 +00001761 }
1762 }
1763 }
1764 }
Fariborz Jahanian3dc7cbc2007-09-10 20:33:04 +00001765}
1766
Steve Naroffb4dfe362007-10-02 22:39:18 +00001767Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroff6cb1d362007-09-28 22:22:11 +00001768 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff4ed9d662007-09-27 14:38:14 +00001769 // optional arguments. The number of types/arguments is obtained
1770 // from the Sel.getNumArgs().
1771 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1772 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001773 llvm::SmallVector<ParmVarDecl*, 16> Params;
1774
Steve Naroff6cb1d362007-09-28 22:22:11 +00001775 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001776 // FIXME: arg->AttrList must be stored too!
Steve Naroff4ed9d662007-09-27 14:38:14 +00001777 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001778 QualType::getFromOpaquePtr(ArgTypes[i]),
1779 VarDecl::None, 0);
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001780 Params.push_back(Param);
1781 }
Steve Naroff9637a9b2007-10-09 22:01:59 +00001782 QualType resultDeclType;
1783
1784 if (ReturnType)
1785 resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1786 else { // get the type for "id".
1787 IdentifierInfo *IdIdent = &Context.Idents.get("id");
1788 ScopedDecl *IdDecl = LookupScopedDecl(IdIdent, Decl::IDNS_Ordinary,
1789 SourceLocation(), TUScope);
1790 TypedefDecl *IdTypedef = dyn_cast_or_null<TypedefDecl>(IdDecl);
1791 assert(IdTypedef && "ActOnMethodDeclaration(): Couldn't find 'id' type");
1792 resultDeclType = IdTypedef->getUnderlyingType();
1793 }
Steve Naroff4ed9d662007-09-27 14:38:14 +00001794 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1795 resultDeclType, 0, -1, AttrList,
Fariborz Jahaniana00e0742007-09-29 18:24:58 +00001796 MethodType == tok::minus,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00001797 MethodDeclKind == tok::objc_optional ?
1798 ObjcMethodDecl::Optional :
1799 ObjcMethodDecl::Required);
Steve Naroff6cb1d362007-09-28 22:22:11 +00001800 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian63ca8ae2007-09-17 21:07:36 +00001801 return ObjcMethod;
Fariborz Jahanian86f74a42007-09-12 18:23:47 +00001802}
1803
Steve Naroff0acc9c92007-09-15 18:49:24 +00001804Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00001805 DeclTy *lastEnumConst,
1806 SourceLocation IdLoc, IdentifierInfo *Id,
1807 SourceLocation EqualLoc, ExprTy *val) {
1808 theEnumDecl = theEnumDecl; // silence unused warning.
1809 EnumConstantDecl *LastEnumConst =
1810 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1811 Expr *Val = static_cast<Expr*>(val);
1812
Chris Lattnera7549902007-08-26 06:24:45 +00001813 // The scope passed in may not be a decl scope. Zip up the scope tree until
1814 // we find one that is.
1815 while ((S->getFlags() & Scope::DeclScope) == 0)
1816 S = S->getParent();
1817
Chris Lattner4b009652007-07-25 00:24:17 +00001818 // Verify that there isn't already something declared with this name in this
1819 // scope.
Steve Naroffcb597472007-09-13 21:41:19 +00001820 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1821 IdLoc, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001822 if (S->isDeclScope(PrevDecl)) {
1823 if (isa<EnumConstantDecl>(PrevDecl))
1824 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1825 else
1826 Diag(IdLoc, diag::err_redefinition, Id->getName());
1827 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1828 // FIXME: Don't leak memory: delete Val;
1829 return 0;
1830 }
1831 }
1832
1833 llvm::APSInt EnumVal(32);
1834 QualType EltTy;
1835 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00001836 // Make sure to promote the operand type to int.
1837 UsualUnaryConversions(Val);
1838
Chris Lattner4b009652007-07-25 00:24:17 +00001839 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1840 SourceLocation ExpLoc;
1841 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
1842 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1843 Id->getName());
1844 // FIXME: Don't leak memory: delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00001845 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00001846 } else {
1847 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00001848 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00001849 }
1850
1851 if (!Val) {
1852 if (LastEnumConst) {
1853 // Assign the last value + 1.
1854 EnumVal = LastEnumConst->getInitVal();
1855 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00001856
1857 // Check for overflow on increment.
1858 if (EnumVal < LastEnumConst->getInitVal())
1859 Diag(IdLoc, diag::warn_enum_value_overflow);
1860
Chris Lattnere7f53a42007-08-27 17:37:24 +00001861 EltTy = LastEnumConst->getType();
1862 } else {
1863 // First value, set to zero.
1864 EltTy = Context.IntTy;
Chris Lattner3496d522007-09-04 02:45:27 +00001865 EnumVal.zextOrTrunc(
1866 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00001867 }
Chris Lattner4b009652007-07-25 00:24:17 +00001868 }
1869
Chris Lattner4b009652007-07-25 00:24:17 +00001870 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1871 LastEnumConst);
1872
1873 // Register this decl in the current scope stack.
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001874 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Chris Lattner4b009652007-07-25 00:24:17 +00001875 Id->setFETokenInfo(New);
1876 S->AddDecl(New);
1877 return New;
1878}
1879
Steve Naroff0acc9c92007-09-15 18:49:24 +00001880void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00001881 DeclTy **Elements, unsigned NumElements) {
1882 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1883 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1884
Chris Lattner435c3fd2007-08-28 05:10:31 +00001885 // TODO: If the result value doesn't fit in an int, it must be a long or long
1886 // long value. ISO C does not support this, but GCC does as an extension,
1887 // emit a warning.
Chris Lattner206754a2007-08-28 06:15:15 +00001888 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattner435c3fd2007-08-28 05:10:31 +00001889
1890
Chris Lattner206754a2007-08-28 06:15:15 +00001891 // Verify that all the values are okay, compute the size of the values, and
1892 // reverse the list.
1893 unsigned NumNegativeBits = 0;
1894 unsigned NumPositiveBits = 0;
1895
1896 // Keep track of whether all elements have type int.
1897 bool AllElementsInt = true;
1898
Chris Lattner4b009652007-07-25 00:24:17 +00001899 EnumConstantDecl *EltList = 0;
1900 for (unsigned i = 0; i != NumElements; ++i) {
1901 EnumConstantDecl *ECD =
1902 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1903 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00001904
1905 // If the enum value doesn't fit in an int, emit an extension warning.
1906 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1907 "Should have promoted value to int");
1908 const llvm::APSInt &InitVal = ECD->getInitVal();
1909 if (InitVal.getBitWidth() > IntWidth) {
1910 llvm::APSInt V(InitVal);
1911 V.trunc(IntWidth);
1912 V.extend(InitVal.getBitWidth());
1913 if (V != InitVal)
1914 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1915 InitVal.toString());
1916 }
Chris Lattner206754a2007-08-28 06:15:15 +00001917
1918 // Keep track of the size of positive and negative values.
1919 if (InitVal.isUnsigned() || !InitVal.isNegative())
1920 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1921 else
1922 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00001923
Chris Lattner206754a2007-08-28 06:15:15 +00001924 // Keep track of whether every enum element has type int (very commmon).
1925 if (AllElementsInt)
1926 AllElementsInt = ECD->getType() == Context.IntTy;
1927
Chris Lattner4b009652007-07-25 00:24:17 +00001928 ECD->setNextDeclarator(EltList);
1929 EltList = ECD;
1930 }
1931
Chris Lattner206754a2007-08-28 06:15:15 +00001932 // Figure out the type that should be used for this enum.
1933 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1934 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001935 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00001936
1937 if (NumNegativeBits) {
1938 // If there is a negative value, figure out the smallest integer type (of
1939 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001940 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001941 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001942 BestWidth = IntWidth;
1943 } else {
1944 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1945 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001946 BestType = Context.LongTy;
1947 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001948 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1949 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00001950 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1951 BestType = Context.LongLongTy;
1952 }
1953 }
1954 } else {
1955 // If there is no negative value, figure out which of uint, ulong, ulonglong
1956 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001957 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00001958 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001959 BestWidth = IntWidth;
1960 } else if (NumPositiveBits <=
1961 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattner206754a2007-08-28 06:15:15 +00001962 BestType = Context.UnsignedLongTy;
1963 else {
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001964 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1965 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00001966 "How could an initializer get larger than ULL?");
1967 BestType = Context.UnsignedLongLongTy;
1968 }
1969 }
1970
Chris Lattnerca01d0a2007-08-29 17:31:48 +00001971 // Loop over all of the enumerator constants, changing their types to match
1972 // the type of the enum if needed.
1973 for (unsigned i = 0; i != NumElements; ++i) {
1974 EnumConstantDecl *ECD =
1975 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1976 if (!ECD) continue; // Already issued a diagnostic.
1977
1978 // Standard C says the enumerators have int type, but we allow, as an
1979 // extension, the enumerators to be larger than int size. If each
1980 // enumerator value fits in an int, type it as an int, otherwise type it the
1981 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1982 // that X has type 'int', not 'unsigned'.
1983 if (ECD->getType() == Context.IntTy)
1984 continue; // Already int type.
1985
1986 // Determine whether the value fits into an int.
1987 llvm::APSInt InitVal = ECD->getInitVal();
1988 bool FitsInInt;
1989 if (InitVal.isUnsigned() || !InitVal.isNegative())
1990 FitsInInt = InitVal.getActiveBits() < IntWidth;
1991 else
1992 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1993
1994 // If it fits into an integer type, force it. Otherwise force it to match
1995 // the enum decl type.
1996 QualType NewTy;
1997 unsigned NewWidth;
1998 bool NewSign;
1999 if (FitsInInt) {
2000 NewTy = Context.IntTy;
2001 NewWidth = IntWidth;
2002 NewSign = true;
2003 } else if (ECD->getType() == BestType) {
2004 // Already the right type!
2005 continue;
2006 } else {
2007 NewTy = BestType;
2008 NewWidth = BestWidth;
2009 NewSign = BestType->isSignedIntegerType();
2010 }
2011
2012 // Adjust the APSInt value.
2013 InitVal.extOrTrunc(NewWidth);
2014 InitVal.setIsSigned(NewSign);
2015 ECD->setInitVal(InitVal);
2016
2017 // Adjust the Expr initializer and type.
2018 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2019 ECD->setType(NewTy);
2020 }
Chris Lattner206754a2007-08-28 06:15:15 +00002021
Chris Lattner90a018d2007-08-28 18:24:31 +00002022 Enum->defineElements(EltList, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00002023}
2024
2025void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2026 if (!current) return;
2027
2028 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2029 // remember this in the LastInGroupList list.
2030 if (last)
2031 LastInGroupList.push_back((Decl*)last);
2032}
2033
2034void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2035 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2036 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2037 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2038 if (!newType.isNull()) // install the new vector type into the decl
2039 vDecl->setType(newType);
2040 }
2041 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2042 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2043 rawAttr);
2044 if (!newType.isNull()) // install the new vector type into the decl
2045 tDecl->setUnderlyingType(newType);
2046 }
2047 }
2048 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroff82113e32007-07-29 16:33:31 +00002049 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2050 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2051 else
Chris Lattner4b009652007-07-25 00:24:17 +00002052 Diag(rawAttr->getAttributeLoc(),
2053 diag::err_typecheck_ocu_vector_not_typedef);
Chris Lattner4b009652007-07-25 00:24:17 +00002054 }
2055 // FIXME: add other attributes...
2056}
2057
2058void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2059 AttributeList *declarator_postfix) {
2060 while (declspec_prefix) {
2061 HandleDeclAttribute(New, declspec_prefix);
2062 declspec_prefix = declspec_prefix->getNext();
2063 }
2064 while (declarator_postfix) {
2065 HandleDeclAttribute(New, declarator_postfix);
2066 declarator_postfix = declarator_postfix->getNext();
2067 }
2068}
2069
Steve Naroff82113e32007-07-29 16:33:31 +00002070void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2071 AttributeList *rawAttr) {
2072 QualType curType = tDecl->getUnderlyingType();
Chris Lattner4b009652007-07-25 00:24:17 +00002073 // check the attribute arugments.
2074 if (rawAttr->getNumArgs() != 1) {
2075 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2076 std::string("1"));
Steve Naroff82113e32007-07-29 16:33:31 +00002077 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002078 }
2079 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2080 llvm::APSInt vecSize(32);
2081 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2082 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2083 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002084 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002085 }
2086 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2087 // in conjunction with complex types (pointers, arrays, functions, etc.).
2088 Type *canonType = curType.getCanonicalType().getTypePtr();
2089 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2090 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2091 curType.getCanonicalType().getAsString());
Steve Naroff82113e32007-07-29 16:33:31 +00002092 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002093 }
2094 // unlike gcc's vector_size attribute, the size is specified as the
2095 // number of elements, not the number of bytes.
Chris Lattner3496d522007-09-04 02:45:27 +00002096 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Chris Lattner4b009652007-07-25 00:24:17 +00002097
2098 if (vectorSize == 0) {
2099 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2100 sizeExpr->getSourceRange());
Steve Naroff82113e32007-07-29 16:33:31 +00002101 return;
Chris Lattner4b009652007-07-25 00:24:17 +00002102 }
Steve Naroff82113e32007-07-29 16:33:31 +00002103 // Instantiate/Install the vector type, the number of elements is > 0.
2104 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2105 // Remember this typedef decl, we will need it later for diagnostics.
2106 OCUVectorDecls.push_back(tDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002107}
2108
2109QualType Sema::HandleVectorTypeAttribute(QualType curType,
2110 AttributeList *rawAttr) {
2111 // check the attribute arugments.
2112 if (rawAttr->getNumArgs() != 1) {
2113 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2114 std::string("1"));
2115 return QualType();
2116 }
2117 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2118 llvm::APSInt vecSize(32);
2119 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2120 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2121 sizeExpr->getSourceRange());
2122 return QualType();
2123 }
2124 // navigate to the base type - we need to provide for vector pointers,
2125 // vector arrays, and functions returning vectors.
2126 Type *canonType = curType.getCanonicalType().getTypePtr();
2127
2128 if (canonType->isPointerType() || canonType->isArrayType() ||
2129 canonType->isFunctionType()) {
2130 assert(1 && "HandleVector(): Complex type construction unimplemented");
2131 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2132 do {
2133 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2134 canonType = PT->getPointeeType().getTypePtr();
2135 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2136 canonType = AT->getElementType().getTypePtr();
2137 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2138 canonType = FT->getResultType().getTypePtr();
2139 } while (canonType->isPointerType() || canonType->isArrayType() ||
2140 canonType->isFunctionType());
2141 */
2142 }
2143 // the base type must be integer or float.
2144 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2145 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2146 curType.getCanonicalType().getAsString());
2147 return QualType();
2148 }
Chris Lattner3496d522007-09-04 02:45:27 +00002149 unsigned typeSize = static_cast<unsigned>(
2150 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Chris Lattner4b009652007-07-25 00:24:17 +00002151 // vecSize is specified in bytes - convert to bits.
Chris Lattner3496d522007-09-04 02:45:27 +00002152 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Chris Lattner4b009652007-07-25 00:24:17 +00002153
2154 // the vector size needs to be an integral multiple of the type size.
2155 if (vectorSize % typeSize) {
2156 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2157 sizeExpr->getSourceRange());
2158 return QualType();
2159 }
2160 if (vectorSize == 0) {
2161 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2162 sizeExpr->getSourceRange());
2163 return QualType();
2164 }
2165 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2166 // the number of elements to be a power of two (unlike GCC).
2167 // Instantiate the vector type, the number of elements is > 0.
2168 return Context.getVectorType(curType, vectorSize/typeSize);
2169}
2170