blob: ba6c7d0175ee1d2d21246b8600b557c9a4187b80 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/TargetInfo.h"
Steve Naroff563477d2007-09-18 23:55:05 +000025#include "llvm/ADT/SmallString.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallSet.h"
Fariborz Jahanian85ff2642007-10-05 18:00:57 +000027#include "llvm/ADT/DenseSet.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Chris Lattner5c0fa302007-09-30 08:31:00 +000031 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
32 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
33 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000034 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000035}
36
Steve Naroffb216c882007-10-09 22:01:59 +000037void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000038 if (S->decl_empty()) return;
39 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
40
Reid Spencer5f016e22007-07-11 17:01:13 +000041 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
42 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000043 Decl *TmpD = static_cast<Decl*>(*I);
44 assert(TmpD && "This decl didn't get pushed??");
45 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
46 assert(D && "This decl isn't a ScopedDecl?");
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048 IdentifierInfo *II = D->getIdentifier();
49 if (!II) continue;
50
51 // Unlink this decl from the identifier. Because the scope contains decls
52 // in an unordered collection, and because we have multiple identifier
53 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
54 if (II->getFETokenInfo<Decl>() == D) {
55 // Normal case, no multiple decls in different namespaces.
56 II->setFETokenInfo(D->getNext());
57 } else {
58 // Scan ahead. There are only three namespaces in C, so this loop can
59 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000060 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000061 while (SomeDecl->getNext() != D) {
62 SomeDecl = SomeDecl->getNext();
63 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
64 }
65 SomeDecl->setNext(D->getNext());
66 }
67
68 // This will have to be revisited for C++: there we want to nest stuff in
69 // namespace decls etc. Even for C, we might want a top-level translation
70 // unit decl or something.
71 if (!CurFunctionDecl)
72 continue;
73
74 // Chain this decl to the containing function, it now owns the memory for
75 // the decl.
76 D->setNext(CurFunctionDecl->getDeclChain());
77 CurFunctionDecl->setDeclChain(D);
78 }
79}
80
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000081/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000082/// return 0 if one not found.
Steve Naroff6a8a9a42007-10-02 20:01:56 +000083ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
84
85 // Scan up the scope chain looking for a decl that matches this identifier
86 // that is in the appropriate namespace. This search should not take long, as
87 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
88 ScopedDecl *IdDecl = NULL;
89 for (ScopedDecl *D = Id->getFETokenInfo<ScopedDecl>(); D; D = D->getNext()) {
90 if (D->getIdentifierNamespace() == Decl::IDNS_Ordinary) {
91 IdDecl = D;
92 break;
93 }
94 }
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000095 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
96 IdDecl = 0;
97 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
98}
99
Reid Spencer5f016e22007-07-11 17:01:13 +0000100/// LookupScopedDecl - Look up the inner-most declaration in the specified
101/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000102ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
103 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (II == 0) return 0;
105 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
106
107 // Scan up the scope chain looking for a decl that matches this identifier
108 // that is in the appropriate namespace. This search should not take long, as
109 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000110 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 if (D->getIdentifierNamespace() == NS)
112 return D;
113
114 // If we didn't find a use of this identifier, and if the identifier
115 // corresponds to a compiler builtin, create the decl object for the builtin
116 // now, injecting it into translation unit scope, and return it.
117 if (NS == Decl::IDNS_Ordinary) {
118 // If this is a builtin on some other target, or if this builtin varies
119 // across targets (e.g. in type), emit a diagnostic and mark the translation
120 // unit non-portable for using it.
121 if (II->isNonPortableBuiltin()) {
122 // Only emit this diagnostic once for this builtin.
123 II->setNonPortableBuiltin(false);
124 Context.Target.DiagnoseNonPortability(IdLoc,
125 diag::port_target_builtin_use);
126 }
127 // If this is a builtin on this (or all) targets, create the decl.
128 if (unsigned BuiltinID = II->getBuiltinID())
129 return LazilyCreateBuiltin(II, BuiltinID, S);
130 }
131 return 0;
132}
133
134/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
135/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000136ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000137 Builtin::ID BID = (Builtin::ID)bid;
138
139 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
140 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000141 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000142
143 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000144 if (Scope *FnS = S->getFnParent())
145 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 while (S->getParent())
147 S = S->getParent();
148 S->AddDecl(New);
149
150 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000151 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // Scan until we find the last (outermost) decl in the id chain.
153 while (LastDecl->getNext())
154 LastDecl = LastDecl->getNext();
155 // Insert before (outside) it.
156 LastDecl->setNext(New);
157 } else {
158 II->setFETokenInfo(New);
159 }
160 // Make sure clients iterating over decls see this.
161 LastInGroupList.push_back(New);
162
163 return New;
164}
165
166/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
167/// and scope as a previous declaration 'Old'. Figure out how to resolve this
168/// situation, merging decls or emitting diagnostics as appropriate.
169///
Steve Naroff8e74c932007-09-13 21:41:19 +0000170TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 // Verify the old decl was also a typedef.
172 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
173 if (!Old) {
174 Diag(New->getLocation(), diag::err_redefinition_different_kind,
175 New->getName());
176 Diag(OldD->getLocation(), diag::err_previous_definition);
177 return New;
178 }
179
180 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
181 // TODO: This is totally simplistic. It should handle merging functions
182 // together etc, merging extern int X; int X; ...
183 Diag(New->getLocation(), diag::err_redefinition, New->getName());
184 Diag(Old->getLocation(), diag::err_previous_definition);
185 return New;
186}
187
188/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
189/// and scope as a previous declaration 'Old'. Figure out how to resolve this
190/// situation, merging decls or emitting diagnostics as appropriate.
191///
Steve Naroff8e74c932007-09-13 21:41:19 +0000192FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 // Verify the old decl was also a function.
194 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
195 if (!Old) {
196 Diag(New->getLocation(), diag::err_redefinition_different_kind,
197 New->getName());
198 Diag(OldD->getLocation(), diag::err_previous_definition);
199 return New;
200 }
201
202 // This is not right, but it's a start. If 'Old' is a function prototype with
203 // the same type as 'New', silently allow this. FIXME: We should link up decl
204 // objects here.
205 if (Old->getBody() == 0 &&
206 Old->getCanonicalType() == New->getCanonicalType()) {
207 return New;
208 }
209
210 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
211 // TODO: This is totally simplistic. It should handle merging functions
212 // together etc, merging extern int X; int X; ...
213 Diag(New->getLocation(), diag::err_redefinition, New->getName());
214 Diag(Old->getLocation(), diag::err_previous_definition);
215 return New;
216}
217
218/// MergeVarDecl - We just parsed a variable 'New' which has the same name
219/// and scope as a previous declaration 'Old'. Figure out how to resolve this
220/// situation, merging decls or emitting diagnostics as appropriate.
221///
222/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
223/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
224///
Steve Naroff8e74c932007-09-13 21:41:19 +0000225VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000226 // Verify the old decl was also a variable.
227 VarDecl *Old = dyn_cast<VarDecl>(OldD);
228 if (!Old) {
229 Diag(New->getLocation(), diag::err_redefinition_different_kind,
230 New->getName());
231 Diag(OldD->getLocation(), diag::err_previous_definition);
232 return New;
233 }
Steve Narofffb22d962007-08-30 01:06:46 +0000234 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
235 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
236 bool OldIsTentative = false;
237
238 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
239 // Handle C "tentative" external object definitions. FIXME: finish!
240 if (!OldFSDecl->getInit() &&
241 (OldFSDecl->getStorageClass() == VarDecl::None ||
242 OldFSDecl->getStorageClass() == VarDecl::Static))
243 OldIsTentative = true;
244 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000245 // Verify the types match.
246 if (Old->getCanonicalType() != New->getCanonicalType()) {
247 Diag(New->getLocation(), diag::err_redefinition, New->getName());
248 Diag(Old->getLocation(), diag::err_previous_definition);
249 return New;
250 }
251 // We've verified the types match, now check if Old is "extern".
252 if (Old->getStorageClass() != VarDecl::Extern) {
253 Diag(New->getLocation(), diag::err_redefinition, New->getName());
254 Diag(Old->getLocation(), diag::err_previous_definition);
255 }
256 return New;
257}
258
259/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
260/// no declarator (e.g. "struct foo;") is parsed.
261Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
262 // TODO: emit error on 'int;' or 'const enum foo;'.
263 // TODO: emit error on 'typedef int;'
264 // if (!DS.isMissingDeclaratorOk()) Diag(...);
265
266 return 0;
267}
268
Steve Naroff9e8925e2007-09-04 14:36:54 +0000269bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000270 AssignmentCheckResult result;
271 SourceLocation loc = Init->getLocStart();
272 // Get the type before calling CheckSingleAssignmentConstraints(), since
273 // it can promote the expression.
274 QualType rhsType = Init->getType();
275
276 result = CheckSingleAssignmentConstraints(DeclType, Init);
277
278 // decode the result (notice that extensions still return a type).
279 switch (result) {
280 case Compatible:
281 break;
282 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000283 // FIXME: tighten up this check which should allow:
284 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
285 if (rhsType == Context.getPointerType(Context.CharTy))
286 break;
Steve Narofff0090632007-09-02 02:04:30 +0000287 Diag(loc, diag::err_typecheck_assign_incompatible,
288 DeclType.getAsString(), rhsType.getAsString(),
289 Init->getSourceRange());
290 return true;
291 case PointerFromInt:
292 // check for null pointer constant (C99 6.3.2.3p3)
293 if (!Init->isNullPointerConstant(Context)) {
294 Diag(loc, diag::ext_typecheck_assign_pointer_int,
295 DeclType.getAsString(), rhsType.getAsString(),
296 Init->getSourceRange());
297 return true;
298 }
299 break;
300 case IntFromPointer:
301 Diag(loc, diag::ext_typecheck_assign_pointer_int,
302 DeclType.getAsString(), rhsType.getAsString(),
303 Init->getSourceRange());
304 break;
305 case IncompatiblePointer:
306 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
307 DeclType.getAsString(), rhsType.getAsString(),
308 Init->getSourceRange());
309 break;
310 case CompatiblePointerDiscardsQualifiers:
311 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
312 DeclType.getAsString(), rhsType.getAsString(),
313 Init->getSourceRange());
314 break;
315 }
316 return false;
317}
318
Steve Naroff9e8925e2007-09-04 14:36:54 +0000319bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
320 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000321 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000322 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000323
324 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
325 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
326 return true;
327 } else if (CheckSingleInitializer(expr, ElementType)) {
328 return true; // types weren't compatible.
329 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000330 if (savExpr != expr) // The type was promoted, update initializer list.
331 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000332 return false;
333}
334
335void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
336 QualType ElementType, bool isStatic,
337 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000338 for (unsigned i = 0; i < IList->getNumInits(); i++) {
339 Expr *expr = IList->getInit(i);
340
Steve Naroff371227d2007-09-04 02:20:04 +0000341 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
342 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000343 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000344 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
345 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000346 }
Steve Naroff371227d2007-09-04 02:20:04 +0000347 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000348 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000349 }
Steve Naroff371227d2007-09-04 02:20:04 +0000350 nInitializers++;
351 }
352 return;
353}
354
355// FIXME: Doesn't deal with arrays of structures yet.
356void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
357 QualType ElementType, bool isStatic,
358 int &totalInits, bool &hadError) {
359 int maxElementsAtThisLevel = 0;
360 int nInitsAtLevel = 0;
361
362 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
363 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000364 maxElementsAtThisLevel = CAT->getMaximumElements();
365 // Set DeclType, used below to recurse (for multi-dimensional arrays).
366 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000367 } else if (DeclType->isScalarType()) {
368 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
369 IList->getSourceRange());
370 maxElementsAtThisLevel = 1;
371 }
372 // The empty init list "{ }" is treated specially below.
373 unsigned numInits = IList->getNumInits();
374 if (numInits) {
375 for (unsigned i = 0; i < numInits; i++) {
376 Expr *expr = IList->getInit(i);
377
378 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
379 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
380 totalInits, hadError);
381 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000382 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000383 nInitsAtLevel++; // increment the number of initializers at this level.
384 totalInits--; // decrement the total number of initializers.
385
386 // Check if we have space for another initializer.
387 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
388 Diag(expr->getLocStart(), diag::warn_excess_initializers,
389 expr->getSourceRange());
390 }
391 }
392 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
393 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
394 } else {
395 // we have an initializer list with no elements.
396 totalInits -= maxElementsAtThisLevel;
397 if (totalInits < 0)
398 Diag(IList->getLocStart(), diag::warn_excess_initializers,
399 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000400 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000401 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000402}
403
Steve Naroff9e8925e2007-09-04 14:36:54 +0000404bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000405 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000406 if (!InitList)
407 return CheckSingleInitializer(Init, DeclType);
408
Steve Narofff0090632007-09-02 02:04:30 +0000409 // We have an InitListExpr, make sure we set the type.
410 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000411
412 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000413
Steve Naroff38374b02007-09-02 20:30:18 +0000414 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
415 // of unknown size ("[]") or an object type that is not a variable array type.
416 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
417 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000418 if (expr)
419 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
420 expr->getSourceRange());
421
Steve Naroff7cf8c442007-09-04 21:13:33 +0000422 // We have a VariableArrayType with unknown size. Note that only the first
423 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000424 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000425 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
426 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000427 if (!hadError) {
428 // Return a new array type from the number of initializers (C99 6.7.8p22).
429 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000430 ConstVal = numInits;
431 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000432 ArrayType::Normal, 0);
433 }
434 return hadError;
435 }
436 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000437 int maxElements = CAT->getMaximumElements();
438 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
439 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000440 return hadError;
441 }
Steve Naroff371227d2007-09-04 02:20:04 +0000442 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
443 int maxElements = 1;
444 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
445 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000446 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000447 }
448 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000449 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000450}
451
Reid Spencer5f016e22007-07-11 17:01:13 +0000452Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000453Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000454 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000455 IdentifierInfo *II = D.getIdentifier();
456
Chris Lattnere80a59c2007-07-25 00:24:17 +0000457 // All of these full declarators require an identifier. If it doesn't have
458 // one, the ParsedFreeStandingDeclSpec action should be used.
459 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000460 Diag(D.getDeclSpec().getSourceRange().Begin(),
461 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000462 D.getDeclSpec().getSourceRange(), D.getSourceRange());
463 return 0;
464 }
465
Chris Lattner31e05722007-08-26 06:24:45 +0000466 // The scope passed in may not be a decl scope. Zip up the scope tree until
467 // we find one that is.
468 while ((S->getFlags() & Scope::DeclScope) == 0)
469 S = S->getParent();
470
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000472 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
473 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 if (PrevDecl && !S->isDeclScope(PrevDecl))
475 PrevDecl = 0; // If in outer scope, it isn't the same thing.
476
Steve Naroffc752d042007-09-13 18:10:37 +0000477 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000478 bool InvalidDecl = false;
479
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
481 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
482 if (!NewTD) return 0;
483
484 // Handle attributes prior to checking for duplicates in MergeVarDecl
485 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
486 D.getAttributes());
487 // Merge the decl with the existing one if appropriate.
488 if (PrevDecl) {
489 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
490 if (NewTD == 0) return 0;
491 }
492 New = NewTD;
493 if (S->getParent() == 0) {
494 // C99 6.7.7p2: If a typedef name specifies a variably modified type
495 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000496 if (const VariableArrayType *VAT =
497 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
498 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
499 VAT->getSizeExpr()->getSourceRange());
500 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 }
502 }
503 } else if (D.isFunctionDeclarator()) {
504 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000505 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000506
Chris Lattner271f1a62007-09-27 15:15:46 +0000507 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 switch (D.getDeclSpec().getStorageClassSpec()) {
509 default: assert(0 && "Unknown storage class!");
510 case DeclSpec::SCS_auto:
511 case DeclSpec::SCS_register:
512 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
513 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000514 InvalidDecl = true;
515 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
517 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
518 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
519 }
520
521 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000522 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 LastDeclarator);
524
525 // Merge the decl with the existing one if appropriate.
526 if (PrevDecl) {
527 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
528 if (NewFD == 0) return 0;
529 }
530 New = NewFD;
531 } else {
532 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000533 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000534
535 VarDecl *NewVD;
536 VarDecl::StorageClass SC;
537 switch (D.getDeclSpec().getStorageClassSpec()) {
538 default: assert(0 && "Unknown storage class!");
539 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
540 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
541 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
542 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
543 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
544 }
545 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 // C99 6.9p2: The storage-class specifiers auto and register shall not
547 // appear in the declaration specifiers in an external declaration.
548 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
549 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
550 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000551 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000554 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000556 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 // Handle attributes prior to checking for duplicates in MergeVarDecl
558 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
559 D.getAttributes());
560
561 // Merge the decl with the existing one if appropriate.
562 if (PrevDecl) {
563 NewVD = MergeVarDecl(NewVD, PrevDecl);
564 if (NewVD == 0) return 0;
565 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000566 New = NewVD;
567 }
568
569 // If this has an identifier, add it to the scope stack.
570 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000571 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 II->setFETokenInfo(New);
573 S->AddDecl(New);
574 }
575
576 if (S->getParent() == 0)
577 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000578
579 // If any semantic error occurred, mark the decl as invalid.
580 if (D.getInvalidType() || InvalidDecl)
581 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000582
583 return New;
584}
585
Steve Naroffbb204692007-09-12 14:07:44 +0000586void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000587 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000588 Expr *Init = static_cast<Expr *>(init);
589
Steve Naroff410e3e22007-09-12 20:13:48 +0000590 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000591
Steve Naroff410e3e22007-09-12 20:13:48 +0000592 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
593 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000594 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
595 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000596 RealDecl->setInvalidDecl();
597 return;
598 }
Steve Naroffbb204692007-09-12 14:07:44 +0000599 // Get the decls type and save a reference for later, since
600 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000601 QualType DclT = VDecl->getType(), SavT = DclT;
602 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000603 VarDecl::StorageClass SC = BVD->getStorageClass();
604 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000605 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000606 BVD->setInvalidDecl();
607 } else if (!BVD->isInvalidDecl()) {
608 CheckInitializer(Init, DclT, SC == VarDecl::Static);
609 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000610 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000611 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000612 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000613 if (!FVD->isInvalidDecl())
614 CheckInitializer(Init, DclT, true);
615 }
616 // If the type changed, it means we had an incomplete type that was
617 // completed by the initializer. For example:
618 // int ary[] = { 1, 3, 5 };
619 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000620 if (!VDecl->isInvalidDecl() && (DclT != SavT))
621 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000622
623 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000624 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000625 return;
626}
627
Reid Spencer5f016e22007-07-11 17:01:13 +0000628/// The declarators are chained together backwards, reverse the list.
629Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
630 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000631 Decl *GroupDecl = static_cast<Decl*>(group);
632 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000633 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000634
635 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
636 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000637 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000639 else { // reverse the list.
640 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000641 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000642 Group->setNextDeclarator(NewGroup);
643 NewGroup = Group;
644 Group = Next;
645 }
646 }
647 // Perform semantic analysis that depends on having fully processed both
648 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000649 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000650 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
651 if (!IDecl)
652 continue;
653 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
654 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
655 QualType T = IDecl->getType();
656
657 // C99 6.7.5.2p2: If an identifier is declared to be an object with
658 // static storage duration, it shall not have a variable length array.
659 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
660 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
661 if (VLA->getSizeExpr()) {
662 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
663 IDecl->setInvalidDecl();
664 }
665 }
666 }
667 // Block scope. C99 6.7p7: If an identifier for an object is declared with
668 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
669 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
670 if (T->isIncompleteType()) {
671 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
672 T.getAsString());
673 IDecl->setInvalidDecl();
674 }
675 }
676 // File scope. C99 6.9.2p2: A declaration of an identifier for and
677 // object that has file scope without an initializer, and without a
678 // storage-class specifier or with the storage-class specifier "static",
679 // constitutes a tentative definition. Note: A tentative definition with
680 // external linkage is valid (C99 6.2.2p5).
681 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
682 // C99 6.9.2p3: If the declaration of an identifier for an object is
683 // a tentative definition and has internal linkage (C99 6.2.2p3), the
684 // declared type shall not be an incomplete type.
685 if (T->isIncompleteType()) {
686 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
687 T.getAsString());
688 IDecl->setInvalidDecl();
689 }
690 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 }
692 return NewGroup;
693}
Steve Naroffe1223f72007-08-28 03:03:08 +0000694
695// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000696ParmVarDecl *
697Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
698 Scope *FnScope) {
699 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
700
701 IdentifierInfo *II = PI.Ident;
702 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
703 // Can this happen for params? We already checked that they don't conflict
704 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000705 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 PI.IdentLoc, FnScope)) {
707
708 }
709
710 // FIXME: Handle storage class (auto, register). No declarator?
711 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000712
713 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
714 // Doing the promotion here has a win and a loss. The win is the type for
715 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
716 // code generator). The loss is the orginal type isn't preserved. For example:
717 //
718 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
719 // int blockvardecl[5];
720 // sizeof(parmvardecl); // size == 4
721 // sizeof(blockvardecl); // size == 20
722 // }
723 //
724 // For expressions, all implicit conversions are captured using the
725 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
726 //
727 // FIXME: If a source translation tool needs to see the original type, then
728 // we need to consider storing both types (in ParmVarDecl)...
729 //
730 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
731 if (const ArrayType *AT = parmDeclType->getAsArrayType())
732 parmDeclType = Context.getPointerType(AT->getElementType());
733 else if (parmDeclType->isFunctionType())
734 parmDeclType = Context.getPointerType(parmDeclType);
735
736 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000737 VarDecl::None, 0);
738 if (PI.InvalidType)
739 New->setInvalidDecl();
740
Reid Spencer5f016e22007-07-11 17:01:13 +0000741 // If this has an identifier, add it to the scope stack.
742 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000743 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 II->setFETokenInfo(New);
745 FnScope->AddDecl(New);
746 }
747
748 return New;
749}
750
751
Chris Lattnerb652cea2007-10-09 17:14:05 +0000752Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 assert(CurFunctionDecl == 0 && "Function parsing confused");
754 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
755 "Not a function declarator!");
756 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
757
758 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
759 // for a K&R function.
760 if (!FTI.hasPrototype) {
761 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
762 if (FTI.ArgInfo[i].TypeInfo == 0) {
763 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
764 FTI.ArgInfo[i].Ident->getName());
765 // Implicitly declare the argument as type 'int' for lack of a better
766 // type.
767 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
768 }
769 }
770
771 // Since this is a function definition, act as though we have information
772 // about the arguments.
773 FTI.hasPrototype = true;
774 } else {
775 // FIXME: Diagnose arguments without names in C.
776
777 }
778
779 Scope *GlobalScope = FnBodyScope->getParent();
780
781 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000782 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 CurFunctionDecl = FD;
784
785 // Create Decl objects for each parameter, adding them to the FunctionDecl.
786 llvm::SmallVector<ParmVarDecl*, 16> Params;
787
788 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
789 // no arguments, not a function that takes a single void argument.
790 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
791 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
792 // empty arg list, don't push any params.
793 } else {
794 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
795 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
796 }
797
798 FD->setParams(&Params[0], Params.size());
799
800 return FD;
801}
802
Chris Lattnerb652cea2007-10-09 17:14:05 +0000803Sema::DeclTy *Sema::ActOnFunctionDefBody(DeclTy *D, StmtTy *Body) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000804 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
805 FD->setBody((Stmt*)Body);
806
807 assert(FD == CurFunctionDecl && "Function parsing confused");
808 CurFunctionDecl = 0;
809
810 // Verify and clean out per-function state.
811
812 // Check goto/label use.
813 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
814 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
815 // Verify that we have no forward references left. If so, there was a goto
816 // or address of a label taken, but no definition of it. Label fwd
817 // definitions are indicated with a null substmt.
818 if (I->second->getSubStmt() == 0) {
819 LabelStmt *L = I->second;
820 // Emit error.
821 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
822
823 // At this point, we have gotos that use the bogus label. Stitch it into
824 // the function body so that they aren't leaked and that the AST is well
825 // formed.
826 L->setSubStmt(new NullStmt(L->getIdentLoc()));
827 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
828 }
829 }
830 LabelMap.clear();
831
832 return FD;
833}
834
835
836/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
837/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000838ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
839 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 if (getLangOptions().C99) // Extension in C99.
841 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
842 else // Legal in C90, but warn about it.
843 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
844
845 // FIXME: handle stuff like:
846 // void foo() { extern float X(); }
847 // void bar() { X(); } <-- implicit decl for X in another scope.
848
849 // Set a Declarator for the implicit definition: int foo();
850 const char *Dummy;
851 DeclSpec DS;
852 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
853 Error = Error; // Silence warning.
854 assert(!Error && "Error setting up implicit decl!");
855 Declarator D(DS, Declarator::BlockContext);
856 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
857 D.SetIdentifier(&II, Loc);
858
859 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000860 if (Scope *FnS = S->getFnParent())
861 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000862 while (S->getParent())
863 S = S->getParent();
864
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000865 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000866}
867
868
869TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000870 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
872
873 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000874 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000875
876 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000877 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
878 T, LastDeclarator);
879 if (D.getInvalidType())
880 NewTD->setInvalidDecl();
881 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000882}
883
Steve Naroff3a165b02007-10-03 21:00:46 +0000884Sema::DeclTy *Sema::ActOnStartClassInterface(Scope* S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000885 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000886 IdentifierInfo *ClassName, SourceLocation ClassLoc,
887 IdentifierInfo *SuperName, SourceLocation SuperLoc,
888 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
889 AttributeList *AttrList) {
890 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000891
892 // Check for another declaration kind with the same name.
893 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
894 ClassLoc, S);
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000895 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000896 Diag(ClassLoc, diag::err_redefinition_different_kind,
897 ClassName->getName());
898 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
899 }
900
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000901 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000902 if (IDecl) {
903 // Class already seen. Is it a forward declaration?
Steve Naroff768f26e2007-10-02 20:26:23 +0000904 if (!IDecl->isForwardDecl())
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000905 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000906 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000907 IDecl->setForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000908 IDecl->AllocIntfRefProtocols(NumProtocols);
909 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000910 }
911 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000912 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000913
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000914 // Chain & install the interface decl into the identifier.
915 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
916 ClassName->setFETokenInfo(IDecl);
917 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000918
919 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000920 ObjcInterfaceDecl* SuperClassEntry = 0;
921 // Check if a different kind of symbol declared in this scope.
922 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
923 SuperLoc, S);
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000924 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000925 Diag(SuperLoc, diag::err_redefinition_different_kind,
926 SuperName->getName());
927 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000928 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000929 else {
930 // Check that super class is previously defined
Steve Naroff6a8a9a42007-10-02 20:01:56 +0000931 SuperClassEntry = getObjCInterfaceDecl(SuperName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000932
Steve Naroff768f26e2007-10-02 20:26:23 +0000933 if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000934 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
935 ClassName->getName());
936 }
937 }
938 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000939 }
940
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000941 /// Check then save referenced protocols
942 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000943 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtocolNames[i]];
Steve Naroff768f26e2007-10-02 20:26:23 +0000944 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000945 Diag(ClassLoc, diag::err_undef_protocolref,
946 ProtocolNames[i]->getName(),
947 ClassName->getName());
948 IDecl->setIntfRefProtocols((int)i, RefPDecl);
949 }
950
Steve Naroff3536b442007-09-06 21:24:23 +0000951 return IDecl;
952}
953
Steve Naroff3a165b02007-10-03 21:00:46 +0000954Sema::DeclTy *Sema::ActOnStartProtocolInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000955 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000956 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
957 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
958 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000959 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolName];
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000960 if (PDecl) {
961 // Protocol already seen. Better be a forward protocol declaration
Steve Naroff768f26e2007-10-02 20:26:23 +0000962 if (!PDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000963 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
964 ProtocolName->getName());
965 else {
Steve Naroff768f26e2007-10-02 20:26:23 +0000966 PDecl->setForwardDecl(false);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000967 PDecl->AllocReferencedProtocols(NumProtoRefs);
968 }
969 }
970 else {
971 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
972 ProtocolName);
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000973 ObjcProtocols[ProtocolName] = PDecl;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000974 }
975
976 /// Check then save referenced protocols
977 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000978 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
Steve Naroff768f26e2007-10-02 20:26:23 +0000979 if (!RefPDecl || RefPDecl->isForwardDecl())
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000980 Diag(ProtocolLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +0000981 ProtoRefNames[i]->getName(),
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000982 ProtocolName->getName());
983 PDecl->setReferencedProtocols((int)i, RefPDecl);
984 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000985
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000986 return PDecl;
987}
988
Fariborz Jahanian245f92a2007-10-05 21:01:53 +0000989/// ActOnFindProtocolDeclaration - This routine looks for a previously
990/// declared protocol and returns it. If not found, issues diagnostic.
991/// Will build a list of previously protocol declarations found in the list.
992Action::DeclTy **
993Sema::ActOnFindProtocolDeclaration(Scope *S,
994 SourceLocation TypeLoc,
995 IdentifierInfo **ProtocolId,
996 unsigned NumProtocols) {
997 for (unsigned i = 0; i != NumProtocols; ++i) {
Fariborz Jahanian05672a02007-10-09 18:03:53 +0000998 ObjcProtocolDecl *PDecl = ObjcProtocols[ProtocolId[i]];
Fariborz Jahanian245f92a2007-10-05 21:01:53 +0000999 if (!PDecl)
1000 Diag(TypeLoc, diag::err_undeclared_protocol,
1001 ProtocolId[i]->getName());
1002 }
1003 return 0;
1004}
1005
Steve Naroff37e58d12007-10-02 22:39:18 +00001006/// ActOnForwardProtocolDeclaration -
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001007/// Scope will always be top level file scope.
1008Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001009Sema::ActOnForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001010 IdentifierInfo **IdentList, unsigned NumElts) {
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001011 llvm::SmallVector<ObjcProtocolDecl*, 32> Protocols;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001012
1013 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner60c52182007-10-07 07:05:08 +00001014 IdentifierInfo *P = IdentList[i];
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001015 ObjcProtocolDecl *PDecl = ObjcProtocols[P];
Chris Lattner60c52182007-10-07 07:05:08 +00001016 if (!PDecl) { // Not already seen?
1017 // FIXME: Pass in the location of the identifier!
1018 PDecl = new ObjcProtocolDecl(AtProtocolLoc, 0, P, true);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001019 ObjcProtocols[P] = PDecl;
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001020 }
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001021
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001022 Protocols.push_back(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001023 }
Chris Lattnerb97de3e2007-10-06 20:05:59 +00001024 return new ObjcForwardProtocolDecl(AtProtocolLoc,
1025 &Protocols[0], Protocols.size());
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001026}
1027
Steve Naroff3a165b02007-10-03 21:00:46 +00001028Sema::DeclTy *Sema::ActOnStartCategoryInterface(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001029 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001030 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1031 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1032 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001033 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001034
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001035 /// Check that class of this category is already completely declared.
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001036 if (!IDecl || IDecl->isForwardDecl()) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001037 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001038 return 0;
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001039 }
Fariborz Jahanian8fe5c2a2007-10-09 18:22:59 +00001040 ObjcCategoryDecl *CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs,
1041 CategoryName);
1042 CDecl->setClassInterface(IDecl);
1043 /// Check for duplicate interface declaration for this category
1044 ObjcCategoryDecl *CDeclChain;
1045 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1046 CDeclChain = CDeclChain->getNextClassCategory()) {
1047 if (CDeclChain->getIdentifier() == CategoryName) {
1048 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1049 CategoryName->getName());
1050 break;
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001051 }
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001052 }
Fariborz Jahanian8fe5c2a2007-10-09 18:22:59 +00001053 if (!CDeclChain)
1054 CDecl->insertNextClassCategory();
1055
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001056 /// Check then save referenced protocols
1057 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001058 ObjcProtocolDecl* RefPDecl = ObjcProtocols[ProtoRefNames[i]];
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001059 if (!RefPDecl || RefPDecl->isForwardDecl()) {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001060 Diag(CategoryLoc, diag::err_undef_protocolref,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001061 ProtoRefNames[i]->getName(),
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001062 CategoryName->getName());
Fariborz Jahanian0332b6c2007-10-08 16:07:03 +00001063 }
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001064 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1065 }
1066
Fariborz Jahanian22d71d62007-10-09 17:05:22 +00001067 return CDecl;
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001068}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001069
Steve Naroff3a165b02007-10-03 21:00:46 +00001070/// ActOnStartCategoryImplementation - Perform semantic checks on the
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001071/// category implementation declaration and build an ObjcCategoryImplDecl
1072/// object.
Steve Naroff3a165b02007-10-03 21:00:46 +00001073Sema::DeclTy *Sema::ActOnStartCategoryImplementation(Scope* S,
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001074 SourceLocation AtCatImplLoc,
1075 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1076 IdentifierInfo *CatName, SourceLocation CatLoc) {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001077 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001078 ObjcCategoryImplDecl *CDecl = new ObjcCategoryImplDecl(AtCatImplLoc,
Chris Lattner6a0e89e2007-10-06 23:12:31 +00001079 CatName, IDecl);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001080 /// Check that class of this category is already completely declared.
Steve Naroff768f26e2007-10-02 20:26:23 +00001081 if (!IDecl || IDecl->isForwardDecl())
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001082 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1083 /// TODO: Check that CatName, category name, is not used in another
1084 // implementation.
1085 return CDecl;
1086}
1087
Steve Naroff3a165b02007-10-03 21:00:46 +00001088Sema::DeclTy *Sema::ActOnStartClassImplementation(Scope *S,
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001089 SourceLocation AtClassImplLoc,
1090 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1091 IdentifierInfo *SuperClassname,
1092 SourceLocation SuperClassLoc) {
1093 ObjcInterfaceDecl* IDecl = 0;
1094 // Check for another declaration kind with the same name.
1095 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1096 ClassLoc, S);
1097 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1098 Diag(ClassLoc, diag::err_redefinition_different_kind,
1099 ClassName->getName());
1100 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1101 }
1102 else {
1103 // Is there an interface declaration of this class; if not, warn!
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001104 IDecl = getObjCInterfaceDecl(ClassName);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001105 if (!IDecl)
1106 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1107 }
1108
1109 // Check that super class name is valid class name
1110 ObjcInterfaceDecl* SDecl = 0;
1111 if (SuperClassname) {
1112 // Check if a different kind of symbol declared in this scope.
1113 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1114 SuperClassLoc, S);
Fariborz Jahanian05672a02007-10-09 18:03:53 +00001115 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001116 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1117 SuperClassname->getName());
1118 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1119 }
1120 else {
Steve Naroff6a8a9a42007-10-02 20:01:56 +00001121 SDecl = getObjCInterfaceDecl(SuperClassname);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001122 if (!SDecl)
1123 Diag(SuperClassLoc, diag::err_undef_superclass,
1124 SuperClassname->getName(), ClassName->getName());
1125 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1126 // This implementation and its interface do not have the same
1127 // super class.
1128 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1129 SuperClassname->getName());
1130 Diag(SDecl->getLocation(), diag::err_previous_definition);
1131 }
1132 }
1133 }
1134
1135 ObjcImplementationDecl* IMPDecl =
1136 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001137 if (!IDecl) {
1138 // Legacy case of @implementation with no corresponding @interface.
1139 // Build, chain & install the interface decl into the identifier.
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001140 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, ClassName);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001141 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1142 ClassName->setFETokenInfo(IDecl);
1143
1144 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001145
1146 // Check that there is no duplicate implementation of this class.
Chris Lattnerf3876682007-10-07 01:13:46 +00001147 if (!ObjcImplementations.insert(ClassName))
1148 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001149
1150 return IMPDecl;
1151}
1152
Steve Naroffa5997c42007-10-02 21:43:37 +00001153void Sema::CheckImplementationIvars(ObjcImplementationDecl *ImpDecl,
1154 ObjcIvarDecl **ivars, unsigned numIvars) {
1155 assert(ImpDecl && "missing implementation decl");
1156 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001157 /// 2nd check is added to accomodate case of non-existing @interface decl.
1158 /// (legacy objective-c @implementation decl without an @interface decl).
1159 if (!IDecl || IDecl->ImplicitInterfaceDecl())
Steve Naroffa5997c42007-10-02 21:43:37 +00001160 return;
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001161 assert(ivars && "missing @implementation ivars");
1162
Steve Naroffa5997c42007-10-02 21:43:37 +00001163 // Check interface's Ivar list against those in the implementation.
1164 // names and types must match.
1165 //
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001166 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1167 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1168 unsigned j = 0;
1169 bool err = false;
1170 while (numIvars > 0 && IntfNumIvars > 0) {
1171 ObjcIvarDecl* ImplIvar = ivars[j];
1172 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1173 assert (ImplIvar && "missing implementation ivar");
1174 assert (ClsIvar && "missing class ivar");
1175 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1176 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1177 ImplIvar->getIdentifier()->getName());
1178 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1179 ClsIvar->getIdentifier()->getName());
1180 }
1181 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1182 // as error.
1183 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1184 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1185 ImplIvar->getIdentifier()->getName());
1186 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1187 ClsIvar->getIdentifier()->getName());
1188 err = true;
1189 break;
1190 }
1191 --numIvars;
1192 --IntfNumIvars;
1193 }
1194 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1195 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1196 diag::err_inconsistant_ivar);
1197
1198}
1199
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001200/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1201/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001202void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001203 bool& IncompleteImpl,
Steve Naroffeefc4182007-10-08 21:05:34 +00001204 const llvm::DenseSet<Selector> &InsMap,
Chris Lattner85994262007-10-05 20:15:24 +00001205 const llvm::DenseSet<Selector> &ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001206 // check unimplemented instance methods.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001207 ObjcMethodDecl** methods = PDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001208 for (int j = 0; j < PDecl->getNumInstanceMethods(); j++) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001209 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001210 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001211 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001212 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001213 }
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001214 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001215 // check unimplemented class methods
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001216 methods = PDecl->getClassMethods();
1217 for (int j = 0; j < PDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001218 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001219 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001220 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001221 IncompleteImpl = true;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001222 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001223
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001224 // Check on this protocols's referenced protocols, recursively
1225 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1226 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001227 CheckProtocolMethodDefs(RefPDecl[i], IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001228}
1229
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001230void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1231 ObjcInterfaceDecl* IDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001232 llvm::DenseSet<Selector> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001233 // Check and see if instance methods in class interface have been
1234 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001235 ObjcMethodDecl **methods = IMPDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001236 for (int i=0; i < IMPDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001237 InsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001238
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001239 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001240 methods = IDecl->getInstanceMethods();
1241 for (int j = 0; j < IDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001242 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001243 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001244 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001245 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001246 }
Chris Lattner85994262007-10-05 20:15:24 +00001247 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001248 // Check and see if class methods in class interface have been
1249 // implemented in the implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001250 methods = IMPDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001251 for (int i=0; i < IMPDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001252 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001253
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001254 methods = IDecl->getClassMethods();
1255 for (int j = 0; j < IDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001256 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001257 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001258 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001259 IncompleteImpl = true;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001260 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001261
1262 // Check the protocol list for unimplemented methods in the @implementation
1263 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001264 ObjcProtocolDecl** protocols = IDecl->getReferencedProtocols();
Chris Lattner85994262007-10-05 20:15:24 +00001265 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++)
1266 CheckProtocolMethodDefs(protocols[i], IncompleteImpl, InsMap, ClsMap);
1267
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001268 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001269 Diag(IMPDecl->getLocation(), diag::warn_incomplete_impl_class,
1270 IMPDecl->getName());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001271}
1272
1273/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
1274/// category interface is implemented in the category @implementation.
1275void Sema::ImplCategoryMethodsVsIntfMethods(ObjcCategoryImplDecl *CatImplDecl,
1276 ObjcCategoryDecl *CatClassDecl) {
Steve Naroffeefc4182007-10-08 21:05:34 +00001277 llvm::DenseSet<Selector> InsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001278 // Check and see if instance methods in category interface have been
1279 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001280 ObjcMethodDecl **methods = CatImplDecl->getInstanceMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001281 for (int i=0; i < CatImplDecl->getNumInstanceMethods(); i++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001282 InsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001283
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001284 bool IncompleteImpl = false;
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001285 methods = CatClassDecl->getInstanceMethods();
1286 for (int j = 0; j < CatClassDecl->getNumInstanceMethods(); j++)
Steve Naroffeefc4182007-10-08 21:05:34 +00001287 if (!InsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001288 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001289 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001290 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001291 }
Chris Lattner85994262007-10-05 20:15:24 +00001292 llvm::DenseSet<Selector> ClsMap;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001293 // Check and see if class methods in category interface have been
1294 // implemented in its implementation class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001295 methods = CatImplDecl->getClassMethods();
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001296 for (int i=0; i < CatImplDecl->getNumClassMethods(); i++)
Chris Lattner85994262007-10-05 20:15:24 +00001297 ClsMap.insert(methods[i]->getSelector());
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001298
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001299 methods = CatClassDecl->getClassMethods();
1300 for (int j = 0; j < CatClassDecl->getNumClassMethods(); j++)
Chris Lattner85994262007-10-05 20:15:24 +00001301 if (!ClsMap.count(methods[j]->getSelector())) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001302 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001303 methods[j]->getSelector().getName());
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001304 IncompleteImpl = true;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001305 }
1306
1307 // Check the protocol list for unimplemented methods in the @implementation
1308 // class.
Fariborz Jahanian7ed9e0f2007-10-02 22:05:16 +00001309 ObjcProtocolDecl** protocols = CatClassDecl->getReferencedProtocols();
1310 for (int i = 0; i < CatClassDecl->getNumReferencedProtocols(); i++) {
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001311 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001312 CheckProtocolMethodDefs(PDecl, IncompleteImpl, InsMap, ClsMap);
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001313 }
Fariborz Jahanianca3adf72007-10-02 20:06:01 +00001314 if (IncompleteImpl)
Fariborz Jahanian4b6df3f2007-10-04 00:22:33 +00001315 Diag(CatImplDecl->getLocation(), diag::warn_incomplete_impl_category,
Chris Lattnerfd5de472007-10-06 22:53:46 +00001316 CatClassDecl->getName());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001317}
1318
Steve Naroff37e58d12007-10-02 22:39:18 +00001319/// ActOnForwardClassDeclaration -
Steve Naroff3536b442007-09-06 21:24:23 +00001320/// Scope will always be top level file scope.
1321Action::DeclTy *
Steve Naroff37e58d12007-10-02 22:39:18 +00001322Sema::ActOnForwardClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1323 IdentifierInfo **IdentList, unsigned NumElts)
1324{
Chris Lattner7e620722007-10-06 20:08:36 +00001325 llvm::SmallVector<ObjcInterfaceDecl*, 32> Interfaces;
1326
Steve Naroff3536b442007-09-06 21:24:23 +00001327 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner7e620722007-10-06 20:08:36 +00001328 ObjcInterfaceDecl *IDecl = getObjCInterfaceDecl(IdentList[i]);
1329 if (!IDecl) { // Not already seen? Make a forward decl.
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001330 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001331 // Chain & install the interface decl into the identifier.
1332 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1333 IdentList[i]->setFETokenInfo(IDecl);
Chris Lattner60c52182007-10-07 07:05:08 +00001334
1335 // Remember that this needs to be removed when the scope is popped.
1336 S->AddDecl(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001337 }
Chris Lattner7e620722007-10-06 20:08:36 +00001338
1339 Interfaces.push_back(IDecl);
Steve Naroff3536b442007-09-06 21:24:23 +00001340 }
Chris Lattner7e620722007-10-06 20:08:36 +00001341
1342 return new ObjcClassDecl(AtClassLoc, &Interfaces[0], Interfaces.size());
Steve Naroff3536b442007-09-06 21:24:23 +00001343}
1344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345
Steve Naroff08d92e42007-09-15 18:49:24 +00001346/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001347/// former case, Name will be non-null. In the later case, Name will be null.
1348/// TagType indicates what kind of tag this is. TK indicates whether this is a
1349/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001350Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001351 SourceLocation KWLoc, IdentifierInfo *Name,
1352 SourceLocation NameLoc, AttributeList *Attr) {
1353 // If this is a use of an existing tag, it must have a name.
1354 assert((Name != 0 || TK == TK_Definition) &&
1355 "Nameless record must be a definition!");
1356
1357 Decl::Kind Kind;
1358 switch (TagType) {
1359 default: assert(0 && "Unknown tag type!");
1360 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1361 case DeclSpec::TST_union: Kind = Decl::Union; break;
1362//case DeclSpec::TST_class: Kind = Decl::Class; break;
1363 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1364 }
1365
1366 // If this is a named struct, check to see if there was a previous forward
1367 // declaration or definition.
1368 if (TagDecl *PrevDecl =
1369 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1370 NameLoc, S))) {
1371
1372 // If this is a use of a previous tag, or if the tag is already declared in
1373 // the same scope (so that the definition/declaration completes or
1374 // rementions the tag), reuse the decl.
1375 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1376 // Make sure that this wasn't declared as an enum and now used as a struct
1377 // or something similar.
1378 if (PrevDecl->getKind() != Kind) {
1379 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1380 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1381 }
1382
1383 // If this is a use or a forward declaration, we're good.
1384 if (TK != TK_Definition)
1385 return PrevDecl;
1386
1387 // Diagnose attempts to redefine a tag.
1388 if (PrevDecl->isDefinition()) {
1389 Diag(NameLoc, diag::err_redefinition, Name->getName());
1390 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1391 // If this is a redefinition, recover by making this struct be
1392 // anonymous, which will make any later references get the previous
1393 // definition.
1394 Name = 0;
1395 } else {
1396 // Okay, this is definition of a previously declared or referenced tag.
1397 // Move the location of the decl to be the definition site.
1398 PrevDecl->setLocation(NameLoc);
1399 return PrevDecl;
1400 }
1401 }
1402 // If we get here, this is a definition of a new struct type in a nested
1403 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1404 // type.
1405 }
1406
1407 // If there is an identifier, use the location of the identifier as the
1408 // location of the decl, otherwise use the location of the struct/union
1409 // keyword.
1410 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1411
1412 // Otherwise, if this is the first time we've seen this tag, create the decl.
1413 TagDecl *New;
1414 switch (Kind) {
1415 default: assert(0 && "Unknown tag kind!");
1416 case Decl::Enum:
1417 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1418 // enum X { A, B, C } D; D should chain to X.
1419 New = new EnumDecl(Loc, Name, 0);
1420 // If this is an undefined enum, warn.
1421 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1422 break;
1423 case Decl::Union:
1424 case Decl::Struct:
1425 case Decl::Class:
1426 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1427 // struct X { int A; } D; D should chain to X.
1428 New = new RecordDecl(Kind, Loc, Name, 0);
1429 break;
1430 }
1431
1432 // If this has an identifier, add it to the scope stack.
1433 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001434 // The scope passed in may not be a decl scope. Zip up the scope tree until
1435 // we find one that is.
1436 while ((S->getFlags() & Scope::DeclScope) == 0)
1437 S = S->getParent();
1438
1439 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001440 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 Name->setFETokenInfo(New);
1442 S->AddDecl(New);
1443 }
1444
1445 return New;
1446}
1447
Steve Naroff08d92e42007-09-15 18:49:24 +00001448/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001449/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001450Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 SourceLocation DeclStart,
1452 Declarator &D, ExprTy *BitfieldWidth) {
1453 IdentifierInfo *II = D.getIdentifier();
1454 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 SourceLocation Loc = DeclStart;
1456 if (II) Loc = D.getIdentifierLoc();
1457
1458 // FIXME: Unnamed fields can be handled in various different ways, for
1459 // example, unnamed unions inject all members into the struct namespace!
1460
1461
1462 if (BitWidth) {
1463 // TODO: Validate.
1464 //printf("WARNING: BITFIELDS IGNORED!\n");
1465
1466 // 6.7.2.1p3
1467 // 6.7.2.1p4
1468
1469 } else {
1470 // Not a bitfield.
1471
1472 // validate II.
1473
1474 }
1475
1476 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001477 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1478 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1481 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001482 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1483 Diag(Loc, diag::err_typecheck_illegal_vla,
1484 VAT->getSizeExpr()->getSourceRange());
1485 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001488 FieldDecl *NewFD;
1489
1490 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001491 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001492 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001493 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001494 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001495 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001496 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001497
Steve Naroff5912a352007-08-28 20:14:24 +00001498 if (D.getInvalidType() || InvalidDecl)
1499 NewFD->setInvalidDecl();
1500 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501}
1502
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001503/// TranslateIvarVisibility - Translate visibility from a token ID to an
1504/// AST enum value.
1505static ObjcIvarDecl::AccessControl
1506TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001507 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001508 case tok::objc_private: return ObjcIvarDecl::Private;
1509 case tok::objc_public: return ObjcIvarDecl::Public;
1510 case tok::objc_protected: return ObjcIvarDecl::Protected;
1511 case tok::objc_package: return ObjcIvarDecl::Package;
1512 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001513 }
1514}
1515
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001516void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001517 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001518 DeclTy **Fields, unsigned NumFields,
1519 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001520 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1521 assert(EnclosingDecl && "missing record or interface decl");
1522 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1523
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001524 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001525 // Diagnose code like:
1526 // struct S { struct S {} X; };
1527 // We discover this when we complete the outer S. Reject and ignore the
1528 // outer S.
1529 Diag(Record->getLocation(), diag::err_nested_redefinition,
1530 Record->getKindName());
1531 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001532 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 return;
1534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001535 // Verify that all the fields are okay.
1536 unsigned NumNamedMembers = 0;
1537 llvm::SmallVector<FieldDecl*, 32> RecFields;
1538 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001539
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001541
Steve Naroff74216642007-09-14 22:20:54 +00001542 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1543 assert(FD && "missing field decl");
1544
1545 // Remember all fields.
1546 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001547
1548 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001549 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001550
Steve Narofff13271f2007-09-14 23:09:53 +00001551 // If we have visibility info, make sure the AST is set accordingly.
1552 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001553 cast<ObjcIvarDecl>(FD)->setAccessControl(
1554 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001555
Reid Spencer5f016e22007-07-11 17:01:13 +00001556 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001557 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001558 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001560 FD->setInvalidDecl();
1561 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001562 continue;
1563 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1565 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001566 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001567 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001568 FD->setInvalidDecl();
1569 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001570 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001571 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001572 if (i != NumFields-1 || // ... that the last member ...
1573 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001574 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001576 FD->setInvalidDecl();
1577 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 continue;
1579 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001580 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1582 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001583 FD->setInvalidDecl();
1584 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 continue;
1586 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001588 if (Record)
1589 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001590 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1592 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001593 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1595 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001596 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 Record->setHasFlexibleArrayMember(true);
1598 } else {
1599 // If this is a struct/class and this is not the last element, reject
1600 // it. Note that GCC supports variable sized arrays in the middle of
1601 // structures.
1602 if (i != NumFields-1) {
1603 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1604 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001605 FD->setInvalidDecl();
1606 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 continue;
1608 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001609 // We support flexible arrays at the end of structs in other structs
1610 // as an extension.
1611 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1612 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001613 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001614 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001615 }
1616 }
1617 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 // Keep track of the number of named members.
1619 if (IdentifierInfo *II = FD->getIdentifier()) {
1620 // Detect duplicate member names.
1621 if (!FieldIDs.insert(II)) {
1622 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1623 // Find the previous decl.
1624 SourceLocation PrevLoc;
1625 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1626 assert(i != e && "Didn't find previous def!");
1627 if (RecFields[i]->getIdentifier() == II) {
1628 PrevLoc = RecFields[i]->getLocation();
1629 break;
1630 }
1631 }
1632 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001633 FD->setInvalidDecl();
1634 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001635 continue;
1636 }
1637 ++NumNamedMembers;
1638 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001639 }
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001642 if (Record)
1643 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001644 else {
1645 ObjcIvarDecl **ClsFields =
1646 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001647 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1648 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1649 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1650 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1651 ObjcImplementationDecl* IMPDecl =
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001652 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001653 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1654 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Steve Naroffa5997c42007-10-02 21:43:37 +00001655 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size());
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001656 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001657 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001658}
1659
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001660/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1661/// returns true, or false, accordingly.
1662/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1663bool Sema:: MatchTwoMethodDeclarations(const ObjcMethodDecl *Method,
1664 const ObjcMethodDecl *PrevMethod) {
1665 if (Method->getMethodType().getCanonicalType() !=
1666 PrevMethod->getMethodType().getCanonicalType())
1667 return false;
1668 for (int i = 0; i < Method->getNumParams(); i++) {
1669 ParmVarDecl *ParamDecl = Method->getParamDecl(i);
1670 ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
1671 if (ParamDecl->getCanonicalType() != PrevParamDecl->getCanonicalType())
1672 return false;
1673 }
1674 return true;
1675}
1676
Chris Lattnerfd5de472007-10-06 22:53:46 +00001677void Sema::ActOnAddMethodsToObjcDecl(Scope* S, DeclTy *classDecl,
Steve Naroff3a165b02007-10-03 21:00:46 +00001678 DeclTy **allMethods, unsigned allNum) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001679 Decl *ClassDecl = static_cast<Decl *>(classDecl);
1680
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001681 // FIXME: Fix this when we can handle methods declared in protocols.
1682 // See Parser::ParseObjCAtProtocolDeclaration
1683 if (!ClassDecl)
1684 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001685 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1686 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001687
Steve Naroffeefc4182007-10-08 21:05:34 +00001688 llvm::DenseMap<Selector, const ObjcMethodDecl*> InsMap;
1689 llvm::DenseMap<Selector, const ObjcMethodDecl*> ClsMap;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001690
1691 bool isClassDeclaration =
Chris Lattnerfd5de472007-10-06 22:53:46 +00001692 (isa<ObjcInterfaceDecl>(ClassDecl) || isa<ObjcCategoryDecl>(ClassDecl));
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001693
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001694 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001695 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001696 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1697 if (!Method) continue; // Already issued a diagnostic.
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001698 if (Method->isInstance()) {
1699 if (isClassDeclaration) {
1700 /// Check for instance method of the same name with incompatible types
Steve Naroffeefc4182007-10-08 21:05:34 +00001701 const ObjcMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001702 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001703 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001704 Method->getSelector().getName());
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001705 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1706 }
1707 else {
1708 insMethods.push_back(Method);
Steve Naroffeefc4182007-10-08 21:05:34 +00001709 InsMap[Method->getSelector()] = Method;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001710 }
1711 }
1712 else
1713 insMethods.push_back(Method);
1714 }
1715 else {
1716 if (isClassDeclaration) {
1717 /// Check for class method of the same name with incompatible types
Steve Naroffeefc4182007-10-08 21:05:34 +00001718 const ObjcMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001719 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001720 Diag(Method->getLocation(), diag::error_duplicate_method_decl,
Chris Lattnerf836e3f2007-10-07 01:33:16 +00001721 Method->getSelector().getName());
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001722 Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1723 }
1724 else {
1725 clsMethods.push_back(Method);
Steve Naroffeefc4182007-10-08 21:05:34 +00001726 ClsMap[Method->getSelector()] = Method;
Fariborz Jahanian85ff2642007-10-05 18:00:57 +00001727 }
1728 }
1729 else
1730 clsMethods.push_back(Method);
1731 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001732 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001733
1734 if (ObjcInterfaceDecl *I = dyn_cast<ObjcInterfaceDecl>(ClassDecl)) {
1735 I->ObjcAddMethods(&insMethods[0], insMethods.size(),
1736 &clsMethods[0], clsMethods.size());
1737 } else if (ObjcProtocolDecl *P = dyn_cast<ObjcProtocolDecl>(ClassDecl)) {
1738 P->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1739 &clsMethods[0], clsMethods.size());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001740 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001741 else if (ObjcCategoryDecl *C = dyn_cast<ObjcCategoryDecl>(ClassDecl)) {
1742 C->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1743 &clsMethods[0], clsMethods.size());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001744 }
Chris Lattnerfd5de472007-10-06 22:53:46 +00001745 else if (ObjcImplementationDecl *IC =
1746 dyn_cast<ObjcImplementationDecl>(ClassDecl)) {
1747 IC->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1748 &clsMethods[0], clsMethods.size());
1749 if (ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1750 ImplMethodsVsClassMethods(IC, IDecl);
1751 } else {
1752 ObjcCategoryImplDecl* CatImplClass = cast<ObjcCategoryImplDecl>(ClassDecl);
1753 CatImplClass->ObjcAddCatImplMethods(&insMethods[0], insMethods.size(),
1754 &clsMethods[0], clsMethods.size());
1755 ObjcInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1756 // Find category interface decl and then check that all methods declared
1757 // in this interface is implemented in the category @implementation.
1758 if (IDecl) {
1759 for (ObjcCategoryDecl *Categories = IDecl->getListCategories();
1760 Categories; Categories = Categories->getNextClassCategory()) {
Chris Lattner6a0e89e2007-10-06 23:12:31 +00001761 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
Chris Lattnerfd5de472007-10-06 22:53:46 +00001762 ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1763 break;
Fariborz Jahanian8f3fde02007-10-02 16:38:50 +00001764 }
1765 }
1766 }
1767 }
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001768}
1769
Steve Naroff37e58d12007-10-02 22:39:18 +00001770Sema::DeclTy *Sema::ActOnMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001771 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001772 // optional arguments. The number of types/arguments is obtained
1773 // from the Sel.getNumArgs().
1774 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1775 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001776 llvm::SmallVector<ParmVarDecl*, 16> Params;
1777
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001778 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001779 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001780 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001781 QualType::getFromOpaquePtr(ArgTypes[i]),
1782 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001783 Params.push_back(Param);
1784 }
Steve Naroffb216c882007-10-09 22:01:59 +00001785 QualType resultDeclType;
1786
1787 if (ReturnType)
1788 resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1789 else { // get the type for "id".
1790 IdentifierInfo *IdIdent = &Context.Idents.get("id");
1791 ScopedDecl *IdDecl = LookupScopedDecl(IdIdent, Decl::IDNS_Ordinary,
1792 SourceLocation(), TUScope);
1793 TypedefDecl *IdTypedef = dyn_cast_or_null<TypedefDecl>(IdDecl);
1794 assert(IdTypedef && "ActOnMethodDeclaration(): Couldn't find 'id' type");
1795 resultDeclType = IdTypedef->getUnderlyingType();
1796 }
Steve Naroff68d331a2007-09-27 14:38:14 +00001797 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1798 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001799 MethodType == tok::minus,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00001800 MethodDeclKind == tok::objc_optional ?
1801 ObjcMethodDecl::Optional :
1802 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001803 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001804 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001805}
1806
Steve Naroff08d92e42007-09-15 18:49:24 +00001807Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 DeclTy *lastEnumConst,
1809 SourceLocation IdLoc, IdentifierInfo *Id,
1810 SourceLocation EqualLoc, ExprTy *val) {
1811 theEnumDecl = theEnumDecl; // silence unused warning.
1812 EnumConstantDecl *LastEnumConst =
1813 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1814 Expr *Val = static_cast<Expr*>(val);
1815
Chris Lattner31e05722007-08-26 06:24:45 +00001816 // The scope passed in may not be a decl scope. Zip up the scope tree until
1817 // we find one that is.
1818 while ((S->getFlags() & Scope::DeclScope) == 0)
1819 S = S->getParent();
1820
Reid Spencer5f016e22007-07-11 17:01:13 +00001821 // Verify that there isn't already something declared with this name in this
1822 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001823 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1824 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001825 if (S->isDeclScope(PrevDecl)) {
1826 if (isa<EnumConstantDecl>(PrevDecl))
1827 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1828 else
1829 Diag(IdLoc, diag::err_redefinition, Id->getName());
1830 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1831 // FIXME: Don't leak memory: delete Val;
1832 return 0;
1833 }
1834 }
1835
1836 llvm::APSInt EnumVal(32);
1837 QualType EltTy;
1838 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001839 // Make sure to promote the operand type to int.
1840 UsualUnaryConversions(Val);
1841
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1843 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001844 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001845 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1846 Id->getName());
1847 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001848 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001849 } else {
1850 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001851 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001852 }
1853
1854 if (!Val) {
1855 if (LastEnumConst) {
1856 // Assign the last value + 1.
1857 EnumVal = LastEnumConst->getInitVal();
1858 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001859
1860 // Check for overflow on increment.
1861 if (EnumVal < LastEnumConst->getInitVal())
1862 Diag(IdLoc, diag::warn_enum_value_overflow);
1863
Chris Lattnerb7416f92007-08-27 17:37:24 +00001864 EltTy = LastEnumConst->getType();
1865 } else {
1866 // First value, set to zero.
1867 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001868 EnumVal.zextOrTrunc(
1869 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001870 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 }
1872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1874 LastEnumConst);
1875
1876 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001877 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001878 Id->setFETokenInfo(New);
1879 S->AddDecl(New);
1880 return New;
1881}
1882
Steve Naroff08d92e42007-09-15 18:49:24 +00001883void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001884 DeclTy **Elements, unsigned NumElements) {
1885 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1886 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1887
Chris Lattnere37f0be2007-08-28 05:10:31 +00001888 // TODO: If the result value doesn't fit in an int, it must be a long or long
1889 // long value. ISO C does not support this, but GCC does as an extension,
1890 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001891 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001892
1893
Chris Lattnerac609682007-08-28 06:15:15 +00001894 // Verify that all the values are okay, compute the size of the values, and
1895 // reverse the list.
1896 unsigned NumNegativeBits = 0;
1897 unsigned NumPositiveBits = 0;
1898
1899 // Keep track of whether all elements have type int.
1900 bool AllElementsInt = true;
1901
Reid Spencer5f016e22007-07-11 17:01:13 +00001902 EnumConstantDecl *EltList = 0;
1903 for (unsigned i = 0; i != NumElements; ++i) {
1904 EnumConstantDecl *ECD =
1905 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1906 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001907
1908 // If the enum value doesn't fit in an int, emit an extension warning.
1909 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1910 "Should have promoted value to int");
1911 const llvm::APSInt &InitVal = ECD->getInitVal();
1912 if (InitVal.getBitWidth() > IntWidth) {
1913 llvm::APSInt V(InitVal);
1914 V.trunc(IntWidth);
1915 V.extend(InitVal.getBitWidth());
1916 if (V != InitVal)
1917 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1918 InitVal.toString());
1919 }
Chris Lattnerac609682007-08-28 06:15:15 +00001920
1921 // Keep track of the size of positive and negative values.
1922 if (InitVal.isUnsigned() || !InitVal.isNegative())
1923 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1924 else
1925 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001926
Chris Lattnerac609682007-08-28 06:15:15 +00001927 // Keep track of whether every enum element has type int (very commmon).
1928 if (AllElementsInt)
1929 AllElementsInt = ECD->getType() == Context.IntTy;
1930
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 ECD->setNextDeclarator(EltList);
1932 EltList = ECD;
1933 }
1934
Chris Lattnerac609682007-08-28 06:15:15 +00001935 // Figure out the type that should be used for this enum.
1936 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1937 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001938 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001939
1940 if (NumNegativeBits) {
1941 // If there is a negative value, figure out the smallest integer type (of
1942 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001943 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001944 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001945 BestWidth = IntWidth;
1946 } else {
1947 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1948 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001949 BestType = Context.LongTy;
1950 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001951 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1952 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001953 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1954 BestType = Context.LongLongTy;
1955 }
1956 }
1957 } else {
1958 // If there is no negative value, figure out which of uint, ulong, ulonglong
1959 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001960 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001961 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001962 BestWidth = IntWidth;
1963 } else if (NumPositiveBits <=
1964 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001965 BestType = Context.UnsignedLongTy;
1966 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001967 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1968 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001969 "How could an initializer get larger than ULL?");
1970 BestType = Context.UnsignedLongLongTy;
1971 }
1972 }
1973
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001974 // Loop over all of the enumerator constants, changing their types to match
1975 // the type of the enum if needed.
1976 for (unsigned i = 0; i != NumElements; ++i) {
1977 EnumConstantDecl *ECD =
1978 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1979 if (!ECD) continue; // Already issued a diagnostic.
1980
1981 // Standard C says the enumerators have int type, but we allow, as an
1982 // extension, the enumerators to be larger than int size. If each
1983 // enumerator value fits in an int, type it as an int, otherwise type it the
1984 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1985 // that X has type 'int', not 'unsigned'.
1986 if (ECD->getType() == Context.IntTy)
1987 continue; // Already int type.
1988
1989 // Determine whether the value fits into an int.
1990 llvm::APSInt InitVal = ECD->getInitVal();
1991 bool FitsInInt;
1992 if (InitVal.isUnsigned() || !InitVal.isNegative())
1993 FitsInInt = InitVal.getActiveBits() < IntWidth;
1994 else
1995 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1996
1997 // If it fits into an integer type, force it. Otherwise force it to match
1998 // the enum decl type.
1999 QualType NewTy;
2000 unsigned NewWidth;
2001 bool NewSign;
2002 if (FitsInInt) {
2003 NewTy = Context.IntTy;
2004 NewWidth = IntWidth;
2005 NewSign = true;
2006 } else if (ECD->getType() == BestType) {
2007 // Already the right type!
2008 continue;
2009 } else {
2010 NewTy = BestType;
2011 NewWidth = BestWidth;
2012 NewSign = BestType->isSignedIntegerType();
2013 }
2014
2015 // Adjust the APSInt value.
2016 InitVal.extOrTrunc(NewWidth);
2017 InitVal.setIsSigned(NewSign);
2018 ECD->setInitVal(InitVal);
2019
2020 // Adjust the Expr initializer and type.
2021 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2022 ECD->setType(NewTy);
2023 }
Chris Lattnerac609682007-08-28 06:15:15 +00002024
Chris Lattnere00b18c2007-08-28 18:24:31 +00002025 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00002026}
2027
2028void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
2029 if (!current) return;
2030
2031 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
2032 // remember this in the LastInGroupList list.
2033 if (last)
2034 LastInGroupList.push_back((Decl*)last);
2035}
2036
2037void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
2038 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
2039 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
2040 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
2041 if (!newType.isNull()) // install the new vector type into the decl
2042 vDecl->setType(newType);
2043 }
2044 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
2045 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
2046 rawAttr);
2047 if (!newType.isNull()) // install the new vector type into the decl
2048 tDecl->setUnderlyingType(newType);
2049 }
2050 }
Steve Naroff73322922007-07-18 18:00:27 +00002051 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00002052 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
2053 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
2054 else
Steve Naroff73322922007-07-18 18:00:27 +00002055 Diag(rawAttr->getAttributeLoc(),
2056 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00002057 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002058 // FIXME: add other attributes...
2059}
2060
2061void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
2062 AttributeList *declarator_postfix) {
2063 while (declspec_prefix) {
2064 HandleDeclAttribute(New, declspec_prefix);
2065 declspec_prefix = declspec_prefix->getNext();
2066 }
2067 while (declarator_postfix) {
2068 HandleDeclAttribute(New, declarator_postfix);
2069 declarator_postfix = declarator_postfix->getNext();
2070 }
2071}
2072
Steve Naroffbea0b342007-07-29 16:33:31 +00002073void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
2074 AttributeList *rawAttr) {
2075 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00002076 // check the attribute arugments.
2077 if (rawAttr->getNumArgs() != 1) {
2078 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2079 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00002080 return;
Steve Naroff73322922007-07-18 18:00:27 +00002081 }
2082 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2083 llvm::APSInt vecSize(32);
2084 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
2085 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2086 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002087 return;
Steve Naroff73322922007-07-18 18:00:27 +00002088 }
2089 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2090 // in conjunction with complex types (pointers, arrays, functions, etc.).
2091 Type *canonType = curType.getCanonicalType().getTypePtr();
2092 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2093 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2094 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00002095 return;
Steve Naroff73322922007-07-18 18:00:27 +00002096 }
2097 // unlike gcc's vector_size attribute, the size is specified as the
2098 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002099 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00002100
2101 if (vectorSize == 0) {
2102 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2103 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00002104 return;
Steve Naroff73322922007-07-18 18:00:27 +00002105 }
Steve Naroffbea0b342007-07-29 16:33:31 +00002106 // Instantiate/Install the vector type, the number of elements is > 0.
2107 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
2108 // Remember this typedef decl, we will need it later for diagnostics.
2109 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00002110}
2111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00002113 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 // check the attribute arugments.
2115 if (rawAttr->getNumArgs() != 1) {
2116 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
2117 std::string("1"));
2118 return QualType();
2119 }
2120 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2121 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002122 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002123 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2124 sizeExpr->getSourceRange());
2125 return QualType();
2126 }
2127 // navigate to the base type - we need to provide for vector pointers,
2128 // vector arrays, and functions returning vectors.
2129 Type *canonType = curType.getCanonicalType().getTypePtr();
2130
Steve Naroff73322922007-07-18 18:00:27 +00002131 if (canonType->isPointerType() || canonType->isArrayType() ||
2132 canonType->isFunctionType()) {
2133 assert(1 && "HandleVector(): Complex type construction unimplemented");
2134 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2135 do {
2136 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2137 canonType = PT->getPointeeType().getTypePtr();
2138 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2139 canonType = AT->getElementType().getTypePtr();
2140 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2141 canonType = FT->getResultType().getTypePtr();
2142 } while (canonType->isPointerType() || canonType->isArrayType() ||
2143 canonType->isFunctionType());
2144 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 }
2146 // the base type must be integer or float.
2147 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2148 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2149 curType.getCanonicalType().getAsString());
2150 return QualType();
2151 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002152 unsigned typeSize = static_cast<unsigned>(
2153 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002154 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002155 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002156
2157 // the vector size needs to be an integral multiple of the type size.
2158 if (vectorSize % typeSize) {
2159 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2160 sizeExpr->getSourceRange());
2161 return QualType();
2162 }
2163 if (vectorSize == 0) {
2164 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2165 sizeExpr->getSourceRange());
2166 return QualType();
2167 }
2168 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2169 // the number of elements to be a power of two (unlike GCC).
2170 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002171 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002172}
2173