blob: 2b0e1452f6e114d4261a492c2142f9b1930be447 [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"
18#include "clang/AST/Expr.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Parse/Scope.h"
22#include "clang/Lex/IdentifierTable.h"
23#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"
27using namespace clang;
28
Reid Spencer5f016e22007-07-11 17:01:13 +000029Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) const {
Steve Naroff3536b442007-09-06 21:24:23 +000030 Decl *IIDecl = II.getFETokenInfo<Decl>();
31 if (dyn_cast_or_null<TypedefDecl>(IIDecl) ||
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +000032 dyn_cast_or_null<ObjcInterfaceDecl>(IIDecl))
Steve Naroff3536b442007-09-06 21:24:23 +000033 return IIDecl;
34 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000035}
36
37void Sema::PopScope(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 Jahanian9d048ff2007-09-29 00:54:24 +000081/// ObjcInterfaceDecl - Look up a for a class declaration in the scope.
82/// return 0 if one not found.
83ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(Scope *S,
84 IdentifierInfo *Id,
85 SourceLocation IdLoc) {
86 ScopedDecl *IdDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
87 IdLoc, S);
88 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
89 IdDecl = 0;
90 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
91}
92
Reid Spencer5f016e22007-07-11 17:01:13 +000093/// LookupScopedDecl - Look up the inner-most declaration in the specified
94/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +000095ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
96 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +000097 if (II == 0) return 0;
98 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
99
100 // Scan up the scope chain looking for a decl that matches this identifier
101 // that is in the appropriate namespace. This search should not take long, as
102 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000103 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (D->getIdentifierNamespace() == NS)
105 return D;
106
107 // If we didn't find a use of this identifier, and if the identifier
108 // corresponds to a compiler builtin, create the decl object for the builtin
109 // now, injecting it into translation unit scope, and return it.
110 if (NS == Decl::IDNS_Ordinary) {
111 // If this is a builtin on some other target, or if this builtin varies
112 // across targets (e.g. in type), emit a diagnostic and mark the translation
113 // unit non-portable for using it.
114 if (II->isNonPortableBuiltin()) {
115 // Only emit this diagnostic once for this builtin.
116 II->setNonPortableBuiltin(false);
117 Context.Target.DiagnoseNonPortability(IdLoc,
118 diag::port_target_builtin_use);
119 }
120 // If this is a builtin on this (or all) targets, create the decl.
121 if (unsigned BuiltinID = II->getBuiltinID())
122 return LazilyCreateBuiltin(II, BuiltinID, S);
123 }
124 return 0;
125}
126
127/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
128/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000129ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 Builtin::ID BID = (Builtin::ID)bid;
131
132 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
133 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000134 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135
136 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000137 if (Scope *FnS = S->getFnParent())
138 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 while (S->getParent())
140 S = S->getParent();
141 S->AddDecl(New);
142
143 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000144 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 // Scan until we find the last (outermost) decl in the id chain.
146 while (LastDecl->getNext())
147 LastDecl = LastDecl->getNext();
148 // Insert before (outside) it.
149 LastDecl->setNext(New);
150 } else {
151 II->setFETokenInfo(New);
152 }
153 // Make sure clients iterating over decls see this.
154 LastInGroupList.push_back(New);
155
156 return New;
157}
158
159/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
160/// and scope as a previous declaration 'Old'. Figure out how to resolve this
161/// situation, merging decls or emitting diagnostics as appropriate.
162///
Steve Naroff8e74c932007-09-13 21:41:19 +0000163TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 // Verify the old decl was also a typedef.
165 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
166 if (!Old) {
167 Diag(New->getLocation(), diag::err_redefinition_different_kind,
168 New->getName());
169 Diag(OldD->getLocation(), diag::err_previous_definition);
170 return New;
171 }
172
173 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
174 // TODO: This is totally simplistic. It should handle merging functions
175 // together etc, merging extern int X; int X; ...
176 Diag(New->getLocation(), diag::err_redefinition, New->getName());
177 Diag(Old->getLocation(), diag::err_previous_definition);
178 return New;
179}
180
181/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
182/// and scope as a previous declaration 'Old'. Figure out how to resolve this
183/// situation, merging decls or emitting diagnostics as appropriate.
184///
Steve Naroff8e74c932007-09-13 21:41:19 +0000185FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Verify the old decl was also a function.
187 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
188 if (!Old) {
189 Diag(New->getLocation(), diag::err_redefinition_different_kind,
190 New->getName());
191 Diag(OldD->getLocation(), diag::err_previous_definition);
192 return New;
193 }
194
195 // This is not right, but it's a start. If 'Old' is a function prototype with
196 // the same type as 'New', silently allow this. FIXME: We should link up decl
197 // objects here.
198 if (Old->getBody() == 0 &&
199 Old->getCanonicalType() == New->getCanonicalType()) {
200 return New;
201 }
202
203 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
204 // TODO: This is totally simplistic. It should handle merging functions
205 // together etc, merging extern int X; int X; ...
206 Diag(New->getLocation(), diag::err_redefinition, New->getName());
207 Diag(Old->getLocation(), diag::err_previous_definition);
208 return New;
209}
210
211/// MergeVarDecl - We just parsed a variable 'New' which has the same name
212/// and scope as a previous declaration 'Old'. Figure out how to resolve this
213/// situation, merging decls or emitting diagnostics as appropriate.
214///
215/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
216/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
217///
Steve Naroff8e74c932007-09-13 21:41:19 +0000218VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000219 // Verify the old decl was also a variable.
220 VarDecl *Old = dyn_cast<VarDecl>(OldD);
221 if (!Old) {
222 Diag(New->getLocation(), diag::err_redefinition_different_kind,
223 New->getName());
224 Diag(OldD->getLocation(), diag::err_previous_definition);
225 return New;
226 }
Steve Narofffb22d962007-08-30 01:06:46 +0000227 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
228 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
229 bool OldIsTentative = false;
230
231 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
232 // Handle C "tentative" external object definitions. FIXME: finish!
233 if (!OldFSDecl->getInit() &&
234 (OldFSDecl->getStorageClass() == VarDecl::None ||
235 OldFSDecl->getStorageClass() == VarDecl::Static))
236 OldIsTentative = true;
237 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 // Verify the types match.
239 if (Old->getCanonicalType() != New->getCanonicalType()) {
240 Diag(New->getLocation(), diag::err_redefinition, New->getName());
241 Diag(Old->getLocation(), diag::err_previous_definition);
242 return New;
243 }
244 // We've verified the types match, now check if Old is "extern".
245 if (Old->getStorageClass() != VarDecl::Extern) {
246 Diag(New->getLocation(), diag::err_redefinition, New->getName());
247 Diag(Old->getLocation(), diag::err_previous_definition);
248 }
249 return New;
250}
251
252/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
253/// no declarator (e.g. "struct foo;") is parsed.
254Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
255 // TODO: emit error on 'int;' or 'const enum foo;'.
256 // TODO: emit error on 'typedef int;'
257 // if (!DS.isMissingDeclaratorOk()) Diag(...);
258
259 return 0;
260}
261
Steve Naroff9e8925e2007-09-04 14:36:54 +0000262bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000263 AssignmentCheckResult result;
264 SourceLocation loc = Init->getLocStart();
265 // Get the type before calling CheckSingleAssignmentConstraints(), since
266 // it can promote the expression.
267 QualType rhsType = Init->getType();
268
269 result = CheckSingleAssignmentConstraints(DeclType, Init);
270
271 // decode the result (notice that extensions still return a type).
272 switch (result) {
273 case Compatible:
274 break;
275 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000276 // FIXME: tighten up this check which should allow:
277 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
278 if (rhsType == Context.getPointerType(Context.CharTy))
279 break;
Steve Narofff0090632007-09-02 02:04:30 +0000280 Diag(loc, diag::err_typecheck_assign_incompatible,
281 DeclType.getAsString(), rhsType.getAsString(),
282 Init->getSourceRange());
283 return true;
284 case PointerFromInt:
285 // check for null pointer constant (C99 6.3.2.3p3)
286 if (!Init->isNullPointerConstant(Context)) {
287 Diag(loc, diag::ext_typecheck_assign_pointer_int,
288 DeclType.getAsString(), rhsType.getAsString(),
289 Init->getSourceRange());
290 return true;
291 }
292 break;
293 case IntFromPointer:
294 Diag(loc, diag::ext_typecheck_assign_pointer_int,
295 DeclType.getAsString(), rhsType.getAsString(),
296 Init->getSourceRange());
297 break;
298 case IncompatiblePointer:
299 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
300 DeclType.getAsString(), rhsType.getAsString(),
301 Init->getSourceRange());
302 break;
303 case CompatiblePointerDiscardsQualifiers:
304 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
305 DeclType.getAsString(), rhsType.getAsString(),
306 Init->getSourceRange());
307 break;
308 }
309 return false;
310}
311
Steve Naroff9e8925e2007-09-04 14:36:54 +0000312bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
313 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000314 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000315 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000316
317 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
318 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
319 return true;
320 } else if (CheckSingleInitializer(expr, ElementType)) {
321 return true; // types weren't compatible.
322 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000323 if (savExpr != expr) // The type was promoted, update initializer list.
324 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000325 return false;
326}
327
328void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
329 QualType ElementType, bool isStatic,
330 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000331 for (unsigned i = 0; i < IList->getNumInits(); i++) {
332 Expr *expr = IList->getInit(i);
333
Steve Naroff371227d2007-09-04 02:20:04 +0000334 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
335 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000336 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000337 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
338 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000339 }
Steve Naroff371227d2007-09-04 02:20:04 +0000340 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000341 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000342 }
Steve Naroff371227d2007-09-04 02:20:04 +0000343 nInitializers++;
344 }
345 return;
346}
347
348// FIXME: Doesn't deal with arrays of structures yet.
349void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
350 QualType ElementType, bool isStatic,
351 int &totalInits, bool &hadError) {
352 int maxElementsAtThisLevel = 0;
353 int nInitsAtLevel = 0;
354
355 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
356 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000357 maxElementsAtThisLevel = CAT->getMaximumElements();
358 // Set DeclType, used below to recurse (for multi-dimensional arrays).
359 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000360 } else if (DeclType->isScalarType()) {
361 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
362 IList->getSourceRange());
363 maxElementsAtThisLevel = 1;
364 }
365 // The empty init list "{ }" is treated specially below.
366 unsigned numInits = IList->getNumInits();
367 if (numInits) {
368 for (unsigned i = 0; i < numInits; i++) {
369 Expr *expr = IList->getInit(i);
370
371 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
372 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
373 totalInits, hadError);
374 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000375 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000376 nInitsAtLevel++; // increment the number of initializers at this level.
377 totalInits--; // decrement the total number of initializers.
378
379 // Check if we have space for another initializer.
380 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
381 Diag(expr->getLocStart(), diag::warn_excess_initializers,
382 expr->getSourceRange());
383 }
384 }
385 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
386 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
387 } else {
388 // we have an initializer list with no elements.
389 totalInits -= maxElementsAtThisLevel;
390 if (totalInits < 0)
391 Diag(IList->getLocStart(), diag::warn_excess_initializers,
392 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000393 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000394 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000395}
396
Steve Naroff9e8925e2007-09-04 14:36:54 +0000397bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000398 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000399 if (!InitList)
400 return CheckSingleInitializer(Init, DeclType);
401
Steve Narofff0090632007-09-02 02:04:30 +0000402 // We have an InitListExpr, make sure we set the type.
403 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000404
405 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000406
Steve Naroff38374b02007-09-02 20:30:18 +0000407 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
408 // of unknown size ("[]") or an object type that is not a variable array type.
409 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
410 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000411 if (expr)
412 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
413 expr->getSourceRange());
414
Steve Naroff7cf8c442007-09-04 21:13:33 +0000415 // We have a VariableArrayType with unknown size. Note that only the first
416 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000417 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000418 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
419 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000420 if (!hadError) {
421 // Return a new array type from the number of initializers (C99 6.7.8p22).
422 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000423 ConstVal = numInits;
424 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000425 ArrayType::Normal, 0);
426 }
427 return hadError;
428 }
429 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000430 int maxElements = CAT->getMaximumElements();
431 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
432 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000433 return hadError;
434 }
Steve Naroff371227d2007-09-04 02:20:04 +0000435 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
436 int maxElements = 1;
437 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
438 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000439 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000440 }
441 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000442 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000443}
444
Reid Spencer5f016e22007-07-11 17:01:13 +0000445Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000446Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000447 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 IdentifierInfo *II = D.getIdentifier();
449
Chris Lattnere80a59c2007-07-25 00:24:17 +0000450 // All of these full declarators require an identifier. If it doesn't have
451 // one, the ParsedFreeStandingDeclSpec action should be used.
452 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000453 Diag(D.getDeclSpec().getSourceRange().Begin(),
454 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000455 D.getDeclSpec().getSourceRange(), D.getSourceRange());
456 return 0;
457 }
458
Chris Lattner31e05722007-08-26 06:24:45 +0000459 // The scope passed in may not be a decl scope. Zip up the scope tree until
460 // we find one that is.
461 while ((S->getFlags() & Scope::DeclScope) == 0)
462 S = S->getParent();
463
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000465 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
466 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 if (PrevDecl && !S->isDeclScope(PrevDecl))
468 PrevDecl = 0; // If in outer scope, it isn't the same thing.
469
Steve Naroffc752d042007-09-13 18:10:37 +0000470 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000471 bool InvalidDecl = false;
472
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
474 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
475 if (!NewTD) return 0;
476
477 // Handle attributes prior to checking for duplicates in MergeVarDecl
478 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
479 D.getAttributes());
480 // Merge the decl with the existing one if appropriate.
481 if (PrevDecl) {
482 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
483 if (NewTD == 0) return 0;
484 }
485 New = NewTD;
486 if (S->getParent() == 0) {
487 // C99 6.7.7p2: If a typedef name specifies a variably modified type
488 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000489 if (const VariableArrayType *VAT =
490 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
491 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
492 VAT->getSizeExpr()->getSourceRange());
493 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000494 }
495 }
496 } else if (D.isFunctionDeclarator()) {
497 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000498 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000499
Chris Lattner271f1a62007-09-27 15:15:46 +0000500 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 switch (D.getDeclSpec().getStorageClassSpec()) {
502 default: assert(0 && "Unknown storage class!");
503 case DeclSpec::SCS_auto:
504 case DeclSpec::SCS_register:
505 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
506 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000507 InvalidDecl = true;
508 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
510 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
511 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
512 }
513
514 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000515 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 LastDeclarator);
517
518 // Merge the decl with the existing one if appropriate.
519 if (PrevDecl) {
520 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
521 if (NewFD == 0) return 0;
522 }
523 New = NewFD;
524 } else {
525 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000526 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000527
528 VarDecl *NewVD;
529 VarDecl::StorageClass SC;
530 switch (D.getDeclSpec().getStorageClassSpec()) {
531 default: assert(0 && "Unknown storage class!");
532 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
533 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
534 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
535 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
536 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
537 }
538 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 // C99 6.9p2: The storage-class specifiers auto and register shall not
540 // appear in the declaration specifiers in an external declaration.
541 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
542 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
543 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000544 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000547 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000549 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 // Handle attributes prior to checking for duplicates in MergeVarDecl
551 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
552 D.getAttributes());
553
554 // Merge the decl with the existing one if appropriate.
555 if (PrevDecl) {
556 NewVD = MergeVarDecl(NewVD, PrevDecl);
557 if (NewVD == 0) return 0;
558 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 New = NewVD;
560 }
561
562 // If this has an identifier, add it to the scope stack.
563 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000564 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 II->setFETokenInfo(New);
566 S->AddDecl(New);
567 }
568
569 if (S->getParent() == 0)
570 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000571
572 // If any semantic error occurred, mark the decl as invalid.
573 if (D.getInvalidType() || InvalidDecl)
574 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000575
576 return New;
577}
578
Steve Naroffbb204692007-09-12 14:07:44 +0000579void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000580 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000581 Expr *Init = static_cast<Expr *>(init);
582
Steve Naroff410e3e22007-09-12 20:13:48 +0000583 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000584
Steve Naroff410e3e22007-09-12 20:13:48 +0000585 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
586 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000587 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
588 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000589 RealDecl->setInvalidDecl();
590 return;
591 }
Steve Naroffbb204692007-09-12 14:07:44 +0000592 // Get the decls type and save a reference for later, since
593 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000594 QualType DclT = VDecl->getType(), SavT = DclT;
595 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000596 VarDecl::StorageClass SC = BVD->getStorageClass();
597 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000598 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000599 BVD->setInvalidDecl();
600 } else if (!BVD->isInvalidDecl()) {
601 CheckInitializer(Init, DclT, SC == VarDecl::Static);
602 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000603 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000604 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000605 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000606 if (!FVD->isInvalidDecl())
607 CheckInitializer(Init, DclT, true);
608 }
609 // If the type changed, it means we had an incomplete type that was
610 // completed by the initializer. For example:
611 // int ary[] = { 1, 3, 5 };
612 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000613 if (!VDecl->isInvalidDecl() && (DclT != SavT))
614 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000615
616 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000617 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000618 return;
619}
620
Reid Spencer5f016e22007-07-11 17:01:13 +0000621/// The declarators are chained together backwards, reverse the list.
622Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
623 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000624 Decl *GroupDecl = static_cast<Decl*>(group);
625 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000626 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000627
628 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
629 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000630 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000632 else { // reverse the list.
633 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000634 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000635 Group->setNextDeclarator(NewGroup);
636 NewGroup = Group;
637 Group = Next;
638 }
639 }
640 // Perform semantic analysis that depends on having fully processed both
641 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000642 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000643 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
644 if (!IDecl)
645 continue;
646 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
647 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
648 QualType T = IDecl->getType();
649
650 // C99 6.7.5.2p2: If an identifier is declared to be an object with
651 // static storage duration, it shall not have a variable length array.
652 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
653 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
654 if (VLA->getSizeExpr()) {
655 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
656 IDecl->setInvalidDecl();
657 }
658 }
659 }
660 // Block scope. C99 6.7p7: If an identifier for an object is declared with
661 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
662 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
663 if (T->isIncompleteType()) {
664 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
665 T.getAsString());
666 IDecl->setInvalidDecl();
667 }
668 }
669 // File scope. C99 6.9.2p2: A declaration of an identifier for and
670 // object that has file scope without an initializer, and without a
671 // storage-class specifier or with the storage-class specifier "static",
672 // constitutes a tentative definition. Note: A tentative definition with
673 // external linkage is valid (C99 6.2.2p5).
674 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
675 // C99 6.9.2p3: If the declaration of an identifier for an object is
676 // a tentative definition and has internal linkage (C99 6.2.2p3), the
677 // declared type shall not be an incomplete type.
678 if (T->isIncompleteType()) {
679 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
680 T.getAsString());
681 IDecl->setInvalidDecl();
682 }
683 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 }
685 return NewGroup;
686}
Steve Naroffe1223f72007-08-28 03:03:08 +0000687
688// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000689ParmVarDecl *
690Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
691 Scope *FnScope) {
692 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
693
694 IdentifierInfo *II = PI.Ident;
695 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
696 // Can this happen for params? We already checked that they don't conflict
697 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000698 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 PI.IdentLoc, FnScope)) {
700
701 }
702
703 // FIXME: Handle storage class (auto, register). No declarator?
704 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000705
706 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
707 // Doing the promotion here has a win and a loss. The win is the type for
708 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
709 // code generator). The loss is the orginal type isn't preserved. For example:
710 //
711 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
712 // int blockvardecl[5];
713 // sizeof(parmvardecl); // size == 4
714 // sizeof(blockvardecl); // size == 20
715 // }
716 //
717 // For expressions, all implicit conversions are captured using the
718 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
719 //
720 // FIXME: If a source translation tool needs to see the original type, then
721 // we need to consider storing both types (in ParmVarDecl)...
722 //
723 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
724 if (const ArrayType *AT = parmDeclType->getAsArrayType())
725 parmDeclType = Context.getPointerType(AT->getElementType());
726 else if (parmDeclType->isFunctionType())
727 parmDeclType = Context.getPointerType(parmDeclType);
728
729 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000730 VarDecl::None, 0);
731 if (PI.InvalidType)
732 New->setInvalidDecl();
733
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 // If this has an identifier, add it to the scope stack.
735 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000736 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 II->setFETokenInfo(New);
738 FnScope->AddDecl(New);
739 }
740
741 return New;
742}
743
744
745Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
746 assert(CurFunctionDecl == 0 && "Function parsing confused");
747 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
748 "Not a function declarator!");
749 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
750
751 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
752 // for a K&R function.
753 if (!FTI.hasPrototype) {
754 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
755 if (FTI.ArgInfo[i].TypeInfo == 0) {
756 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
757 FTI.ArgInfo[i].Ident->getName());
758 // Implicitly declare the argument as type 'int' for lack of a better
759 // type.
760 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
761 }
762 }
763
764 // Since this is a function definition, act as though we have information
765 // about the arguments.
766 FTI.hasPrototype = true;
767 } else {
768 // FIXME: Diagnose arguments without names in C.
769
770 }
771
772 Scope *GlobalScope = FnBodyScope->getParent();
773
774 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000775 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 CurFunctionDecl = FD;
777
778 // Create Decl objects for each parameter, adding them to the FunctionDecl.
779 llvm::SmallVector<ParmVarDecl*, 16> Params;
780
781 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
782 // no arguments, not a function that takes a single void argument.
783 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
784 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
785 // empty arg list, don't push any params.
786 } else {
787 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
788 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
789 }
790
791 FD->setParams(&Params[0], Params.size());
792
793 return FD;
794}
795
796Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
797 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
798 FD->setBody((Stmt*)Body);
799
800 assert(FD == CurFunctionDecl && "Function parsing confused");
801 CurFunctionDecl = 0;
802
803 // Verify and clean out per-function state.
804
805 // Check goto/label use.
806 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
807 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
808 // Verify that we have no forward references left. If so, there was a goto
809 // or address of a label taken, but no definition of it. Label fwd
810 // definitions are indicated with a null substmt.
811 if (I->second->getSubStmt() == 0) {
812 LabelStmt *L = I->second;
813 // Emit error.
814 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
815
816 // At this point, we have gotos that use the bogus label. Stitch it into
817 // the function body so that they aren't leaked and that the AST is well
818 // formed.
819 L->setSubStmt(new NullStmt(L->getIdentLoc()));
820 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
821 }
822 }
823 LabelMap.clear();
824
825 return FD;
826}
827
828
829/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
830/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000831ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
832 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 if (getLangOptions().C99) // Extension in C99.
834 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
835 else // Legal in C90, but warn about it.
836 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
837
838 // FIXME: handle stuff like:
839 // void foo() { extern float X(); }
840 // void bar() { X(); } <-- implicit decl for X in another scope.
841
842 // Set a Declarator for the implicit definition: int foo();
843 const char *Dummy;
844 DeclSpec DS;
845 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
846 Error = Error; // Silence warning.
847 assert(!Error && "Error setting up implicit decl!");
848 Declarator D(DS, Declarator::BlockContext);
849 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
850 D.SetIdentifier(&II, Loc);
851
852 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000853 if (Scope *FnS = S->getFnParent())
854 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000855 while (S->getParent())
856 S = S->getParent();
857
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000858 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000859}
860
861
862TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000863 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
865
866 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000867 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000868
869 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000870 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
871 T, LastDeclarator);
872 if (D.getInvalidType())
873 NewTD->setInvalidDecl();
874 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000875}
876
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000877Sema::DeclTy *Sema::ObjcStartClassInterface(Scope* S,
878 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000879 IdentifierInfo *ClassName, SourceLocation ClassLoc,
880 IdentifierInfo *SuperName, SourceLocation SuperLoc,
881 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
882 AttributeList *AttrList) {
883 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000884
885 // Check for another declaration kind with the same name.
886 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
887 ClassLoc, S);
888 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
889 && !isa<ObjcProtocolDecl>(PrevDecl)) {
890 Diag(ClassLoc, diag::err_redefinition_different_kind,
891 ClassName->getName());
892 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
893 }
894
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000895 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000896 if (IDecl) {
897 // Class already seen. Is it a forward declaration?
898 if (!IDecl->getIsForwardDecl())
899 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000900 else {
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000901 IDecl->setIsForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000902 IDecl->AllocIntfRefProtocols(NumProtocols);
903 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000904 }
905 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000906 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000907
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000908 // Chain & install the interface decl into the identifier.
909 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
910 ClassName->setFETokenInfo(IDecl);
911 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000912
913 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000914 ObjcInterfaceDecl* SuperClassEntry = 0;
915 // Check if a different kind of symbol declared in this scope.
916 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
917 SuperLoc, S);
918 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
919 && !isa<ObjcProtocolDecl>(PrevDecl)) {
920 Diag(SuperLoc, diag::err_redefinition_different_kind,
921 SuperName->getName());
922 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000923 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000924 else {
925 // Check that super class is previously defined
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000926 SuperClassEntry = getObjCInterfaceDecl(S, SuperName, SuperLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000927
928 if (!SuperClassEntry || SuperClassEntry->getIsForwardDecl()) {
929 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
930 ClassName->getName());
931 }
932 }
933 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000934 }
935
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000936 /// Check then save referenced protocols
937 for (unsigned int i = 0; i != NumProtocols; i++) {
938 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtocolNames[i]);
939 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
940 Diag(ClassLoc, diag::err_undef_protocolref,
941 ProtocolNames[i]->getName(),
942 ClassName->getName());
943 IDecl->setIntfRefProtocols((int)i, RefPDecl);
944 }
945
Steve Naroff3536b442007-09-06 21:24:23 +0000946 return IDecl;
947}
948
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000949Sema::DeclTy *Sema::ObjcStartProtoInterface(Scope* S,
950 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000951 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
952 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
953 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000954 ObjcProtocolDecl *PDecl = Context.getObjCProtocolDecl(ProtocolName);
955 if (PDecl) {
956 // Protocol already seen. Better be a forward protocol declaration
957 if (!PDecl->getIsForwardProtoDecl())
958 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
959 ProtocolName->getName());
960 else {
961 PDecl->setIsForwardProtoDecl(false);
962 PDecl->AllocReferencedProtocols(NumProtoRefs);
963 }
964 }
965 else {
966 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
967 ProtocolName);
968 PDecl->setIsForwardProtoDecl(false);
969 // Chain & install the protocol decl into the identifier.
970 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
971 ProtocolName->setFETokenInfo(PDecl);
972 Context.setObjCProtocolDecl(ProtocolName, PDecl);
973 }
974
975 /// Check then save referenced protocols
976 for (unsigned int i = 0; i != NumProtoRefs; i++) {
977 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtoRefNames[i]);
978 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
979 Diag(ProtocolLoc, diag::err_undef_protocolref,
980 ProtoRefNames[i]->getName(),
981 ProtocolName->getName());
982 PDecl->setReferencedProtocols((int)i, RefPDecl);
983 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000984
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000985 return PDecl;
986}
987
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000988/// ObjcForwardProtocolDeclaration -
989/// Scope will always be top level file scope.
990Action::DeclTy *
991Sema::ObjcForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
992 IdentifierInfo **IdentList, unsigned NumElts) {
993 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
994 NumElts);
995
996 for (unsigned i = 0; i != NumElts; ++i) {
997 ObjcProtocolDecl *PDecl;
998 PDecl = Context.getObjCProtocolDecl(IdentList[i]);
999 if (!PDecl) {// Already seen?
1000 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1001 // Chain & install the protocol decl into the identifier.
1002 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1003 IdentList[i]->setFETokenInfo(PDecl);
1004 Context.setObjCProtocolDecl(IdentList[i], PDecl);
1005 }
1006 // Remember that this needs to be removed when the scope is popped.
1007 S->AddDecl(IdentList[i]);
1008
1009 FDecl->setForwardProtocolDecl((int)i, PDecl);
1010 }
1011 return FDecl;
1012}
1013
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001014Sema::DeclTy *Sema::ObjcStartCatInterface(Scope* S,
1015 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001016 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1017 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1018 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1019 ObjcCategoryDecl *CDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001020 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001021 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs, ClassName);
1022 if (IDecl) {
1023 assert (ClassName->getFETokenInfo<ScopedDecl>() && "Missing @interface decl");
1024 Decl *D = static_cast<Decl *>(ClassName->getFETokenInfo<ScopedDecl>());
1025 assert(isa<ObjcInterfaceDecl>(D) && "Missing @interface decl");
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001026
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001027 // Chain & install the category decl into the identifier.
1028 // Note that head of the chain is the @interface class type and follow up
1029 // nodes in the chain are the protocol decl nodes.
1030 cast<ObjcInterfaceDecl>(D)->setNext(CDecl);
1031 }
1032
1033 CDecl->setClassInterface(IDecl);
1034 /// Check that class of this category is already completely declared.
1035 if (!IDecl || IDecl->getIsForwardDecl())
1036 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1037 else {
1038 /// Check for duplicate interface declaration for this category
1039 ObjcCategoryDecl *CDeclChain;
1040 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1041 CDeclChain = CDeclChain->getNextClassCategory()) {
1042 if (CDeclChain->getCatName() == CategoryName) {
1043 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1044 CategoryName->getName());
1045 break;
1046 }
1047 }
1048 if (!CDeclChain) {
1049 CDecl->setCatName(CategoryName);
1050 CDecl->insertNextClassCategory();
1051 }
1052 }
1053
1054 /// Check then save referenced protocols
1055 for (unsigned int i = 0; i != NumProtoRefs; i++) {
1056 ObjcProtocolDecl* RefPDecl = Context.getObjCProtocolDecl(ProtoRefNames[i]);
1057 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
1058 Diag(CategoryLoc, diag::err_undef_protocolref,
1059 ProtoRefNames[i]->getName(),
1060 CategoryName->getName());
1061 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1062 }
1063
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001064 return CDecl;
1065}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001066
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001067Sema::DeclTy *Sema::ObjcStartClassImplementation(Scope *S,
1068 SourceLocation AtClassImplLoc,
1069 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1070 IdentifierInfo *SuperClassname,
1071 SourceLocation SuperClassLoc) {
1072 ObjcInterfaceDecl* IDecl = 0;
1073 // Check for another declaration kind with the same name.
1074 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1075 ClassLoc, S);
1076 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1077 Diag(ClassLoc, diag::err_redefinition_different_kind,
1078 ClassName->getName());
1079 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1080 }
1081 else {
1082 // Is there an interface declaration of this class; if not, warn!
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001083 IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001084 if (!IDecl)
1085 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1086 }
1087
1088 // Check that super class name is valid class name
1089 ObjcInterfaceDecl* SDecl = 0;
1090 if (SuperClassname) {
1091 // Check if a different kind of symbol declared in this scope.
1092 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1093 SuperClassLoc, S);
1094 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1095 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1096 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1097 SuperClassname->getName());
1098 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1099 }
1100 else {
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001101 SDecl = getObjCInterfaceDecl(S, SuperClassname, SuperClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001102 if (!SDecl)
1103 Diag(SuperClassLoc, diag::err_undef_superclass,
1104 SuperClassname->getName(), ClassName->getName());
1105 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1106 // This implementation and its interface do not have the same
1107 // super class.
1108 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1109 SuperClassname->getName());
1110 Diag(SDecl->getLocation(), diag::err_previous_definition);
1111 }
1112 }
1113 }
1114
1115 ObjcImplementationDecl* IMPDecl =
1116 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001117 if (!IDecl) {
1118 // Legacy case of @implementation with no corresponding @interface.
1119 // Build, chain & install the interface decl into the identifier.
1120 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName);
1121 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1122 ClassName->setFETokenInfo(IDecl);
1123
1124 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001125
1126 // Check that there is no duplicate implementation of this class.
1127 bool err = false;
1128 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1129 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1130 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1131 err = true;
1132 break;
1133 }
1134 }
1135 if (!err)
1136 Context.setObjcImplementationClass(IMPDecl);
1137
1138 return IMPDecl;
1139}
1140
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001141void Sema::ActOnImpleIvarVsClassIvars(DeclTy *ClassDecl,
1142 DeclTy **Fields, unsigned numIvars) {
1143 ObjcInterfaceDecl* IDecl =
1144 cast<ObjcInterfaceDecl>(static_cast<Decl*>(ClassDecl));
1145 assert(IDecl && "missing named interface class decl");
1146 ObjcIvarDecl** ivars = reinterpret_cast<ObjcIvarDecl**>(Fields);
1147 assert(ivars && "missing @implementation ivars");
1148
1149 // Check interface's Ivar list against those in the implementation.
1150 // names and types must match.
1151 //
1152 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1153 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1154 unsigned j = 0;
1155 bool err = false;
1156 while (numIvars > 0 && IntfNumIvars > 0) {
1157 ObjcIvarDecl* ImplIvar = ivars[j];
1158 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1159 assert (ImplIvar && "missing implementation ivar");
1160 assert (ClsIvar && "missing class ivar");
1161 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1162 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1163 ImplIvar->getIdentifier()->getName());
1164 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1165 ClsIvar->getIdentifier()->getName());
1166 }
1167 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1168 // as error.
1169 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1170 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1171 ImplIvar->getIdentifier()->getName());
1172 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1173 ClsIvar->getIdentifier()->getName());
1174 err = true;
1175 break;
1176 }
1177 --numIvars;
1178 --IntfNumIvars;
1179 }
1180 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1181 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1182 diag::err_inconsistant_ivar);
1183
1184}
1185
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001186/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1187/// Declared in protocol, and those referenced by it.
1188///
1189static void CheckProtocolMethodDefs(Sema* objSema, ObjcProtocolDecl *PDecl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001190 const llvm::DenseMap<void *, char>& InsMap,
1191 const llvm::DenseMap<void *, char>& ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001192 // check unimplemented instance methods.
1193 ObjcMethodDecl** methods = PDecl->getInsMethods();
1194 for (int j = 0; j < PDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001195 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001196 llvm::SmallString<128> buf;
1197 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001198 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001199 }
1200 // check unimplemented class methods
1201 methods = PDecl->getClsMethods();
1202 for (int j = 0; j < PDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001203 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001204 llvm::SmallString<128> buf;
1205 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001206 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001207 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001208
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001209 // Check on this protocols's referenced protocols, recursively
1210 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1211 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
1212 CheckProtocolMethodDefs(objSema, RefPDecl[i], InsMap, ClsMap);
1213}
1214
1215static void ImplMethodsVsClassMethods(Sema* objSema,
1216 ObjcImplementationDecl* IMPDecl,
1217 ObjcInterfaceDecl* IDecl) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001218 llvm::DenseMap<void *, char> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001219 // Check and see if instance methods in class interface have been
1220 // implemented in the implementation class.
1221 ObjcMethodDecl **methods = IMPDecl->getInsMethods();
1222 for (int i=0; i < IMPDecl->getNumInsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001223 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001224 }
1225
1226 methods = IDecl->getInsMethods();
1227 for (int j = 0; j < IDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001228 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001229 llvm::SmallString<128> buf;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001230 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001231 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001232 }
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001233 llvm::DenseMap<void *, char> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001234 // Check and see if class methods in class interface have been
1235 // implemented in the implementation class.
1236 methods = IMPDecl->getClsMethods();
1237 for (int i=0; i < IMPDecl->getNumClsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001238 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001239 }
1240
1241 methods = IDecl->getClsMethods();
1242 for (int j = 0; j < IDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001243 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001244 llvm::SmallString<128> buf;
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001245 objSema->Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001246 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001247 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001248
1249 // Check the protocol list for unimplemented methods in the @implementation
1250 // class.
1251 ObjcProtocolDecl** protocols = IDecl->getIntfRefProtocols();
1252 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1253 ObjcProtocolDecl* PDecl = protocols[i];
1254 CheckProtocolMethodDefs(objSema, PDecl, InsMap, ClsMap);
1255 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001256 return;
1257}
1258
Steve Naroff3536b442007-09-06 21:24:23 +00001259/// ObjcClassDeclaration -
1260/// Scope will always be top level file scope.
1261Action::DeclTy *
1262Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1263 IdentifierInfo **IdentList, unsigned NumElts) {
1264 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1265
1266 for (unsigned i = 0; i != NumElts; ++i) {
1267 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001268 IDecl = getObjCInterfaceDecl(S, IdentList[i], AtClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001269 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001270 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001271 // Chain & install the interface decl into the identifier.
1272 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1273 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001274 }
Steve Naroff3536b442007-09-06 21:24:23 +00001275 // Remember that this needs to be removed when the scope is popped.
1276 S->AddDecl(IdentList[i]);
1277
1278 CDecl->setInterfaceDecl((int)i, IDecl);
1279 }
1280 return CDecl;
1281}
1282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283
Steve Naroff08d92e42007-09-15 18:49:24 +00001284/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001285/// former case, Name will be non-null. In the later case, Name will be null.
1286/// TagType indicates what kind of tag this is. TK indicates whether this is a
1287/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001288Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 SourceLocation KWLoc, IdentifierInfo *Name,
1290 SourceLocation NameLoc, AttributeList *Attr) {
1291 // If this is a use of an existing tag, it must have a name.
1292 assert((Name != 0 || TK == TK_Definition) &&
1293 "Nameless record must be a definition!");
1294
1295 Decl::Kind Kind;
1296 switch (TagType) {
1297 default: assert(0 && "Unknown tag type!");
1298 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1299 case DeclSpec::TST_union: Kind = Decl::Union; break;
1300//case DeclSpec::TST_class: Kind = Decl::Class; break;
1301 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1302 }
1303
1304 // If this is a named struct, check to see if there was a previous forward
1305 // declaration or definition.
1306 if (TagDecl *PrevDecl =
1307 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1308 NameLoc, S))) {
1309
1310 // If this is a use of a previous tag, or if the tag is already declared in
1311 // the same scope (so that the definition/declaration completes or
1312 // rementions the tag), reuse the decl.
1313 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1314 // Make sure that this wasn't declared as an enum and now used as a struct
1315 // or something similar.
1316 if (PrevDecl->getKind() != Kind) {
1317 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1318 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1319 }
1320
1321 // If this is a use or a forward declaration, we're good.
1322 if (TK != TK_Definition)
1323 return PrevDecl;
1324
1325 // Diagnose attempts to redefine a tag.
1326 if (PrevDecl->isDefinition()) {
1327 Diag(NameLoc, diag::err_redefinition, Name->getName());
1328 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1329 // If this is a redefinition, recover by making this struct be
1330 // anonymous, which will make any later references get the previous
1331 // definition.
1332 Name = 0;
1333 } else {
1334 // Okay, this is definition of a previously declared or referenced tag.
1335 // Move the location of the decl to be the definition site.
1336 PrevDecl->setLocation(NameLoc);
1337 return PrevDecl;
1338 }
1339 }
1340 // If we get here, this is a definition of a new struct type in a nested
1341 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1342 // type.
1343 }
1344
1345 // If there is an identifier, use the location of the identifier as the
1346 // location of the decl, otherwise use the location of the struct/union
1347 // keyword.
1348 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1349
1350 // Otherwise, if this is the first time we've seen this tag, create the decl.
1351 TagDecl *New;
1352 switch (Kind) {
1353 default: assert(0 && "Unknown tag kind!");
1354 case Decl::Enum:
1355 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1356 // enum X { A, B, C } D; D should chain to X.
1357 New = new EnumDecl(Loc, Name, 0);
1358 // If this is an undefined enum, warn.
1359 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1360 break;
1361 case Decl::Union:
1362 case Decl::Struct:
1363 case Decl::Class:
1364 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1365 // struct X { int A; } D; D should chain to X.
1366 New = new RecordDecl(Kind, Loc, Name, 0);
1367 break;
1368 }
1369
1370 // If this has an identifier, add it to the scope stack.
1371 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001372 // The scope passed in may not be a decl scope. Zip up the scope tree until
1373 // we find one that is.
1374 while ((S->getFlags() & Scope::DeclScope) == 0)
1375 S = S->getParent();
1376
1377 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001378 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 Name->setFETokenInfo(New);
1380 S->AddDecl(New);
1381 }
1382
1383 return New;
1384}
1385
Steve Naroff08d92e42007-09-15 18:49:24 +00001386/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001387/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001388Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 SourceLocation DeclStart,
1390 Declarator &D, ExprTy *BitfieldWidth) {
1391 IdentifierInfo *II = D.getIdentifier();
1392 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001393 SourceLocation Loc = DeclStart;
1394 if (II) Loc = D.getIdentifierLoc();
1395
1396 // FIXME: Unnamed fields can be handled in various different ways, for
1397 // example, unnamed unions inject all members into the struct namespace!
1398
1399
1400 if (BitWidth) {
1401 // TODO: Validate.
1402 //printf("WARNING: BITFIELDS IGNORED!\n");
1403
1404 // 6.7.2.1p3
1405 // 6.7.2.1p4
1406
1407 } else {
1408 // Not a bitfield.
1409
1410 // validate II.
1411
1412 }
1413
1414 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001415 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1416 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001417
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1419 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001420 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1421 Diag(Loc, diag::err_typecheck_illegal_vla,
1422 VAT->getSizeExpr()->getSourceRange());
1423 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001424 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001426 FieldDecl *NewFD;
1427
1428 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001429 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001430 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1431 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001432 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001433 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001434 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001435
Steve Naroff5912a352007-08-28 20:14:24 +00001436 if (D.getInvalidType() || InvalidDecl)
1437 NewFD->setInvalidDecl();
1438 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001439}
1440
Steve Narofff13271f2007-09-14 23:09:53 +00001441static void ObjcSetIvarVisibility(ObjcIvarDecl *OIvar,
1442 tok::ObjCKeywordKind ivarVisibility) {
1443 assert(OIvar && "missing instance variable");
1444 switch (ivarVisibility) {
1445 case tok::objc_private:
1446 OIvar->setAccessControl(ObjcIvarDecl::Private);
1447 break;
1448 case tok::objc_public:
1449 OIvar->setAccessControl(ObjcIvarDecl::Public);
1450 break;
1451 case tok::objc_protected:
1452 OIvar->setAccessControl(ObjcIvarDecl::Protected);
1453 break;
1454 case tok::objc_package:
1455 OIvar->setAccessControl(ObjcIvarDecl::Package);
1456 break;
1457 default:
1458 OIvar->setAccessControl(ObjcIvarDecl::None);
1459 break;
1460 }
1461}
1462
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001463void Sema::ActOnFields(Scope* S,
1464 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001465 DeclTy **Fields, unsigned NumFields,
1466 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001467 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1468 assert(EnclosingDecl && "missing record or interface decl");
1469 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1470
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001471 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 // Diagnose code like:
1473 // struct S { struct S {} X; };
1474 // We discover this when we complete the outer S. Reject and ignore the
1475 // outer S.
1476 Diag(Record->getLocation(), diag::err_nested_redefinition,
1477 Record->getKindName());
1478 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001479 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 return;
1481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001482 // Verify that all the fields are okay.
1483 unsigned NumNamedMembers = 0;
1484 llvm::SmallVector<FieldDecl*, 32> RecFields;
1485 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001488
Steve Naroff74216642007-09-14 22:20:54 +00001489 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1490 assert(FD && "missing field decl");
1491
1492 // Remember all fields.
1493 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001494
1495 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001496 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001497
Steve Narofff13271f2007-09-14 23:09:53 +00001498 // If we have visibility info, make sure the AST is set accordingly.
1499 if (visibility)
1500 ObjcSetIvarVisibility(dyn_cast<ObjcIvarDecl>(FD), visibility[i]);
1501
Reid Spencer5f016e22007-07-11 17:01:13 +00001502 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001503 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001504 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001505 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001506 FD->setInvalidDecl();
1507 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 continue;
1509 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001510 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1511 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001512 if (!Record) { // Incomplete ivar type is always an error.
1513 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001514 FD->setInvalidDecl();
1515 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001516 continue;
1517 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 if (i != NumFields-1 || // ... that the last member ...
1519 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001520 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001521 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001522 FD->setInvalidDecl();
1523 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 continue;
1525 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001526 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1528 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001529 FD->setInvalidDecl();
1530 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001531 continue;
1532 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001534 if (Record)
1535 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1538 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001539 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001540 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1541 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001542 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 Record->setHasFlexibleArrayMember(true);
1544 } else {
1545 // If this is a struct/class and this is not the last element, reject
1546 // it. Note that GCC supports variable sized arrays in the middle of
1547 // structures.
1548 if (i != NumFields-1) {
1549 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1550 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001551 FD->setInvalidDecl();
1552 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001553 continue;
1554 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // We support flexible arrays at the end of structs in other structs
1556 // as an extension.
1557 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1558 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001559 if (Record)
1560 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001561 }
1562 }
1563 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001564 // Keep track of the number of named members.
1565 if (IdentifierInfo *II = FD->getIdentifier()) {
1566 // Detect duplicate member names.
1567 if (!FieldIDs.insert(II)) {
1568 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1569 // Find the previous decl.
1570 SourceLocation PrevLoc;
1571 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1572 assert(i != e && "Didn't find previous def!");
1573 if (RecFields[i]->getIdentifier() == II) {
1574 PrevLoc = RecFields[i]->getLocation();
1575 break;
1576 }
1577 }
1578 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001579 FD->setInvalidDecl();
1580 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 continue;
1582 }
1583 ++NumNamedMembers;
1584 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001585 }
1586
Reid Spencer5f016e22007-07-11 17:01:13 +00001587 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001588 if (Record)
1589 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001590 else {
1591 ObjcIvarDecl **ClsFields =
1592 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001593 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1594 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1595 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1596 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1597 ObjcImplementationDecl* IMPDecl =
1598 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1599 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1600 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001601 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1602 IMPDecl->getIdentifier(), RecLoc);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001603 if (IDecl)
1604 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1605 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1606 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001607 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001608}
1609
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001610void Sema::ObjcAddMethodsToClass(Scope* S, DeclTy *ClassDecl,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001611 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001612 // FIXME: Fix this when we can handle methods declared in protocols.
1613 // See Parser::ParseObjCAtProtocolDeclaration
1614 if (!ClassDecl)
1615 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001616 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1617 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1618
1619 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001620 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001621 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1622 if (!Method) continue; // Already issued a diagnostic.
1623 if (Method->isInstance())
1624 insMethods.push_back(Method);
1625 else
1626 clsMethods.push_back(Method);
1627 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001628 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1629 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1630 static_cast<Decl*>(ClassDecl));
1631 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1632 &clsMethods[0], clsMethods.size());
1633 }
1634 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1635 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1636 static_cast<Decl*>(ClassDecl));
1637 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1638 &clsMethods[0], clsMethods.size());
1639 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001640 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1641 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1642 static_cast<Decl*>(ClassDecl));
1643 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1644 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001645 }
1646 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1647 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1648 static_cast<Decl*>(ClassDecl));
1649 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1650 &clsMethods[0], clsMethods.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001651 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1652 ImplClass->getIdentifier(), SourceLocation());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001653 if (IDecl)
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001654 ImplMethodsVsClassMethods(this, ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001655 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001656 else
1657 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001658 return;
1659}
1660
Fariborz Jahanian00933592007-09-18 00:25:23 +00001661Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001662 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001663 // optional arguments. The number of types/arguments is obtained
1664 // from the Sel.getNumArgs().
1665 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1666 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001667 llvm::SmallVector<ParmVarDecl*, 16> Params;
1668
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001669 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001670 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001671 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1672 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001673 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001674 Params.push_back(Param);
1675 }
1676 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001677 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1678 resultDeclType, 0, -1, AttrList,
1679 MethodType == tok::minus);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001680 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian00933592007-09-18 00:25:23 +00001681 if (MethodDeclKind == tok::objc_optional)
Steve Naroff563477d2007-09-18 23:55:05 +00001682 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Optional);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001683 else
Steve Naroff563477d2007-09-18 23:55:05 +00001684 ObjcMethod->setDeclImplementation(ObjcMethodDecl::Required);
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001685 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001686}
1687
Steve Naroff08d92e42007-09-15 18:49:24 +00001688Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 DeclTy *lastEnumConst,
1690 SourceLocation IdLoc, IdentifierInfo *Id,
1691 SourceLocation EqualLoc, ExprTy *val) {
1692 theEnumDecl = theEnumDecl; // silence unused warning.
1693 EnumConstantDecl *LastEnumConst =
1694 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1695 Expr *Val = static_cast<Expr*>(val);
1696
Chris Lattner31e05722007-08-26 06:24:45 +00001697 // The scope passed in may not be a decl scope. Zip up the scope tree until
1698 // we find one that is.
1699 while ((S->getFlags() & Scope::DeclScope) == 0)
1700 S = S->getParent();
1701
Reid Spencer5f016e22007-07-11 17:01:13 +00001702 // Verify that there isn't already something declared with this name in this
1703 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001704 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1705 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 if (S->isDeclScope(PrevDecl)) {
1707 if (isa<EnumConstantDecl>(PrevDecl))
1708 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1709 else
1710 Diag(IdLoc, diag::err_redefinition, Id->getName());
1711 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1712 // FIXME: Don't leak memory: delete Val;
1713 return 0;
1714 }
1715 }
1716
1717 llvm::APSInt EnumVal(32);
1718 QualType EltTy;
1719 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001720 // Make sure to promote the operand type to int.
1721 UsualUnaryConversions(Val);
1722
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1724 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001725 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1727 Id->getName());
1728 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001729 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001730 } else {
1731 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001733 }
1734
1735 if (!Val) {
1736 if (LastEnumConst) {
1737 // Assign the last value + 1.
1738 EnumVal = LastEnumConst->getInitVal();
1739 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001740
1741 // Check for overflow on increment.
1742 if (EnumVal < LastEnumConst->getInitVal())
1743 Diag(IdLoc, diag::warn_enum_value_overflow);
1744
Chris Lattnerb7416f92007-08-27 17:37:24 +00001745 EltTy = LastEnumConst->getType();
1746 } else {
1747 // First value, set to zero.
1748 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001749 EnumVal.zextOrTrunc(
1750 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001751 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 }
1753
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1755 LastEnumConst);
1756
1757 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001758 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 Id->setFETokenInfo(New);
1760 S->AddDecl(New);
1761 return New;
1762}
1763
Steve Naroff08d92e42007-09-15 18:49:24 +00001764void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 DeclTy **Elements, unsigned NumElements) {
1766 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1767 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1768
Chris Lattnere37f0be2007-08-28 05:10:31 +00001769 // TODO: If the result value doesn't fit in an int, it must be a long or long
1770 // long value. ISO C does not support this, but GCC does as an extension,
1771 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001772 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001773
1774
Chris Lattnerac609682007-08-28 06:15:15 +00001775 // Verify that all the values are okay, compute the size of the values, and
1776 // reverse the list.
1777 unsigned NumNegativeBits = 0;
1778 unsigned NumPositiveBits = 0;
1779
1780 // Keep track of whether all elements have type int.
1781 bool AllElementsInt = true;
1782
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 EnumConstantDecl *EltList = 0;
1784 for (unsigned i = 0; i != NumElements; ++i) {
1785 EnumConstantDecl *ECD =
1786 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1787 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001788
1789 // If the enum value doesn't fit in an int, emit an extension warning.
1790 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1791 "Should have promoted value to int");
1792 const llvm::APSInt &InitVal = ECD->getInitVal();
1793 if (InitVal.getBitWidth() > IntWidth) {
1794 llvm::APSInt V(InitVal);
1795 V.trunc(IntWidth);
1796 V.extend(InitVal.getBitWidth());
1797 if (V != InitVal)
1798 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1799 InitVal.toString());
1800 }
Chris Lattnerac609682007-08-28 06:15:15 +00001801
1802 // Keep track of the size of positive and negative values.
1803 if (InitVal.isUnsigned() || !InitVal.isNegative())
1804 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1805 else
1806 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001807
Chris Lattnerac609682007-08-28 06:15:15 +00001808 // Keep track of whether every enum element has type int (very commmon).
1809 if (AllElementsInt)
1810 AllElementsInt = ECD->getType() == Context.IntTy;
1811
Reid Spencer5f016e22007-07-11 17:01:13 +00001812 ECD->setNextDeclarator(EltList);
1813 EltList = ECD;
1814 }
1815
Chris Lattnerac609682007-08-28 06:15:15 +00001816 // Figure out the type that should be used for this enum.
1817 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1818 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001819 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001820
1821 if (NumNegativeBits) {
1822 // If there is a negative value, figure out the smallest integer type (of
1823 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001824 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001825 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001826 BestWidth = IntWidth;
1827 } else {
1828 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1829 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001830 BestType = Context.LongTy;
1831 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001832 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1833 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001834 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1835 BestType = Context.LongLongTy;
1836 }
1837 }
1838 } else {
1839 // If there is no negative value, figure out which of uint, ulong, ulonglong
1840 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001841 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001842 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001843 BestWidth = IntWidth;
1844 } else if (NumPositiveBits <=
1845 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001846 BestType = Context.UnsignedLongTy;
1847 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001848 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1849 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001850 "How could an initializer get larger than ULL?");
1851 BestType = Context.UnsignedLongLongTy;
1852 }
1853 }
1854
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001855 // Loop over all of the enumerator constants, changing their types to match
1856 // the type of the enum if needed.
1857 for (unsigned i = 0; i != NumElements; ++i) {
1858 EnumConstantDecl *ECD =
1859 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1860 if (!ECD) continue; // Already issued a diagnostic.
1861
1862 // Standard C says the enumerators have int type, but we allow, as an
1863 // extension, the enumerators to be larger than int size. If each
1864 // enumerator value fits in an int, type it as an int, otherwise type it the
1865 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1866 // that X has type 'int', not 'unsigned'.
1867 if (ECD->getType() == Context.IntTy)
1868 continue; // Already int type.
1869
1870 // Determine whether the value fits into an int.
1871 llvm::APSInt InitVal = ECD->getInitVal();
1872 bool FitsInInt;
1873 if (InitVal.isUnsigned() || !InitVal.isNegative())
1874 FitsInInt = InitVal.getActiveBits() < IntWidth;
1875 else
1876 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1877
1878 // If it fits into an integer type, force it. Otherwise force it to match
1879 // the enum decl type.
1880 QualType NewTy;
1881 unsigned NewWidth;
1882 bool NewSign;
1883 if (FitsInInt) {
1884 NewTy = Context.IntTy;
1885 NewWidth = IntWidth;
1886 NewSign = true;
1887 } else if (ECD->getType() == BestType) {
1888 // Already the right type!
1889 continue;
1890 } else {
1891 NewTy = BestType;
1892 NewWidth = BestWidth;
1893 NewSign = BestType->isSignedIntegerType();
1894 }
1895
1896 // Adjust the APSInt value.
1897 InitVal.extOrTrunc(NewWidth);
1898 InitVal.setIsSigned(NewSign);
1899 ECD->setInitVal(InitVal);
1900
1901 // Adjust the Expr initializer and type.
1902 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1903 ECD->setType(NewTy);
1904 }
Chris Lattnerac609682007-08-28 06:15:15 +00001905
Chris Lattnere00b18c2007-08-28 18:24:31 +00001906 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001907}
1908
1909void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1910 if (!current) return;
1911
1912 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1913 // remember this in the LastInGroupList list.
1914 if (last)
1915 LastInGroupList.push_back((Decl*)last);
1916}
1917
1918void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1919 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1920 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1921 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1922 if (!newType.isNull()) // install the new vector type into the decl
1923 vDecl->setType(newType);
1924 }
1925 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1926 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1927 rawAttr);
1928 if (!newType.isNull()) // install the new vector type into the decl
1929 tDecl->setUnderlyingType(newType);
1930 }
1931 }
Steve Naroff73322922007-07-18 18:00:27 +00001932 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001933 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1934 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1935 else
Steve Naroff73322922007-07-18 18:00:27 +00001936 Diag(rawAttr->getAttributeLoc(),
1937 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001938 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001939 // FIXME: add other attributes...
1940}
1941
1942void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1943 AttributeList *declarator_postfix) {
1944 while (declspec_prefix) {
1945 HandleDeclAttribute(New, declspec_prefix);
1946 declspec_prefix = declspec_prefix->getNext();
1947 }
1948 while (declarator_postfix) {
1949 HandleDeclAttribute(New, declarator_postfix);
1950 declarator_postfix = declarator_postfix->getNext();
1951 }
1952}
1953
Steve Naroffbea0b342007-07-29 16:33:31 +00001954void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1955 AttributeList *rawAttr) {
1956 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001957 // check the attribute arugments.
1958 if (rawAttr->getNumArgs() != 1) {
1959 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1960 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001961 return;
Steve Naroff73322922007-07-18 18:00:27 +00001962 }
1963 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1964 llvm::APSInt vecSize(32);
1965 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1966 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1967 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001968 return;
Steve Naroff73322922007-07-18 18:00:27 +00001969 }
1970 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1971 // in conjunction with complex types (pointers, arrays, functions, etc.).
1972 Type *canonType = curType.getCanonicalType().getTypePtr();
1973 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1974 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1975 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001976 return;
Steve Naroff73322922007-07-18 18:00:27 +00001977 }
1978 // unlike gcc's vector_size attribute, the size is specified as the
1979 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001980 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001981
1982 if (vectorSize == 0) {
1983 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1984 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001985 return;
Steve Naroff73322922007-07-18 18:00:27 +00001986 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001987 // Instantiate/Install the vector type, the number of elements is > 0.
1988 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1989 // Remember this typedef decl, we will need it later for diagnostics.
1990 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001991}
1992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001994 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 // check the attribute arugments.
1996 if (rawAttr->getNumArgs() != 1) {
1997 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1998 std::string("1"));
1999 return QualType();
2000 }
2001 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
2002 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00002003 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002004 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
2005 sizeExpr->getSourceRange());
2006 return QualType();
2007 }
2008 // navigate to the base type - we need to provide for vector pointers,
2009 // vector arrays, and functions returning vectors.
2010 Type *canonType = curType.getCanonicalType().getTypePtr();
2011
Steve Naroff73322922007-07-18 18:00:27 +00002012 if (canonType->isPointerType() || canonType->isArrayType() ||
2013 canonType->isFunctionType()) {
2014 assert(1 && "HandleVector(): Complex type construction unimplemented");
2015 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2016 do {
2017 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2018 canonType = PT->getPointeeType().getTypePtr();
2019 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2020 canonType = AT->getElementType().getTypePtr();
2021 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2022 canonType = FT->getResultType().getTypePtr();
2023 } while (canonType->isPointerType() || canonType->isArrayType() ||
2024 canonType->isFunctionType());
2025 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 }
2027 // the base type must be integer or float.
2028 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2029 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2030 curType.getCanonicalType().getAsString());
2031 return QualType();
2032 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002033 unsigned typeSize = static_cast<unsigned>(
2034 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002036 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002037
2038 // the vector size needs to be an integral multiple of the type size.
2039 if (vectorSize % typeSize) {
2040 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2041 sizeExpr->getSourceRange());
2042 return QualType();
2043 }
2044 if (vectorSize == 0) {
2045 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2046 sizeExpr->getSourceRange());
2047 return QualType();
2048 }
2049 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2050 // the number of elements to be a power of two (unlike GCC).
2051 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002052 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002053}
2054