blob: b827732b872cc9871815cdd07b23056079f83391 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Builtins.h"
17#include "clang/AST/Decl.h"
Steve Naroff980e5082007-10-01 19:00:59 +000018#include "clang/AST/DeclObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/Type.h"
21#include "clang/Parse/DeclSpec.h"
22#include "clang/Parse/Scope.h"
23#include "clang/Lex/IdentifierTable.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000026#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000028#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner5c0fa302007-09-30 08:31:00 +000032 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
33 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
34 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000035 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000036}
37
38void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000039 if (S->decl_empty()) return;
40 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
41
Reid Spencer5f016e22007-07-11 17:01:13 +000042 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
43 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000044 Decl *TmpD = static_cast<Decl*>(*I);
45 assert(TmpD && "This decl didn't get pushed??");
46 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
47 assert(D && "This decl isn't a ScopedDecl?");
48
Reid Spencer5f016e22007-07-11 17:01:13 +000049 IdentifierInfo *II = D->getIdentifier();
50 if (!II) continue;
51
52 // Unlink this decl from the identifier. Because the scope contains decls
53 // in an unordered collection, and because we have multiple identifier
54 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
55 if (II->getFETokenInfo<Decl>() == D) {
56 // Normal case, no multiple decls in different namespaces.
57 II->setFETokenInfo(D->getNext());
58 } else {
59 // Scan ahead. There are only three namespaces in C, so this loop can
60 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000061 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000062 while (SomeDecl->getNext() != D) {
63 SomeDecl = SomeDecl->getNext();
64 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
65 }
66 SomeDecl->setNext(D->getNext());
67 }
68
69 // This will have to be revisited for C++: there we want to nest stuff in
70 // namespace decls etc. Even for C, we might want a top-level translation
71 // unit decl or something.
72 if (!CurFunctionDecl)
73 continue;
74
75 // Chain this decl to the containing function, it now owns the memory for
76 // the decl.
77 D->setNext(CurFunctionDecl->getDeclChain());
78 CurFunctionDecl->setDeclChain(D);
79 }
80}
81
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000082/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000083/// return 0 if one not found.
Steve Naroff6a8a9a42007-10-02 20:01:56 +000084ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
85
86 // Scan up the scope chain looking for a decl that matches this identifier
87 // that is in the appropriate namespace. This search should not take long, as
88 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
89 ScopedDecl *IdDecl = NULL;
90 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
91 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
92 IdDecl = D;
93 break;
94 }
95 }
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000096 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
97 IdDecl = 0;
98 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
99}
100
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000101/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
102/// return 0 if one not found.
103ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000104 IdentifierInfo *Id,
105 SourceLocation IdLoc) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000106 // Note that Protocols have their own namespace.
107 ScopedDecl *PrDecl = LookupScopedDecl(Id, Decl::IDNS_Protocol,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000108 IdLoc, S);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000109 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
110 PrDecl = 0;
111 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
112}
113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114/// LookupScopedDecl - Look up the inner-most declaration in the specified
115/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000116ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
117 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 if (II == 0) return 0;
119 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
120
121 // Scan up the scope chain looking for a decl that matches this identifier
122 // that is in the appropriate namespace. This search should not take long, as
123 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000124 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 if (D->getIdentifierNamespace() == NS)
126 return D;
127
128 // If we didn't find a use of this identifier, and if the identifier
129 // corresponds to a compiler builtin, create the decl object for the builtin
130 // now, injecting it into translation unit scope, and return it.
131 if (NS == Decl::IDNS_Ordinary) {
132 // If this is a builtin on some other target, or if this builtin varies
133 // across targets (e.g. in type), emit a diagnostic and mark the translation
134 // unit non-portable for using it.
135 if (II->isNonPortableBuiltin()) {
136 // Only emit this diagnostic once for this builtin.
137 II->setNonPortableBuiltin(false);
138 Context.Target.DiagnoseNonPortability(IdLoc,
139 diag::port_target_builtin_use);
140 }
141 // If this is a builtin on this (or all) targets, create the decl.
142 if (unsigned BuiltinID = II->getBuiltinID())
143 return LazilyCreateBuiltin(II, BuiltinID, S);
144 }
145 return 0;
146}
147
148/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
149/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000150ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 Builtin::ID BID = (Builtin::ID)bid;
152
153 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
154 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000155 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000156
157 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000158 if (Scope *FnS = S->getFnParent())
159 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 while (S->getParent())
161 S = S->getParent();
162 S->AddDecl(New);
163
164 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000165 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 // Scan until we find the last (outermost) decl in the id chain.
167 while (LastDecl->getNext())
168 LastDecl = LastDecl->getNext();
169 // Insert before (outside) it.
170 LastDecl->setNext(New);
171 } else {
172 II->setFETokenInfo(New);
173 }
174 // Make sure clients iterating over decls see this.
175 LastInGroupList.push_back(New);
176
177 return New;
178}
179
180/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
181/// and scope as a previous declaration 'Old'. Figure out how to resolve this
182/// situation, merging decls or emitting diagnostics as appropriate.
183///
Steve Naroff8e74c932007-09-13 21:41:19 +0000184TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 // Verify the old decl was also a typedef.
186 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
187 if (!Old) {
188 Diag(New->getLocation(), diag::err_redefinition_different_kind,
189 New->getName());
190 Diag(OldD->getLocation(), diag::err_previous_definition);
191 return New;
192 }
193
194 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
195 // TODO: This is totally simplistic. It should handle merging functions
196 // together etc, merging extern int X; int X; ...
197 Diag(New->getLocation(), diag::err_redefinition, New->getName());
198 Diag(Old->getLocation(), diag::err_previous_definition);
199 return New;
200}
201
202/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
203/// and scope as a previous declaration 'Old'. Figure out how to resolve this
204/// situation, merging decls or emitting diagnostics as appropriate.
205///
Steve Naroff8e74c932007-09-13 21:41:19 +0000206FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 // Verify the old decl was also a function.
208 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
209 if (!Old) {
210 Diag(New->getLocation(), diag::err_redefinition_different_kind,
211 New->getName());
212 Diag(OldD->getLocation(), diag::err_previous_definition);
213 return New;
214 }
215
216 // This is not right, but it's a start. If 'Old' is a function prototype with
217 // the same type as 'New', silently allow this. FIXME: We should link up decl
218 // objects here.
219 if (Old->getBody() == 0 &&
220 Old->getCanonicalType() == New->getCanonicalType()) {
221 return New;
222 }
223
224 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
225 // TODO: This is totally simplistic. It should handle merging functions
226 // together etc, merging extern int X; int X; ...
227 Diag(New->getLocation(), diag::err_redefinition, New->getName());
228 Diag(Old->getLocation(), diag::err_previous_definition);
229 return New;
230}
231
232/// MergeVarDecl - We just parsed a variable 'New' which has the same name
233/// and scope as a previous declaration 'Old'. Figure out how to resolve this
234/// situation, merging decls or emitting diagnostics as appropriate.
235///
236/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
237/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
238///
Steve Naroff8e74c932007-09-13 21:41:19 +0000239VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000240 // Verify the old decl was also a variable.
241 VarDecl *Old = dyn_cast<VarDecl>(OldD);
242 if (!Old) {
243 Diag(New->getLocation(), diag::err_redefinition_different_kind,
244 New->getName());
245 Diag(OldD->getLocation(), diag::err_previous_definition);
246 return New;
247 }
Steve Narofffb22d962007-08-30 01:06:46 +0000248 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
249 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
250 bool OldIsTentative = false;
251
252 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
253 // Handle C "tentative" external object definitions. FIXME: finish!
254 if (!OldFSDecl->getInit() &&
255 (OldFSDecl->getStorageClass() == VarDecl::None ||
256 OldFSDecl->getStorageClass() == VarDecl::Static))
257 OldIsTentative = true;
258 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 // Verify the types match.
260 if (Old->getCanonicalType() != New->getCanonicalType()) {
261 Diag(New->getLocation(), diag::err_redefinition, New->getName());
262 Diag(Old->getLocation(), diag::err_previous_definition);
263 return New;
264 }
265 // We've verified the types match, now check if Old is "extern".
266 if (Old->getStorageClass() != VarDecl::Extern) {
267 Diag(New->getLocation(), diag::err_redefinition, New->getName());
268 Diag(Old->getLocation(), diag::err_previous_definition);
269 }
270 return New;
271}
272
273/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
274/// no declarator (e.g. "struct foo;") is parsed.
275Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
276 // TODO: emit error on 'int;' or 'const enum foo;'.
277 // TODO: emit error on 'typedef int;'
278 // if (!DS.isMissingDeclaratorOk()) Diag(...);
279
280 return 0;
281}
282
Steve Naroff9e8925e2007-09-04 14:36:54 +0000283bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000284 AssignmentCheckResult result;
285 SourceLocation loc = Init->getLocStart();
286 // Get the type before calling CheckSingleAssignmentConstraints(), since
287 // it can promote the expression.
288 QualType rhsType = Init->getType();
289
290 result = CheckSingleAssignmentConstraints(DeclType, Init);
291
292 // decode the result (notice that extensions still return a type).
293 switch (result) {
294 case Compatible:
295 break;
296 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000297 // FIXME: tighten up this check which should allow:
298 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
299 if (rhsType == Context.getPointerType(Context.CharTy))
300 break;
Steve Narofff0090632007-09-02 02:04:30 +0000301 Diag(loc, diag::err_typecheck_assign_incompatible,
302 DeclType.getAsString(), rhsType.getAsString(),
303 Init->getSourceRange());
304 return true;
305 case PointerFromInt:
306 // check for null pointer constant (C99 6.3.2.3p3)
307 if (!Init->isNullPointerConstant(Context)) {
308 Diag(loc, diag::ext_typecheck_assign_pointer_int,
309 DeclType.getAsString(), rhsType.getAsString(),
310 Init->getSourceRange());
311 return true;
312 }
313 break;
314 case IntFromPointer:
315 Diag(loc, diag::ext_typecheck_assign_pointer_int,
316 DeclType.getAsString(), rhsType.getAsString(),
317 Init->getSourceRange());
318 break;
319 case IncompatiblePointer:
320 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
321 DeclType.getAsString(), rhsType.getAsString(),
322 Init->getSourceRange());
323 break;
324 case CompatiblePointerDiscardsQualifiers:
325 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
326 DeclType.getAsString(), rhsType.getAsString(),
327 Init->getSourceRange());
328 break;
329 }
330 return false;
331}
332
Steve Naroff9e8925e2007-09-04 14:36:54 +0000333bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
334 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000335 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000336 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000337
338 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
339 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
340 return true;
341 } else if (CheckSingleInitializer(expr, ElementType)) {
342 return true; // types weren't compatible.
343 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000344 if (savExpr != expr) // The type was promoted, update initializer list.
345 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000346 return false;
347}
348
349void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
350 QualType ElementType, bool isStatic,
351 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000352 for (unsigned i = 0; i < IList->getNumInits(); i++) {
353 Expr *expr = IList->getInit(i);
354
Steve Naroff371227d2007-09-04 02:20:04 +0000355 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
356 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000357 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000358 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
359 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000360 }
Steve Naroff371227d2007-09-04 02:20:04 +0000361 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000362 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000363 }
Steve Naroff371227d2007-09-04 02:20:04 +0000364 nInitializers++;
365 }
366 return;
367}
368
369// FIXME: Doesn't deal with arrays of structures yet.
370void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
371 QualType ElementType, bool isStatic,
372 int &totalInits, bool &hadError) {
373 int maxElementsAtThisLevel = 0;
374 int nInitsAtLevel = 0;
375
376 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
377 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000378 maxElementsAtThisLevel = CAT->getMaximumElements();
379 // Set DeclType, used below to recurse (for multi-dimensional arrays).
380 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000381 } else if (DeclType->isScalarType()) {
382 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
383 IList->getSourceRange());
384 maxElementsAtThisLevel = 1;
385 }
386 // The empty init list "{ }" is treated specially below.
387 unsigned numInits = IList->getNumInits();
388 if (numInits) {
389 for (unsigned i = 0; i < numInits; i++) {
390 Expr *expr = IList->getInit(i);
391
392 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
393 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
394 totalInits, hadError);
395 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000396 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000397 nInitsAtLevel++; // increment the number of initializers at this level.
398 totalInits--; // decrement the total number of initializers.
399
400 // Check if we have space for another initializer.
401 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
402 Diag(expr->getLocStart(), diag::warn_excess_initializers,
403 expr->getSourceRange());
404 }
405 }
406 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
407 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
408 } else {
409 // we have an initializer list with no elements.
410 totalInits -= maxElementsAtThisLevel;
411 if (totalInits < 0)
412 Diag(IList->getLocStart(), diag::warn_excess_initializers,
413 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000414 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000415 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000416}
417
Steve Naroff9e8925e2007-09-04 14:36:54 +0000418bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000419 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000420 if (!InitList)
421 return CheckSingleInitializer(Init, DeclType);
422
Steve Narofff0090632007-09-02 02:04:30 +0000423 // We have an InitListExpr, make sure we set the type.
424 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000425
426 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000427
Steve Naroff38374b02007-09-02 20:30:18 +0000428 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
429 // of unknown size ("[]") or an object type that is not a variable array type.
430 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
431 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000432 if (expr)
433 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
434 expr->getSourceRange());
435
Steve Naroff7cf8c442007-09-04 21:13:33 +0000436 // We have a VariableArrayType with unknown size. Note that only the first
437 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000438 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000439 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
440 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000441 if (!hadError) {
442 // Return a new array type from the number of initializers (C99 6.7.8p22).
443 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000444 ConstVal = numInits;
445 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000446 ArrayType::Normal, 0);
447 }
448 return hadError;
449 }
450 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000451 int maxElements = CAT->getMaximumElements();
452 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
453 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000454 return hadError;
455 }
Steve Naroff371227d2007-09-04 02:20:04 +0000456 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
457 int maxElements = 1;
458 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
459 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000460 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000461 }
462 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000463 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000464}
465
Reid Spencer5f016e22007-07-11 17:01:13 +0000466Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000467Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000468 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 IdentifierInfo *II = D.getIdentifier();
470
Chris Lattnere80a59c2007-07-25 00:24:17 +0000471 // All of these full declarators require an identifier. If it doesn't have
472 // one, the ParsedFreeStandingDeclSpec action should be used.
473 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000474 Diag(D.getDeclSpec().getSourceRange().Begin(),
475 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000476 D.getDeclSpec().getSourceRange(), D.getSourceRange());
477 return 0;
478 }
479
Chris Lattner31e05722007-08-26 06:24:45 +0000480 // The scope passed in may not be a decl scope. Zip up the scope tree until
481 // we find one that is.
482 while ((S->getFlags() & Scope::DeclScope) == 0)
483 S = S->getParent();
484
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000486 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
487 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 if (PrevDecl && !S->isDeclScope(PrevDecl))
489 PrevDecl = 0; // If in outer scope, it isn't the same thing.
490
Steve Naroffc752d042007-09-13 18:10:37 +0000491 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000492 bool InvalidDecl = false;
493
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
495 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
496 if (!NewTD) return 0;
497
498 // Handle attributes prior to checking for duplicates in MergeVarDecl
499 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
500 D.getAttributes());
501 // Merge the decl with the existing one if appropriate.
502 if (PrevDecl) {
503 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
504 if (NewTD == 0) return 0;
505 }
506 New = NewTD;
507 if (S->getParent() == 0) {
508 // C99 6.7.7p2: If a typedef name specifies a variably modified type
509 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000510 if (const VariableArrayType *VAT =
511 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
512 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
513 VAT->getSizeExpr()->getSourceRange());
514 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 }
516 }
517 } else if (D.isFunctionDeclarator()) {
518 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000519 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000520
Chris Lattner271f1a62007-09-27 15:15:46 +0000521 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 switch (D.getDeclSpec().getStorageClassSpec()) {
523 default: assert(0 && "Unknown storage class!");
524 case DeclSpec::SCS_auto:
525 case DeclSpec::SCS_register:
526 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
527 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000528 InvalidDecl = true;
529 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
531 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
532 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
533 }
534
535 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000536 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 LastDeclarator);
538
539 // Merge the decl with the existing one if appropriate.
540 if (PrevDecl) {
541 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
542 if (NewFD == 0) return 0;
543 }
544 New = NewFD;
545 } else {
546 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000547 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000548
549 VarDecl *NewVD;
550 VarDecl::StorageClass SC;
551 switch (D.getDeclSpec().getStorageClassSpec()) {
552 default: assert(0 && "Unknown storage class!");
553 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
554 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
555 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
556 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
557 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
558 }
559 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 // C99 6.9p2: The storage-class specifiers auto and register shall not
561 // appear in the declaration specifiers in an external declaration.
562 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
563 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
564 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000565 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000568 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000570 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 // Handle attributes prior to checking for duplicates in MergeVarDecl
572 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
573 D.getAttributes());
574
575 // Merge the decl with the existing one if appropriate.
576 if (PrevDecl) {
577 NewVD = MergeVarDecl(NewVD, PrevDecl);
578 if (NewVD == 0) return 0;
579 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 New = NewVD;
581 }
582
583 // If this has an identifier, add it to the scope stack.
584 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000585 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 II->setFETokenInfo(New);
587 S->AddDecl(New);
588 }
589
590 if (S->getParent() == 0)
591 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000592
593 // If any semantic error occurred, mark the decl as invalid.
594 if (D.getInvalidType() || InvalidDecl)
595 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000596
597 return New;
598}
599
Steve Naroffbb204692007-09-12 14:07:44 +0000600void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000601 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000602 Expr *Init = static_cast<Expr *>(init);
603
Steve Naroff410e3e22007-09-12 20:13:48 +0000604 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000605
Steve Naroff410e3e22007-09-12 20:13:48 +0000606 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
607 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000608 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
609 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000610 RealDecl->setInvalidDecl();
611 return;
612 }
Steve Naroffbb204692007-09-12 14:07:44 +0000613 // Get the decls type and save a reference for later, since
614 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000615 QualType DclT = VDecl->getType(), SavT = DclT;
616 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000617 VarDecl::StorageClass SC = BVD->getStorageClass();
618 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000619 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000620 BVD->setInvalidDecl();
621 } else if (!BVD->isInvalidDecl()) {
622 CheckInitializer(Init, DclT, SC == VarDecl::Static);
623 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000624 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000625 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000626 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000627 if (!FVD->isInvalidDecl())
628 CheckInitializer(Init, DclT, true);
629 }
630 // If the type changed, it means we had an incomplete type that was
631 // completed by the initializer. For example:
632 // int ary[] = { 1, 3, 5 };
633 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000634 if (!VDecl->isInvalidDecl() && (DclT != SavT))
635 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000636
637 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000638 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000639 return;
640}
641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642/// The declarators are chained together backwards, reverse the list.
643Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
644 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000645 Decl *GroupDecl = static_cast<Decl*>(group);
646 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000647 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000648
649 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
650 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000651 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000653 else { // reverse the list.
654 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000655 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000656 Group->setNextDeclarator(NewGroup);
657 NewGroup = Group;
658 Group = Next;
659 }
660 }
661 // Perform semantic analysis that depends on having fully processed both
662 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000663 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000664 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
665 if (!IDecl)
666 continue;
667 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
668 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
669 QualType T = IDecl->getType();
670
671 // C99 6.7.5.2p2: If an identifier is declared to be an object with
672 // static storage duration, it shall not have a variable length array.
673 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
674 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
675 if (VLA->getSizeExpr()) {
676 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
677 IDecl->setInvalidDecl();
678 }
679 }
680 }
681 // Block scope. C99 6.7p7: If an identifier for an object is declared with
682 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
683 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
684 if (T->isIncompleteType()) {
685 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
686 T.getAsString());
687 IDecl->setInvalidDecl();
688 }
689 }
690 // File scope. C99 6.9.2p2: A declaration of an identifier for and
691 // object that has file scope without an initializer, and without a
692 // storage-class specifier or with the storage-class specifier "static",
693 // constitutes a tentative definition. Note: A tentative definition with
694 // external linkage is valid (C99 6.2.2p5).
695 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
696 // C99 6.9.2p3: If the declaration of an identifier for an object is
697 // a tentative definition and has internal linkage (C99 6.2.2p3), the
698 // declared type shall not be an incomplete type.
699 if (T->isIncompleteType()) {
700 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
701 T.getAsString());
702 IDecl->setInvalidDecl();
703 }
704 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 }
706 return NewGroup;
707}
Steve Naroffe1223f72007-08-28 03:03:08 +0000708
709// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000710ParmVarDecl *
711Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
712 Scope *FnScope) {
713 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
714
715 IdentifierInfo *II = PI.Ident;
716 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
717 // Can this happen for params? We already checked that they don't conflict
718 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000719 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000720 PI.IdentLoc, FnScope)) {
721
722 }
723
724 // FIXME: Handle storage class (auto, register). No declarator?
725 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000726
727 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
728 // Doing the promotion here has a win and a loss. The win is the type for
729 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
730 // code generator). The loss is the orginal type isn't preserved. For example:
731 //
732 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
733 // int blockvardecl[5];
734 // sizeof(parmvardecl); // size == 4
735 // sizeof(blockvardecl); // size == 20
736 // }
737 //
738 // For expressions, all implicit conversions are captured using the
739 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
740 //
741 // FIXME: If a source translation tool needs to see the original type, then
742 // we need to consider storing both types (in ParmVarDecl)...
743 //
744 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
745 if (const ArrayType *AT = parmDeclType->getAsArrayType())
746 parmDeclType = Context.getPointerType(AT->getElementType());
747 else if (parmDeclType->isFunctionType())
748 parmDeclType = Context.getPointerType(parmDeclType);
749
750 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000751 VarDecl::None, 0);
752 if (PI.InvalidType)
753 New->setInvalidDecl();
754
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 // If this has an identifier, add it to the scope stack.
756 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000757 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000758 II->setFETokenInfo(New);
759 FnScope->AddDecl(New);
760 }
761
762 return New;
763}
764
765
766Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
767 assert(CurFunctionDecl == 0 && "Function parsing confused");
768 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
769 "Not a function declarator!");
770 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
771
772 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
773 // for a K&R function.
774 if (!FTI.hasPrototype) {
775 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
776 if (FTI.ArgInfo[i].TypeInfo == 0) {
777 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
778 FTI.ArgInfo[i].Ident->getName());
779 // Implicitly declare the argument as type 'int' for lack of a better
780 // type.
781 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
782 }
783 }
784
785 // Since this is a function definition, act as though we have information
786 // about the arguments.
787 FTI.hasPrototype = true;
788 } else {
789 // FIXME: Diagnose arguments without names in C.
790
791 }
792
793 Scope *GlobalScope = FnBodyScope->getParent();
794
795 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000796 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000797 CurFunctionDecl = FD;
798
799 // Create Decl objects for each parameter, adding them to the FunctionDecl.
800 llvm::SmallVector<ParmVarDecl*, 16> Params;
801
802 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
803 // no arguments, not a function that takes a single void argument.
804 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
805 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
806 // empty arg list, don't push any params.
807 } else {
808 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
809 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
810 }
811
812 FD->setParams(&Params[0], Params.size());
813
814 return FD;
815}
816
817Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
818 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
819 FD->setBody((Stmt*)Body);
820
821 assert(FD == CurFunctionDecl && "Function parsing confused");
822 CurFunctionDecl = 0;
823
824 // Verify and clean out per-function state.
825
826 // Check goto/label use.
827 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
828 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
829 // Verify that we have no forward references left. If so, there was a goto
830 // or address of a label taken, but no definition of it. Label fwd
831 // definitions are indicated with a null substmt.
832 if (I->second->getSubStmt() == 0) {
833 LabelStmt *L = I->second;
834 // Emit error.
835 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
836
837 // At this point, we have gotos that use the bogus label. Stitch it into
838 // the function body so that they aren't leaked and that the AST is well
839 // formed.
840 L->setSubStmt(new NullStmt(L->getIdentLoc()));
841 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
842 }
843 }
844 LabelMap.clear();
845
846 return FD;
847}
848
849
850/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
851/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000852ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
853 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 if (getLangOptions().C99) // Extension in C99.
855 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
856 else // Legal in C90, but warn about it.
857 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
858
859 // FIXME: handle stuff like:
860 // void foo() { extern float X(); }
861 // void bar() { X(); } <-- implicit decl for X in another scope.
862
863 // Set a Declarator for the implicit definition: int foo();
864 const char *Dummy;
865 DeclSpec DS;
866 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
867 Error = Error; // Silence warning.
868 assert(!Error && "Error setting up implicit decl!");
869 Declarator D(DS, Declarator::BlockContext);
870 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
871 D.SetIdentifier(&II, Loc);
872
873 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000874 if (Scope *FnS = S->getFnParent())
875 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 while (S->getParent())
877 S = S->getParent();
878
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000879 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000880}
881
882
883TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000884 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
886
887 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000888 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
890 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000891 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
892 T, LastDeclarator);
893 if (D.getInvalidType())
894 NewTD->setInvalidDecl();
895 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896}
897
Steve Naroff3a165b02007-10-03 21:00:46 +0000898Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000899 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000900 IdentifierInfo *ClassName, SourceLocation ClassLoc,
901 IdentifierInfo *SuperName, SourceLocation SuperLoc,
902 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
903 AttributeList *AttrList) {
904 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000905
906 // Check for another declaration kind with the same name.
907 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
908 ClassLoc, S);
909 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
910 && !isa<ObjcProtocolDecl>(PrevDecl)) {
911 Diag(ClassLoc, diag::err_redefinition_different_kind,
912 ClassName->getName());
913 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
914 }
915
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000916 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000917 if (IDecl) {
918 // Class already seen. Is it a forward declaration?
Steve Naroff768f26e2007-10-02 20:26:23 +0000919 if (!IDecl->isForwardDecl())
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000920 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000921 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000922 IDecl->setForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000923 IDecl->AllocIntfRefProtocols(NumProtocols);
924 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000925 }
926 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000927 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000928
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000929 // Chain & install the interface decl into the identifier.
930 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
931 ClassName->setFETokenInfo(IDecl);
932 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000933
934 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000935 ObjcInterfaceDecl* SuperClassEntry = 0;
936 // Check if a different kind of symbol declared in this scope.
937 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
938 SuperLoc, S);
939 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
940 && !isa<ObjcProtocolDecl>(PrevDecl)) {
941 Diag(SuperLoc, diag::err_redefinition_different_kind,
942 SuperName->getName());
943 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000944 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000945 else {
946 // Check that super class is previously defined
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000947 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000948
Steve Naroff768f26e2007-10-02 20:26:23 +0000949 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000950 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
951 ClassName->getName());
952 }
953 }
954 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000955 }
956
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000957 /// Check then save referenced protocols
958 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000959 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000960 ClassLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +0000961 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000962 Diag(ClassLoc, diag::err_undef_protocolref,
963 ProtocolNames[i]->getName(),
964 ClassName->getName());
965 IDecl->setIntfRefProtocols((int)i, RefPDecl);
966 }
967
Steve Naroff3536b442007-09-06 21:24:23 +0000968 return IDecl;
969}
970
Steve Naroff3a165b02007-10-03 21:00:46 +0000971Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000972 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000973 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
974 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
975 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000976 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000977 if (PDecl) {
978 // Protocol already seen. Better be a forward protocol declaration
Steve Naroff768f26e2007-10-02 20:26:23 +0000979 if (!PDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000980 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
981 ProtocolName->getName());
982 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000983 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000984 PDecl->AllocReferencedProtocols(NumProtoRefs);
985 }
986 }
987 else {
988 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
989 ProtocolName);
Steve Naroff768f26e2007-10-02 20:26:23 +0000990 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000991 // Chain & install the protocol decl into the identifier.
992 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
993 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000994 }
995
996 /// Check then save referenced protocols
997 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000998 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000999 ProtocolLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001000 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001001 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001002 ProtoRefNames[i]->getName(),
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001003 ProtocolName->getName());
1004 PDecl->setReferencedProtocols((int)i, RefPDecl);
1005 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001006
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001007 return PDecl;
1008}
1009
Steve Naroff37e58d12007-10-02 22:39:18 +00001010/// ActOnForwardProtocolDeclaration -
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001011/// Scope will always be top level file scope.
1012Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001013Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001014 IdentifierInfo **IdentList, unsigned NumElts) {
1015 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
1016 NumElts);
1017
1018 for (unsigned i = 0; i != NumElts; ++i) {
1019 ObjcProtocolDecl *PDecl;
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001020 PDecl = getObjCProtocolDecl(S, IdentList[i], AtProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001021 if (!PDecl) {// Already seen?
1022 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1023 // Chain & install the protocol decl into the identifier.
1024 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1025 IdentList[i]->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001026 }
1027 // Remember that this needs to be removed when the scope is popped.
1028 S->AddDecl(IdentList[i]);
1029
1030 FDecl->setForwardProtocolDecl((int)i, PDecl);
1031 }
1032 return FDecl;
1033}
1034
Steve Naroff3a165b02007-10-03 21:00:46 +00001035Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001036 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001037 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1038 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1039 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1040 ObjcCategoryDecl *CDecl;
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001041 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian60199032007-10-02 17:36:55 +00001042 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001043 CDecl->setClassInterface(IDecl);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001044
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001045 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001046 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001047 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1048 else {
1049 /// Check for duplicate interface declaration for this category
1050 ObjcCategoryDecl *CDeclChain;
1051 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1052 CDeclChain = CDeclChain->getNextClassCategory()) {
1053 if (CDeclChain->getCatName() == CategoryName) {
1054 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1055 CategoryName->getName());
1056 break;
1057 }
1058 }
1059 if (!CDeclChain) {
1060 CDecl->setCatName(CategoryName);
1061 CDecl->insertNextClassCategory();
1062 }
1063 }
1064
1065 /// Check then save referenced protocols
1066 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001067 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001068 CategoryLoc);
Steve Naroff768f26e2007-10-02 20:26:23 +00001069 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001070 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001071 ProtoRefNames[i]->getName(),
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001072 CategoryName->getName());
1073 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1074 }
1075
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001076 return CDecl;
1077}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001078
Steve Naroff3a165b02007-10-03 21:00:46 +00001079/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001080/// category implementation declaration and build an ObjcCategoryImplDecl
1081/// object.
Steve Naroff3a165b02007-10-03 21:00:46 +00001082Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001083 SourceLocation AtCatImplLoc,
1084 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1085 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001086 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001087 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
1088 ClassName, IDecl,
1089 CatName);
1090 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001091 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001092 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1093 /// TODO: Check that CatName, category name, is not used in another
1094 // implementation.
1095 return CDecl;
1096}
1097
Steve Naroff3a165b02007-10-03 21:00:46 +00001098Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001099 SourceLocation AtClassImplLoc,
1100 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1101 IdentifierInfo *SuperClassname,
1102 SourceLocation SuperClassLoc) {
1103 ObjcInterfaceDecl* IDecl = 0;
1104 // Check for another declaration kind with the same name.
1105 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1106 ClassLoc, S);
1107 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1108 Diag(ClassLoc, diag::err_redefinition_different_kind,
1109 ClassName->getName());
1110 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1111 }
1112 else {
1113 // Is there an interface declaration of this class; if not, warn!
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001114 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001115 if (!IDecl)
1116 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1117 }
1118
1119 // Check that super class name is valid class name
1120 ObjcInterfaceDecl* SDecl = 0;
1121 if (SuperClassname) {
1122 // Check if a different kind of symbol declared in this scope.
1123 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1124 SuperClassLoc, S);
1125 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1126 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1127 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1128 SuperClassname->getName());
1129 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1130 }
1131 else {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001132 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001133 if (!SDecl)
1134 Diag(SuperClassLoc, diag::err_undef_superclass,
1135 SuperClassname->getName(), ClassName->getName());
1136 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1137 // This implementation and its interface do not have the same
1138 // super class.
1139 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1140 SuperClassname->getName());
1141 Diag(SDecl->getLocation(), diag::err_previous_definition);
1142 }
1143 }
1144 }
1145
1146 ObjcImplementationDecl* IMPDecl =
1147 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001148 if (!IDecl) {
1149 // Legacy case of @implementation with no corresponding @interface.
1150 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001151 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001152 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1153 ClassName->setFETokenInfo(IDecl);
1154
1155 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001156
1157 // Check that there is no duplicate implementation of this class.
1158 bool err = false;
1159 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1160 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1161 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1162 err = true;
1163 break;
1164 }
1165 }
1166 if (!err)
1167 Context.setObjcImplementationClass(IMPDecl);
1168
1169 return IMPDecl;
1170}
1171
Steve Naroffa5997c42007-10-02 21:43:37 +00001172void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1173 ObjcIvarDecl **ivars, unsigned numIvars) {
1174 assert(ImpDecl && "missing implementation decl");
1175 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001176 /// 2nd check is added to accomodate case of non-existing @interface decl.
1177 /// (legacy objective-c @implementation decl without an @interface decl).
1178 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroffa5997c42007-10-02 21:43:37 +00001179 return;
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001180 assert(ivars && "missing @implementation ivars");
1181
Steve Naroffa5997c42007-10-02 21:43:37 +00001182 // Check interface's Ivar list against those in the implementation.
1183 // names and types must match.
1184 //
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001185 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1186 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1187 unsigned j = 0;
1188 bool err = false;
1189 while (numIvars > 0 && IntfNumIvars > 0) {
1190 ObjcIvarDecl* ImplIvar = ivars[j];
1191 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1192 assert (ImplIvar && "missing implementation ivar");
1193 assert (ClsIvar && "missing class ivar");
1194 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1195 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1196 ImplIvar->getIdentifier()->getName());
1197 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1198 ClsIvar->getIdentifier()->getName());
1199 }
1200 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1201 // as error.
1202 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1203 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1204 ImplIvar->getIdentifier()->getName());
1205 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1206 ClsIvar->getIdentifier()->getName());
1207 err = true;
1208 break;
1209 }
1210 --numIvars;
1211 --IntfNumIvars;
1212 }
1213 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1214 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1215 diag::err_inconsistant_ivar);
1216
1217}
1218
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001219/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1220/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001221void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001222 bool& IncompleteImpl,
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001223 const llvm::DenseSet<void *>& InsMap,
Chris Lattner85994262007-10-05 20:15:24 +00001224 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001225 // check unimplemented instance methods.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001226 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001227 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
1228 void * cpv = methods[j]->getSelector().getAsOpaquePtr();
1229 if (!InsMap.count(cpv)) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001230 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001231 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1232 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001233 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001234 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001235 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001236 // check unimplemented class methods
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001237 methods = PDecl->getClassMethods();
1238 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001239 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001240 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001241 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1242 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001243 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001244 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001245
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001246 // Check on this protocols's referenced protocols, recursively
1247 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1248 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001249 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001250}
1251
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001252void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1253 ObjcInterfaceDecl* IDecl) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001254 llvm::DenseSet<void *> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001255 // Check and see if instance methods in class interface have been
1256 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001257 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001258 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
1259 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001260
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001261 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001262 methods = IDecl->getInstanceMethods();
1263 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001264 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001265 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001266 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1267 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001268 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001269 }
Chris Lattner85994262007-10-05 20:15:24 +00001270 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001271 // Check and see if class methods in class interface have been
1272 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001273 methods = IMPDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001274 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001275 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001276
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001277 methods = IDecl->getClassMethods();
1278 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001279 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001280 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001281 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1282 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001283 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001284 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001285
1286 // Check the protocol list for unimplemented methods in the @implementation
1287 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001288 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner85994262007-10-05 20:15:24 +00001289 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1290 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1291
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001292 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001293 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1294 IMPDecl->getName());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001295}
1296
1297/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1298/// category interface is implemented in the category @implementation.
1299void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1300 ObjcCategoryDecl *CatClassDecl) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001301 llvm::DenseSet<void *> InsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001302 // Check and see if instance methods in category interface have been
1303 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001304 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001305 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
1306 InsMap.insert(methods[i]->getSelector().getAsOpaquePtr());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001307
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001308 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001309 methods = CatClassDecl->getInstanceMethods();
1310 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001311 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
1312 llvm::SmallString<128> buf;
1313 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1314 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001315 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001316 }
Chris Lattner85994262007-10-05 20:15:24 +00001317 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001318 // Check and see if class methods in category interface have been
1319 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001320 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001321 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001322 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001323
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001324 methods = CatClassDecl->getClassMethods();
1325 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001326 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001327 llvm::SmallString<128> buf;
1328 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1329 methods[j]->getSelector().getName(buf));
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001330 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001331 }
1332
1333 // Check the protocol list for unimplemented methods in the @implementation
1334 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001335 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1336 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001337 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001338 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001339 }
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001340 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001341 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001342 CatClassDecl->getCatName()->getName());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001343}
1344
Steve Naroff37e58d12007-10-02 22:39:18 +00001345/// ActOnForwardClassDeclaration -
Steve Naroff3536b442007-09-06 21:24:23 +00001346/// Scope will always be top level file scope.
1347Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001348Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1349 IdentifierInfo **IdentList, unsigned NumElts)
1350{
Steve Naroff3536b442007-09-06 21:24:23 +00001351 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1352
1353 for (unsigned i = 0; i != NumElts; ++i) {
1354 ObjcInterfaceDecl *IDecl;
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001355 IDecl = getObjCInterfaceDecl(IdentList[i]);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001356 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001357 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001358 // Chain & install the interface decl into the identifier.
1359 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1360 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001361 }
Steve Naroff3536b442007-09-06 21:24:23 +00001362 // Remember that this needs to be removed when the scope is popped.
1363 S->AddDecl(IdentList[i]);
1364
1365 CDecl->setInterfaceDecl((int)i, IDecl);
1366 }
1367 return CDecl;
1368}
1369
Reid Spencer5f016e22007-07-11 17:01:13 +00001370
Steve Naroff08d92e42007-09-15 18:49:24 +00001371/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001372/// former case, Name will be non-null. In the later case, Name will be null.
1373/// TagType indicates what kind of tag this is. TK indicates whether this is a
1374/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001375Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 SourceLocation KWLoc, IdentifierInfo *Name,
1377 SourceLocation NameLoc, AttributeList *Attr) {
1378 // If this is a use of an existing tag, it must have a name.
1379 assert((Name != 0 || TK == TK_Definition) &&
1380 "Nameless record must be a definition!");
1381
1382 Decl::Kind Kind;
1383 switch (TagType) {
1384 default: assert(0 && "Unknown tag type!");
1385 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1386 case DeclSpec::TST_union: Kind = Decl::Union; break;
1387//case DeclSpec::TST_class: Kind = Decl::Class; break;
1388 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1389 }
1390
1391 // If this is a named struct, check to see if there was a previous forward
1392 // declaration or definition.
1393 if (TagDecl *PrevDecl =
1394 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1395 NameLoc, S))) {
1396
1397 // If this is a use of a previous tag, or if the tag is already declared in
1398 // the same scope (so that the definition/declaration completes or
1399 // rementions the tag), reuse the decl.
1400 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1401 // Make sure that this wasn't declared as an enum and now used as a struct
1402 // or something similar.
1403 if (PrevDecl->getKind() != Kind) {
1404 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1405 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1406 }
1407
1408 // If this is a use or a forward declaration, we're good.
1409 if (TK != TK_Definition)
1410 return PrevDecl;
1411
1412 // Diagnose attempts to redefine a tag.
1413 if (PrevDecl->isDefinition()) {
1414 Diag(NameLoc, diag::err_redefinition, Name->getName());
1415 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1416 // If this is a redefinition, recover by making this struct be
1417 // anonymous, which will make any later references get the previous
1418 // definition.
1419 Name = 0;
1420 } else {
1421 // Okay, this is definition of a previously declared or referenced tag.
1422 // Move the location of the decl to be the definition site.
1423 PrevDecl->setLocation(NameLoc);
1424 return PrevDecl;
1425 }
1426 }
1427 // If we get here, this is a definition of a new struct type in a nested
1428 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1429 // type.
1430 }
1431
1432 // If there is an identifier, use the location of the identifier as the
1433 // location of the decl, otherwise use the location of the struct/union
1434 // keyword.
1435 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1436
1437 // Otherwise, if this is the first time we've seen this tag, create the decl.
1438 TagDecl *New;
1439 switch (Kind) {
1440 default: assert(0 && "Unknown tag kind!");
1441 case Decl::Enum:
1442 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1443 // enum X { A, B, C } D; D should chain to X.
1444 New = new EnumDecl(Loc, Name, 0);
1445 // If this is an undefined enum, warn.
1446 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1447 break;
1448 case Decl::Union:
1449 case Decl::Struct:
1450 case Decl::Class:
1451 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1452 // struct X { int A; } D; D should chain to X.
1453 New = new RecordDecl(Kind, Loc, Name, 0);
1454 break;
1455 }
1456
1457 // If this has an identifier, add it to the scope stack.
1458 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001459 // The scope passed in may not be a decl scope. Zip up the scope tree until
1460 // we find one that is.
1461 while ((S->getFlags() & Scope::DeclScope) == 0)
1462 S = S->getParent();
1463
1464 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001465 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001466 Name->setFETokenInfo(New);
1467 S->AddDecl(New);
1468 }
1469
1470 return New;
1471}
1472
Steve Naroff08d92e42007-09-15 18:49:24 +00001473/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001474/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001475Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 SourceLocation DeclStart,
1477 Declarator &D, ExprTy *BitfieldWidth) {
1478 IdentifierInfo *II = D.getIdentifier();
1479 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 SourceLocation Loc = DeclStart;
1481 if (II) Loc = D.getIdentifierLoc();
1482
1483 // FIXME: Unnamed fields can be handled in various different ways, for
1484 // example, unnamed unions inject all members into the struct namespace!
1485
1486
1487 if (BitWidth) {
1488 // TODO: Validate.
1489 //printf("WARNING: BITFIELDS IGNORED!\n");
1490
1491 // 6.7.2.1p3
1492 // 6.7.2.1p4
1493
1494 } else {
1495 // Not a bitfield.
1496
1497 // validate II.
1498
1499 }
1500
1501 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001502 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1503 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001504
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1506 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001507 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1508 Diag(Loc, diag::err_typecheck_illegal_vla,
1509 VAT->getSizeExpr()->getSourceRange());
1510 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001513 FieldDecl *NewFD;
1514
1515 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001516 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001517 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001518 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001519 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001520 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001521 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001522
Steve Naroff5912a352007-08-28 20:14:24 +00001523 if (D.getInvalidType() || InvalidDecl)
1524 NewFD->setInvalidDecl();
1525 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001526}
1527
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001528/// TranslateIvarVisibility - Translate visibility from a token ID to an
1529/// AST enum value.
1530static ObjcIvarDecl::AccessControl
1531TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001532 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001533 case tok::objc_private: return ObjcIvarDecl::Private;
1534 case tok::objc_public: return ObjcIvarDecl::Public;
1535 case tok::objc_protected: return ObjcIvarDecl::Protected;
1536 case tok::objc_package: return ObjcIvarDecl::Package;
1537 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001538 }
1539}
1540
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001541void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001542 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001543 DeclTy **Fields, unsigned NumFields,
1544 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001545 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1546 assert(EnclosingDecl && "missing record or interface decl");
1547 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1548
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001549 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001550 // Diagnose code like:
1551 // struct S { struct S {} X; };
1552 // We discover this when we complete the outer S. Reject and ignore the
1553 // outer S.
1554 Diag(Record->getLocation(), diag::err_nested_redefinition,
1555 Record->getKindName());
1556 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001557 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001558 return;
1559 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 // Verify that all the fields are okay.
1561 unsigned NumNamedMembers = 0;
1562 llvm::SmallVector<FieldDecl*, 32> RecFields;
1563 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001566
Steve Naroff74216642007-09-14 22:20:54 +00001567 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1568 assert(FD && "missing field decl");
1569
1570 // Remember all fields.
1571 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001572
1573 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001574 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001575
Steve Narofff13271f2007-09-14 23:09:53 +00001576 // If we have visibility info, make sure the AST is set accordingly.
1577 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001578 cast<ObjcIvarDecl>(FD)->setAccessControl(
1579 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001582 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001583 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001584 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001585 FD->setInvalidDecl();
1586 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 continue;
1588 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1590 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001591 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001592 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001593 FD->setInvalidDecl();
1594 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001595 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001596 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 if (i != NumFields-1 || // ... that the last member ...
1598 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001599 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001601 FD->setInvalidDecl();
1602 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001603 continue;
1604 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001605 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1607 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001608 FD->setInvalidDecl();
1609 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001610 continue;
1611 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001613 if (Record)
1614 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001616 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1617 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001618 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001619 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1620 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001621 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001622 Record->setHasFlexibleArrayMember(true);
1623 } else {
1624 // If this is a struct/class and this is not the last element, reject
1625 // it. Note that GCC supports variable sized arrays in the middle of
1626 // structures.
1627 if (i != NumFields-1) {
1628 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1629 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001630 FD->setInvalidDecl();
1631 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 continue;
1633 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 // We support flexible arrays at the end of structs in other structs
1635 // as an extension.
1636 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1637 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001638 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001639 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 }
1641 }
1642 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001643 // Keep track of the number of named members.
1644 if (IdentifierInfo *II = FD->getIdentifier()) {
1645 // Detect duplicate member names.
1646 if (!FieldIDs.insert(II)) {
1647 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1648 // Find the previous decl.
1649 SourceLocation PrevLoc;
1650 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1651 assert(i != e && "Didn't find previous def!");
1652 if (RecFields[i]->getIdentifier() == II) {
1653 PrevLoc = RecFields[i]->getLocation();
1654 break;
1655 }
1656 }
1657 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001658 FD->setInvalidDecl();
1659 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001660 continue;
1661 }
1662 ++NumNamedMembers;
1663 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 }
1665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001667 if (Record)
1668 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001669 else {
1670 ObjcIvarDecl **ClsFields =
1671 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001672 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1673 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1674 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1675 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1676 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001677 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001678 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1679 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroffa5997c42007-10-02 21:43:37 +00001680 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001681 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001682 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001683}
1684
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001685/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1686/// returns true, or false, accordingly.
1687/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1688bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1689 const ObjcMethodDecl *PrevMethod) {
1690 if (Method->getMethodType().getCanonicalType() !=
1691 PrevMethod->getMethodType().getCanonicalType())
1692 return false;
1693 for (int i = 0; i < Method->getNumParams(); i++) {
1694 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1695 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1696 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1697 return false;
1698 }
1699 return true;
1700}
1701
Steve Naroff3a165b02007-10-03 21:00:46 +00001702void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *ClassDecl,
1703 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001704 // FIXME: Fix this when we can handle methods declared in protocols.
1705 // See Parser::ParseObjCAtProtocolDeclaration
1706 if (!ClassDecl)
1707 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001708 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1709 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001710
1711 llvm::DenseMap<void *, const ObjcMethodDecl*> InsMap;
1712 llvm::DenseMap<void *, const ObjcMethodDecl*> ClsMap;
1713
1714 bool isClassDeclaration =
1715 (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))
1716 || isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl)));
1717
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001718 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001719 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001720 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1721 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001722 if (Method->isInstance()) {
1723 if (isClassDeclaration) {
1724 /// Check for instance method of the same name with incompatible types
1725 const ObjcMethodDecl *&PrevMethod =
1726 InsMap[Method->getSelector().getAsOpaquePtr()];
1727 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1728 llvm::SmallString<128> buf;
1729 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1730 Method->getSelector().getName(buf));
1731 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1732 }
1733 else {
1734 insMethods.push_back(Method);
1735 InsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1736 }
1737 }
1738 else
1739 insMethods.push_back(Method);
1740 }
1741 else {
1742 if (isClassDeclaration) {
1743 /// Check for class method of the same name with incompatible types
1744 const ObjcMethodDecl *&PrevMethod =
1745 ClsMap[Method->getSelector().getAsOpaquePtr()];
1746 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1747 llvm::SmallString<128> buf;
1748 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
1749 Method->getSelector().getName(buf));
1750 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1751 }
1752 else {
1753 clsMethods.push_back(Method);
1754 ClsMap[Method->getSelector().getAsOpaquePtr()] = Method;
1755 }
1756 }
1757 else
1758 clsMethods.push_back(Method);
1759 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001760 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001761 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1762 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1763 static_cast<Decl*>(ClassDecl));
1764 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1765 &clsMethods[0], clsMethods.size());
1766 }
1767 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1768 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1769 static_cast<Decl*>(ClassDecl));
1770 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1771 &clsMethods[0], clsMethods.size());
1772 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001773 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1774 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1775 static_cast<Decl*>(ClassDecl));
1776 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1777 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001778 }
1779 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1780 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1781 static_cast<Decl*>(ClassDecl));
1782 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1783 &clsMethods[0], clsMethods.size());
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001784 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImplClass->getIdentifier());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001785 if (IDecl)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001786 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001787 }
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001788 else {
1789 ObjcCategoryImplDecl* CatImplClass = dyn_cast<ObjcCategoryImplDecl>(
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001790 static_cast<Decl*>(ClassDecl));
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001791 if (CatImplClass) {
1792 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1793 &clsMethods[0], clsMethods.size());
1794 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1795 // Find category interface decl and then check that all methods declared
1796 // in this interface is implemented in the category @implementation.
1797 if (IDecl) {
1798 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1799 Categories; Categories = Categories->getNextClassCategory()) {
1800 if (Categories->getCatName() == CatImplClass->getObjcCatName()) {
1801 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1802 break;
1803 }
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001804 }
1805 }
1806 }
Fariborz Jahanianb384d322007-10-04 20:19:06 +00001807 else
1808 assert(0 && "Sema::ActOnAddMethodsToObjcDecl(): Unknown DeclTy");
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001809 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001810}
1811
Steve Naroff37e58d12007-10-02 22:39:18 +00001812Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001813 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001814 // optional arguments. The number of types/arguments is obtained
1815 // from the Sel.getNumArgs().
1816 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1817 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001818 llvm::SmallVector<ParmVarDecl*, 16> Params;
1819
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001820 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001821 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001822 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001823 QualType::getFromOpaquePtr(ArgTypes[i]),
1824 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001825 Params.push_back(Param);
1826 }
1827 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001828 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1829 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001830 MethodType == tok::minus,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001831 MethodDeclKind == tok::objc_optional ?
1832 ObjcMethodDecl::Optional :
1833 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001834 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001835 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001836}
1837
Steve Naroff08d92e42007-09-15 18:49:24 +00001838Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 DeclTy *lastEnumConst,
1840 SourceLocation IdLoc, IdentifierInfo *Id,
1841 SourceLocation EqualLoc, ExprTy *val) {
1842 theEnumDecl = theEnumDecl; // silence unused warning.
1843 EnumConstantDecl *LastEnumConst =
1844 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1845 Expr *Val = static_cast<Expr*>(val);
1846
Chris Lattner31e05722007-08-26 06:24:45 +00001847 // The scope passed in may not be a decl scope. Zip up the scope tree until
1848 // we find one that is.
1849 while ((S->getFlags() & Scope::DeclScope) == 0)
1850 S = S->getParent();
1851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 // Verify that there isn't already something declared with this name in this
1853 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001854 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1855 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 if (S->isDeclScope(PrevDecl)) {
1857 if (isa<EnumConstantDecl>(PrevDecl))
1858 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1859 else
1860 Diag(IdLoc, diag::err_redefinition, Id->getName());
1861 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1862 // FIXME: Don't leak memory: delete Val;
1863 return 0;
1864 }
1865 }
1866
1867 llvm::APSInt EnumVal(32);
1868 QualType EltTy;
1869 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001870 // Make sure to promote the operand type to int.
1871 UsualUnaryConversions(Val);
1872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1874 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001875 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1877 Id->getName());
1878 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001879 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001880 } else {
1881 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001882 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001883 }
1884
1885 if (!Val) {
1886 if (LastEnumConst) {
1887 // Assign the last value + 1.
1888 EnumVal = LastEnumConst->getInitVal();
1889 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001890
1891 // Check for overflow on increment.
1892 if (EnumVal < LastEnumConst->getInitVal())
1893 Diag(IdLoc, diag::warn_enum_value_overflow);
1894
Chris Lattnerb7416f92007-08-27 17:37:24 +00001895 EltTy = LastEnumConst->getType();
1896 } else {
1897 // First value, set to zero.
1898 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001899 EnumVal.zextOrTrunc(
1900 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001901 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 }
1903
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1905 LastEnumConst);
1906
1907 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001908 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001909 Id->setFETokenInfo(New);
1910 S->AddDecl(New);
1911 return New;
1912}
1913
Steve Naroff08d92e42007-09-15 18:49:24 +00001914void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001915 DeclTy **Elements, unsigned NumElements) {
1916 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1917 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1918
Chris Lattnere37f0be2007-08-28 05:10:31 +00001919 // TODO: If the result value doesn't fit in an int, it must be a long or long
1920 // long value. ISO C does not support this, but GCC does as an extension,
1921 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001922 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001923
1924
Chris Lattnerac609682007-08-28 06:15:15 +00001925 // Verify that all the values are okay, compute the size of the values, and
1926 // reverse the list.
1927 unsigned NumNegativeBits = 0;
1928 unsigned NumPositiveBits = 0;
1929
1930 // Keep track of whether all elements have type int.
1931 bool AllElementsInt = true;
1932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 EnumConstantDecl *EltList = 0;
1934 for (unsigned i = 0; i != NumElements; ++i) {
1935 EnumConstantDecl *ECD =
1936 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1937 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001938
1939 // If the enum value doesn't fit in an int, emit an extension warning.
1940 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1941 "Should have promoted value to int");
1942 const llvm::APSInt &InitVal = ECD->getInitVal();
1943 if (InitVal.getBitWidth() > IntWidth) {
1944 llvm::APSInt V(InitVal);
1945 V.trunc(IntWidth);
1946 V.extend(InitVal.getBitWidth());
1947 if (V != InitVal)
1948 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1949 InitVal.toString());
1950 }
Chris Lattnerac609682007-08-28 06:15:15 +00001951
1952 // Keep track of the size of positive and negative values.
1953 if (InitVal.isUnsigned() || !InitVal.isNegative())
1954 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1955 else
1956 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001957
Chris Lattnerac609682007-08-28 06:15:15 +00001958 // Keep track of whether every enum element has type int (very commmon).
1959 if (AllElementsInt)
1960 AllElementsInt = ECD->getType() == Context.IntTy;
1961
Reid Spencer5f016e22007-07-11 17:01:13 +00001962 ECD->setNextDeclarator(EltList);
1963 EltList = ECD;
1964 }
1965
Chris Lattnerac609682007-08-28 06:15:15 +00001966 // Figure out the type that should be used for this enum.
1967 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1968 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001969 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001970
1971 if (NumNegativeBits) {
1972 // If there is a negative value, figure out the smallest integer type (of
1973 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001974 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001975 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001976 BestWidth = IntWidth;
1977 } else {
1978 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1979 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001980 BestType = Context.LongTy;
1981 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001982 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1983 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001984 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1985 BestType = Context.LongLongTy;
1986 }
1987 }
1988 } else {
1989 // If there is no negative value, figure out which of uint, ulong, ulonglong
1990 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001991 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001992 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001993 BestWidth = IntWidth;
1994 } else if (NumPositiveBits <=
1995 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001996 BestType = Context.UnsignedLongTy;
1997 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001998 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1999 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002000 "How could an initializer get larger than ULL?");
2001 BestType = Context.UnsignedLongLongTy;
2002 }
2003 }
2004
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002005 // Loop over all of the enumerator constants, changing their types to match
2006 // the type of the enum if needed.
2007 for (unsigned i = 0; i != NumElements; ++i) {
2008 EnumConstantDecl *ECD =
2009 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2010 if (!ECD) continue; // Already issued a diagnostic.
2011
2012 // Standard C says the enumerators have int type, but we allow, as an
2013 // extension, the enumerators to be larger than int size. If each
2014 // enumerator value fits in an int, type it as an int, otherwise type it the
2015 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2016 // that X has type 'int', not 'unsigned'.
2017 if (ECD->getType() == Context.IntTy)
2018 continue; // Already int type.
2019
2020 // Determine whether the value fits into an int.
2021 llvm::APSInt InitVal = ECD->getInitVal();
2022 bool FitsInInt;
2023 if (InitVal.isUnsigned() || !InitVal.isNegative())
2024 FitsInInt = InitVal.getActiveBits() < IntWidth;
2025 else
2026 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2027
2028 // If it fits into an integer type, force it. Otherwise force it to match
2029 // the enum decl type.
2030 QualType NewTy;
2031 unsigned NewWidth;
2032 bool NewSign;
2033 if (FitsInInt) {
2034 NewTy = Context.IntTy;
2035 NewWidth = IntWidth;
2036 NewSign = true;
2037 } else if (ECD->getType() == BestType) {
2038 // Already the right type!
2039 continue;
2040 } else {
2041 NewTy = BestType;
2042 NewWidth = BestWidth;
2043 NewSign = BestType->isSignedIntegerType();
2044 }
2045
2046 // Adjust the APSInt value.
2047 InitVal.extOrTrunc(NewWidth);
2048 InitVal.setIsSigned(NewSign);
2049 ECD->setInitVal(InitVal);
2050
2051 // Adjust the Expr initializer and type.
2052 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2053 ECD->setType(NewTy);
2054 }
Chris Lattnerac609682007-08-28 06:15:15 +00002055
Chris Lattnere00b18c2007-08-28 18:24:31 +00002056 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00002057}
2058
2059void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2060 if (!current) return;
2061
2062 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2063 // remember this in the LastInGroupList list.
2064 if (last)
2065 LastInGroupList.push_back((Decl*)last);
2066}
2067
2068void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2069 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2070 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2071 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2072 if (!newType.isNull()) // install the new vector type into the decl
2073 vDecl->setType(newType);
2074 }
2075 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2076 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2077 rawAttr);
2078 if (!newType.isNull()) // install the new vector type into the decl
2079 tDecl->setUnderlyingType(newType);
2080 }
2081 }
Steve Naroff73322922007-07-18 18:00:27 +00002082 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002083 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2084 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2085 else
Steve Naroff73322922007-07-18 18:00:27 +00002086 Diag(rawAttr->getAttributeLoc(),
2087 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002088 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 // FIXME: add other attributes...
2090}
2091
2092void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2093 AttributeList *declarator_postfix) {
2094 while (declspec_prefix) {
2095 HandleDeclAttribute(New, declspec_prefix);
2096 declspec_prefix = declspec_prefix->getNext();
2097 }
2098 while (declarator_postfix) {
2099 HandleDeclAttribute(New, declarator_postfix);
2100 declarator_postfix = declarator_postfix->getNext();
2101 }
2102}
2103
Steve Naroffbea0b342007-07-29 16:33:31 +00002104void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2105 AttributeList *rawAttr) {
2106 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002107 // check the attribute arugments.
2108 if (rawAttr->getNumArgs() != 1) {
2109 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2110 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002111 return;
Steve Naroff73322922007-07-18 18:00:27 +00002112 }
2113 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2114 llvm::APSInt vecSize(32);
2115 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2116 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2117 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002118 return;
Steve Naroff73322922007-07-18 18:00:27 +00002119 }
2120 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2121 // in conjunction with complex types (pointers, arrays, functions, etc.).
2122 Type *canonType = curType.getCanonicalType().getTypePtr();
2123 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2124 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2125 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002126 return;
Steve Naroff73322922007-07-18 18:00:27 +00002127 }
2128 // unlike gcc's vector_size attribute, the size is specified as the
2129 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002130 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002131
2132 if (vectorSize == 0) {
2133 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2134 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002135 return;
Steve Naroff73322922007-07-18 18:00:27 +00002136 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002137 // Instantiate/Install the vector type, the number of elements is > 0.
2138 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2139 // Remember this typedef decl, we will need it later for diagnostics.
2140 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002141}
2142
Reid Spencer5f016e22007-07-11 17:01:13 +00002143QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002144 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 // check the attribute arugments.
2146 if (rawAttr->getNumArgs() != 1) {
2147 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2148 std::string("1"));
2149 return QualType();
2150 }
2151 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2152 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002153 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2155 sizeExpr->getSourceRange());
2156 return QualType();
2157 }
2158 // navigate to the base type - we need to provide for vector pointers,
2159 // vector arrays, and functions returning vectors.
2160 Type *canonType = curType.getCanonicalType().getTypePtr();
2161
Steve Naroff73322922007-07-18 18:00:27 +00002162 if (canonType->isPointerType() || canonType->isArrayType() ||
2163 canonType->isFunctionType()) {
2164 assert(1 && "HandleVector(): Complex type construction unimplemented");
2165 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2166 do {
2167 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2168 canonType = PT->getPointeeType().getTypePtr();
2169 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2170 canonType = AT->getElementType().getTypePtr();
2171 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2172 canonType = FT->getResultType().getTypePtr();
2173 } while (canonType->isPointerType() || canonType->isArrayType() ||
2174 canonType->isFunctionType());
2175 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 }
2177 // the base type must be integer or float.
2178 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2179 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2180 curType.getCanonicalType().getAsString());
2181 return QualType();
2182 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002183 unsigned typeSize = static_cast<unsigned>(
2184 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002185 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002186 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002187
2188 // the vector size needs to be an integral multiple of the type size.
2189 if (vectorSize % typeSize) {
2190 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2191 sizeExpr->getSourceRange());
2192 return QualType();
2193 }
2194 if (vectorSize == 0) {
2195 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2196 sizeExpr->getSourceRange());
2197 return QualType();
2198 }
2199 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2200 // the number of elements to be a power of two (unlike GCC).
2201 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002202 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002203}
2204