blob: 7cf76f59750693f527d57b7f69875e30ce66c9bd [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 {
Chris Lattner5c0fa302007-09-30 08:31:00 +000030 if (Decl *IIDecl = II.getFETokenInfo<Decl>())
31 if (isa<TypedefDecl>(IIDecl) || isa<ObjcInterfaceDecl>(IIDecl))
32 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000033 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000034}
35
36void Sema::PopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +000037 if (S->decl_empty()) return;
38 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
41 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +000042 Decl *TmpD = static_cast<Decl*>(*I);
43 assert(TmpD && "This decl didn't get pushed??");
44 ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
45 assert(D && "This decl isn't a ScopedDecl?");
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047 IdentifierInfo *II = D->getIdentifier();
48 if (!II) continue;
49
50 // Unlink this decl from the identifier. Because the scope contains decls
51 // in an unordered collection, and because we have multiple identifier
52 // namespaces (e.g. tag, normal, label),the decl may not be the first entry.
53 if (II->getFETokenInfo<Decl>() == D) {
54 // Normal case, no multiple decls in different namespaces.
55 II->setFETokenInfo(D->getNext());
56 } else {
57 // Scan ahead. There are only three namespaces in C, so this loop can
58 // never execute more than 3 times.
Steve Naroffc752d042007-09-13 18:10:37 +000059 ScopedDecl *SomeDecl = II->getFETokenInfo<ScopedDecl>();
Reid Spencer5f016e22007-07-11 17:01:13 +000060 while (SomeDecl->getNext() != D) {
61 SomeDecl = SomeDecl->getNext();
62 assert(SomeDecl && "Didn't find this decl on its identifier's chain!");
63 }
64 SomeDecl->setNext(D->getNext());
65 }
66
67 // This will have to be revisited for C++: there we want to nest stuff in
68 // namespace decls etc. Even for C, we might want a top-level translation
69 // unit decl or something.
70 if (!CurFunctionDecl)
71 continue;
72
73 // Chain this decl to the containing function, it now owns the memory for
74 // the decl.
75 D->setNext(CurFunctionDecl->getDeclChain());
76 CurFunctionDecl->setDeclChain(D);
77 }
78}
79
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000080/// getObjcInterfaceDecl - Look up a for a class declaration in the scope.
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +000081/// return 0 if one not found.
82ObjcInterfaceDecl *Sema::getObjCInterfaceDecl(Scope *S,
83 IdentifierInfo *Id,
84 SourceLocation IdLoc) {
85 ScopedDecl *IdDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
86 IdLoc, S);
87 if (IdDecl && !isa<ObjcInterfaceDecl>(IdDecl))
88 IdDecl = 0;
89 return cast_or_null<ObjcInterfaceDecl>(static_cast<Decl*>(IdDecl));
90}
91
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +000092/// getObjcProtocolDecl - Look up a for a protocol declaration in the scope.
93/// return 0 if one not found.
94ObjcProtocolDecl *Sema::getObjCProtocolDecl(Scope *S,
95 IdentifierInfo *Id,
96 SourceLocation IdLoc) {
97 // Note that Protocols have their own namespace.
98 ScopedDecl *PrDecl = LookupScopedDecl(Id, Decl::IDNS_Protocol,
99 IdLoc, S);
100 if (PrDecl && !isa<ObjcProtocolDecl>(PrDecl))
101 PrDecl = 0;
102 return cast_or_null<ObjcProtocolDecl>(static_cast<Decl*>(PrDecl));
103}
104
Reid Spencer5f016e22007-07-11 17:01:13 +0000105/// LookupScopedDecl - Look up the inner-most declaration in the specified
106/// namespace.
Steve Naroffc752d042007-09-13 18:10:37 +0000107ScopedDecl *Sema::LookupScopedDecl(IdentifierInfo *II, unsigned NSI,
108 SourceLocation IdLoc, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 if (II == 0) return 0;
110 Decl::IdentifierNamespace NS = (Decl::IdentifierNamespace)NSI;
111
112 // Scan up the scope chain looking for a decl that matches this identifier
113 // that is in the appropriate namespace. This search should not take long, as
114 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Steve Naroffc752d042007-09-13 18:10:37 +0000115 for (ScopedDecl *D = II->getFETokenInfo<ScopedDecl>(); D; D = D->getNext())
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 if (D->getIdentifierNamespace() == NS)
117 return D;
118
119 // If we didn't find a use of this identifier, and if the identifier
120 // corresponds to a compiler builtin, create the decl object for the builtin
121 // now, injecting it into translation unit scope, and return it.
122 if (NS == Decl::IDNS_Ordinary) {
123 // If this is a builtin on some other target, or if this builtin varies
124 // across targets (e.g. in type), emit a diagnostic and mark the translation
125 // unit non-portable for using it.
126 if (II->isNonPortableBuiltin()) {
127 // Only emit this diagnostic once for this builtin.
128 II->setNonPortableBuiltin(false);
129 Context.Target.DiagnoseNonPortability(IdLoc,
130 diag::port_target_builtin_use);
131 }
132 // If this is a builtin on this (or all) targets, create the decl.
133 if (unsigned BuiltinID = II->getBuiltinID())
134 return LazilyCreateBuiltin(II, BuiltinID, S);
135 }
136 return 0;
137}
138
139/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
140/// lazily create a decl for it.
Steve Naroffc752d042007-09-13 18:10:37 +0000141ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 Builtin::ID BID = (Builtin::ID)bid;
143
144 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
145 FunctionDecl *New = new FunctionDecl(SourceLocation(), II, R,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000146 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000147
148 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000149 if (Scope *FnS = S->getFnParent())
150 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 while (S->getParent())
152 S = S->getParent();
153 S->AddDecl(New);
154
155 // Add this decl to the end of the identifier info.
Steve Naroffc752d042007-09-13 18:10:37 +0000156 if (ScopedDecl *LastDecl = II->getFETokenInfo<ScopedDecl>()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // Scan until we find the last (outermost) decl in the id chain.
158 while (LastDecl->getNext())
159 LastDecl = LastDecl->getNext();
160 // Insert before (outside) it.
161 LastDecl->setNext(New);
162 } else {
163 II->setFETokenInfo(New);
164 }
165 // Make sure clients iterating over decls see this.
166 LastInGroupList.push_back(New);
167
168 return New;
169}
170
171/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
172/// and scope as a previous declaration 'Old'. Figure out how to resolve this
173/// situation, merging decls or emitting diagnostics as appropriate.
174///
Steve Naroff8e74c932007-09-13 21:41:19 +0000175TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 // Verify the old decl was also a typedef.
177 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
178 if (!Old) {
179 Diag(New->getLocation(), diag::err_redefinition_different_kind,
180 New->getName());
181 Diag(OldD->getLocation(), diag::err_previous_definition);
182 return New;
183 }
184
185 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
186 // TODO: This is totally simplistic. It should handle merging functions
187 // together etc, merging extern int X; int X; ...
188 Diag(New->getLocation(), diag::err_redefinition, New->getName());
189 Diag(Old->getLocation(), diag::err_previous_definition);
190 return New;
191}
192
193/// MergeFunctionDecl - We just parsed a function 'New' which has the same name
194/// and scope as a previous declaration 'Old'. Figure out how to resolve this
195/// situation, merging decls or emitting diagnostics as appropriate.
196///
Steve Naroff8e74c932007-09-13 21:41:19 +0000197FunctionDecl *Sema::MergeFunctionDecl(FunctionDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 // Verify the old decl was also a function.
199 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
200 if (!Old) {
201 Diag(New->getLocation(), diag::err_redefinition_different_kind,
202 New->getName());
203 Diag(OldD->getLocation(), diag::err_previous_definition);
204 return New;
205 }
206
207 // This is not right, but it's a start. If 'Old' is a function prototype with
208 // the same type as 'New', silently allow this. FIXME: We should link up decl
209 // objects here.
210 if (Old->getBody() == 0 &&
211 Old->getCanonicalType() == New->getCanonicalType()) {
212 return New;
213 }
214
215 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
216 // TODO: This is totally simplistic. It should handle merging functions
217 // together etc, merging extern int X; int X; ...
218 Diag(New->getLocation(), diag::err_redefinition, New->getName());
219 Diag(Old->getLocation(), diag::err_previous_definition);
220 return New;
221}
222
223/// MergeVarDecl - We just parsed a variable 'New' which has the same name
224/// and scope as a previous declaration 'Old'. Figure out how to resolve this
225/// situation, merging decls or emitting diagnostics as appropriate.
226///
227/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
228/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
229///
Steve Naroff8e74c932007-09-13 21:41:19 +0000230VarDecl *Sema::MergeVarDecl(VarDecl *New, ScopedDecl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 // Verify the old decl was also a variable.
232 VarDecl *Old = dyn_cast<VarDecl>(OldD);
233 if (!Old) {
234 Diag(New->getLocation(), diag::err_redefinition_different_kind,
235 New->getName());
236 Diag(OldD->getLocation(), diag::err_previous_definition);
237 return New;
238 }
Steve Narofffb22d962007-08-30 01:06:46 +0000239 FileVarDecl *OldFSDecl = dyn_cast<FileVarDecl>(Old);
240 FileVarDecl *NewFSDecl = dyn_cast<FileVarDecl>(New);
241 bool OldIsTentative = false;
242
243 if (OldFSDecl && NewFSDecl) { // C99 6.9.2
244 // Handle C "tentative" external object definitions. FIXME: finish!
245 if (!OldFSDecl->getInit() &&
246 (OldFSDecl->getStorageClass() == VarDecl::None ||
247 OldFSDecl->getStorageClass() == VarDecl::Static))
248 OldIsTentative = true;
249 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 // Verify the types match.
251 if (Old->getCanonicalType() != New->getCanonicalType()) {
252 Diag(New->getLocation(), diag::err_redefinition, New->getName());
253 Diag(Old->getLocation(), diag::err_previous_definition);
254 return New;
255 }
256 // We've verified the types match, now check if Old is "extern".
257 if (Old->getStorageClass() != VarDecl::Extern) {
258 Diag(New->getLocation(), diag::err_redefinition, New->getName());
259 Diag(Old->getLocation(), diag::err_previous_definition);
260 }
261 return New;
262}
263
264/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
265/// no declarator (e.g. "struct foo;") is parsed.
266Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
267 // TODO: emit error on 'int;' or 'const enum foo;'.
268 // TODO: emit error on 'typedef int;'
269 // if (!DS.isMissingDeclaratorOk()) Diag(...);
270
271 return 0;
272}
273
Steve Naroff9e8925e2007-09-04 14:36:54 +0000274bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000275 AssignmentCheckResult result;
276 SourceLocation loc = Init->getLocStart();
277 // Get the type before calling CheckSingleAssignmentConstraints(), since
278 // it can promote the expression.
279 QualType rhsType = Init->getType();
280
281 result = CheckSingleAssignmentConstraints(DeclType, Init);
282
283 // decode the result (notice that extensions still return a type).
284 switch (result) {
285 case Compatible:
286 break;
287 case Incompatible:
Steve Naroff6f9f3072007-09-02 15:34:30 +0000288 // FIXME: tighten up this check which should allow:
289 // char s[] = "abc", which is identical to char s[] = { 'a', 'b', 'c' };
290 if (rhsType == Context.getPointerType(Context.CharTy))
291 break;
Steve Narofff0090632007-09-02 02:04:30 +0000292 Diag(loc, diag::err_typecheck_assign_incompatible,
293 DeclType.getAsString(), rhsType.getAsString(),
294 Init->getSourceRange());
295 return true;
296 case PointerFromInt:
297 // check for null pointer constant (C99 6.3.2.3p3)
298 if (!Init->isNullPointerConstant(Context)) {
299 Diag(loc, diag::ext_typecheck_assign_pointer_int,
300 DeclType.getAsString(), rhsType.getAsString(),
301 Init->getSourceRange());
302 return true;
303 }
304 break;
305 case IntFromPointer:
306 Diag(loc, diag::ext_typecheck_assign_pointer_int,
307 DeclType.getAsString(), rhsType.getAsString(),
308 Init->getSourceRange());
309 break;
310 case IncompatiblePointer:
311 Diag(loc, diag::ext_typecheck_assign_incompatible_pointer,
312 DeclType.getAsString(), rhsType.getAsString(),
313 Init->getSourceRange());
314 break;
315 case CompatiblePointerDiscardsQualifiers:
316 Diag(loc, diag::ext_typecheck_assign_discards_qualifiers,
317 DeclType.getAsString(), rhsType.getAsString(),
318 Init->getSourceRange());
319 break;
320 }
321 return false;
322}
323
Steve Naroff9e8925e2007-09-04 14:36:54 +0000324bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
325 bool isStatic, QualType ElementType) {
Steve Naroff371227d2007-09-04 02:20:04 +0000326 SourceLocation loc;
Steve Naroff9e8925e2007-09-04 14:36:54 +0000327 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Steve Naroff371227d2007-09-04 02:20:04 +0000328
329 if (isStatic && !expr->isConstantExpr(Context, &loc)) { // C99 6.7.8p4.
330 Diag(loc, diag::err_init_element_not_constant, expr->getSourceRange());
331 return true;
332 } else if (CheckSingleInitializer(expr, ElementType)) {
333 return true; // types weren't compatible.
334 }
Steve Naroff9e8925e2007-09-04 14:36:54 +0000335 if (savExpr != expr) // The type was promoted, update initializer list.
336 IList->setInit(slot, expr);
Steve Naroff371227d2007-09-04 02:20:04 +0000337 return false;
338}
339
340void Sema::CheckVariableInitList(QualType DeclType, InitListExpr *IList,
341 QualType ElementType, bool isStatic,
342 int &nInitializers, bool &hadError) {
Steve Naroff6f9f3072007-09-02 15:34:30 +0000343 for (unsigned i = 0; i < IList->getNumInits(); i++) {
344 Expr *expr = IList->getInit(i);
345
Steve Naroff371227d2007-09-04 02:20:04 +0000346 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
347 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000348 int maxElements = CAT->getMaximumElements();
Steve Naroff371227d2007-09-04 02:20:04 +0000349 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
350 maxElements, hadError);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000351 }
Steve Naroff371227d2007-09-04 02:20:04 +0000352 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000353 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff6f9f3072007-09-02 15:34:30 +0000354 }
Steve Naroff371227d2007-09-04 02:20:04 +0000355 nInitializers++;
356 }
357 return;
358}
359
360// FIXME: Doesn't deal with arrays of structures yet.
361void Sema::CheckConstantInitList(QualType DeclType, InitListExpr *IList,
362 QualType ElementType, bool isStatic,
363 int &totalInits, bool &hadError) {
364 int maxElementsAtThisLevel = 0;
365 int nInitsAtLevel = 0;
366
367 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
368 // We have a constant array type, compute maxElements *at this level*.
Steve Naroff7cf8c442007-09-04 21:13:33 +0000369 maxElementsAtThisLevel = CAT->getMaximumElements();
370 // Set DeclType, used below to recurse (for multi-dimensional arrays).
371 DeclType = CAT->getElementType();
Steve Naroff371227d2007-09-04 02:20:04 +0000372 } else if (DeclType->isScalarType()) {
373 Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
374 IList->getSourceRange());
375 maxElementsAtThisLevel = 1;
376 }
377 // The empty init list "{ }" is treated specially below.
378 unsigned numInits = IList->getNumInits();
379 if (numInits) {
380 for (unsigned i = 0; i < numInits; i++) {
381 Expr *expr = IList->getInit(i);
382
383 if (InitListExpr *InitList = dyn_cast<InitListExpr>(expr)) {
384 CheckConstantInitList(DeclType, InitList, ElementType, isStatic,
385 totalInits, hadError);
386 } else {
Steve Naroff9e8925e2007-09-04 14:36:54 +0000387 hadError = CheckInitExpr(expr, IList, i, isStatic, ElementType);
Steve Naroff371227d2007-09-04 02:20:04 +0000388 nInitsAtLevel++; // increment the number of initializers at this level.
389 totalInits--; // decrement the total number of initializers.
390
391 // Check if we have space for another initializer.
392 if ((nInitsAtLevel > maxElementsAtThisLevel) || (totalInits < 0))
393 Diag(expr->getLocStart(), diag::warn_excess_initializers,
394 expr->getSourceRange());
395 }
396 }
397 if (nInitsAtLevel < maxElementsAtThisLevel) // fill the remaining elements.
398 totalInits -= (maxElementsAtThisLevel - nInitsAtLevel);
399 } else {
400 // we have an initializer list with no elements.
401 totalInits -= maxElementsAtThisLevel;
402 if (totalInits < 0)
403 Diag(IList->getLocStart(), diag::warn_excess_initializers,
404 IList->getSourceRange());
Steve Naroff6f9f3072007-09-02 15:34:30 +0000405 }
Steve Naroffd35005e2007-09-03 01:24:23 +0000406 return;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000407}
408
Steve Naroff9e8925e2007-09-04 14:36:54 +0000409bool Sema::CheckInitializer(Expr *&Init, QualType &DeclType, bool isStatic) {
Steve Narofff0090632007-09-02 02:04:30 +0000410 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Steve Naroffd35005e2007-09-03 01:24:23 +0000411 if (!InitList)
412 return CheckSingleInitializer(Init, DeclType);
413
Steve Narofff0090632007-09-02 02:04:30 +0000414 // We have an InitListExpr, make sure we set the type.
415 Init->setType(DeclType);
Steve Naroffd35005e2007-09-03 01:24:23 +0000416
417 bool hadError = false;
Steve Naroff6f9f3072007-09-02 15:34:30 +0000418
Steve Naroff38374b02007-09-02 20:30:18 +0000419 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
420 // of unknown size ("[]") or an object type that is not a variable array type.
421 if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType()) {
422 Expr *expr = VAT->getSizeExpr();
Steve Naroffd35005e2007-09-03 01:24:23 +0000423 if (expr)
424 return Diag(expr->getLocStart(), diag::err_variable_object_no_init,
425 expr->getSourceRange());
426
Steve Naroff7cf8c442007-09-04 21:13:33 +0000427 // We have a VariableArrayType with unknown size. Note that only the first
428 // array can have unknown size. For example, "int [][]" is illegal.
Steve Naroff371227d2007-09-04 02:20:04 +0000429 int numInits = 0;
Steve Naroff7cf8c442007-09-04 21:13:33 +0000430 CheckVariableInitList(VAT->getElementType(), InitList, VAT->getBaseType(),
431 isStatic, numInits, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000432 if (!hadError) {
433 // Return a new array type from the number of initializers (C99 6.7.8p22).
434 llvm::APSInt ConstVal(32);
Steve Naroff371227d2007-09-04 02:20:04 +0000435 ConstVal = numInits;
436 DeclType = Context.getConstantArrayType(DeclType, ConstVal,
Steve Naroffd35005e2007-09-03 01:24:23 +0000437 ArrayType::Normal, 0);
438 }
439 return hadError;
440 }
441 if (const ConstantArrayType *CAT = DeclType->getAsConstantArrayType()) {
Steve Naroff7cf8c442007-09-04 21:13:33 +0000442 int maxElements = CAT->getMaximumElements();
443 CheckConstantInitList(DeclType, InitList, CAT->getBaseType(),
444 isStatic, maxElements, hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000445 return hadError;
446 }
Steve Naroff371227d2007-09-04 02:20:04 +0000447 if (DeclType->isScalarType()) { // C99 6.7.8p11: Allow "int x = { 1, 2 };"
448 int maxElements = 1;
449 CheckConstantInitList(DeclType, InitList, DeclType, isStatic, maxElements,
450 hadError);
Steve Naroffd35005e2007-09-03 01:24:23 +0000451 return hadError;
Steve Naroff38374b02007-09-02 20:30:18 +0000452 }
453 // FIXME: Handle struct/union types.
Steve Naroffd35005e2007-09-03 01:24:23 +0000454 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +0000455}
456
Reid Spencer5f016e22007-07-11 17:01:13 +0000457Sema::DeclTy *
Steve Naroff08d92e42007-09-15 18:49:24 +0000458Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000459 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000460 IdentifierInfo *II = D.getIdentifier();
461
Chris Lattnere80a59c2007-07-25 00:24:17 +0000462 // All of these full declarators require an identifier. If it doesn't have
463 // one, the ParsedFreeStandingDeclSpec action should be used.
464 if (II == 0) {
Chris Lattner98e08632007-08-28 06:17:15 +0000465 Diag(D.getDeclSpec().getSourceRange().Begin(),
466 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000467 D.getDeclSpec().getSourceRange(), D.getSourceRange());
468 return 0;
469 }
470
Chris Lattner31e05722007-08-26 06:24:45 +0000471 // The scope passed in may not be a decl scope. Zip up the scope tree until
472 // we find one that is.
473 while ((S->getFlags() & Scope::DeclScope) == 0)
474 S = S->getParent();
475
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 // See if this is a redefinition of a variable in the same scope.
Steve Naroffc752d042007-09-13 18:10:37 +0000477 ScopedDecl *PrevDecl = LookupScopedDecl(II, Decl::IDNS_Ordinary,
478 D.getIdentifierLoc(), S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 if (PrevDecl && !S->isDeclScope(PrevDecl))
480 PrevDecl = 0; // If in outer scope, it isn't the same thing.
481
Steve Naroffc752d042007-09-13 18:10:37 +0000482 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000483 bool InvalidDecl = false;
484
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
486 TypedefDecl *NewTD = ParseTypedefDecl(S, D, LastDeclarator);
487 if (!NewTD) return 0;
488
489 // Handle attributes prior to checking for duplicates in MergeVarDecl
490 HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
491 D.getAttributes());
492 // Merge the decl with the existing one if appropriate.
493 if (PrevDecl) {
494 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
495 if (NewTD == 0) return 0;
496 }
497 New = NewTD;
498 if (S->getParent() == 0) {
499 // C99 6.7.7p2: If a typedef name specifies a variably modified type
500 // then it shall have block scope.
Steve Naroffd7444aa2007-08-31 17:20:07 +0000501 if (const VariableArrayType *VAT =
502 NewTD->getUnderlyingType()->getAsVariablyModifiedType()) {
503 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla,
504 VAT->getSizeExpr()->getSourceRange());
505 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 }
507 }
508 } else if (D.isFunctionDeclarator()) {
509 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000510 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Steve Naroff49b45262007-07-13 16:58:59 +0000511
Chris Lattner271f1a62007-09-27 15:15:46 +0000512 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 switch (D.getDeclSpec().getStorageClassSpec()) {
514 default: assert(0 && "Unknown storage class!");
515 case DeclSpec::SCS_auto:
516 case DeclSpec::SCS_register:
517 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
518 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000519 InvalidDecl = true;
520 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
522 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
523 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
524 }
525
526 FunctionDecl *NewFD = new FunctionDecl(D.getIdentifierLoc(), II, R, SC,
Chris Lattner70c8b2e2007-08-26 04:02:13 +0000527 D.getDeclSpec().isInlineSpecified(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 LastDeclarator);
529
530 // Merge the decl with the existing one if appropriate.
531 if (PrevDecl) {
532 NewFD = MergeFunctionDecl(NewFD, PrevDecl);
533 if (NewFD == 0) return 0;
534 }
535 New = NewFD;
536 } else {
537 QualType R = GetTypeForDeclarator(D, S);
Steve Naroff53a32342007-08-28 18:45:29 +0000538 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000539
540 VarDecl *NewVD;
541 VarDecl::StorageClass SC;
542 switch (D.getDeclSpec().getStorageClassSpec()) {
543 default: assert(0 && "Unknown storage class!");
544 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
545 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
546 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
547 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
548 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
549 }
550 if (S->getParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 // C99 6.9p2: The storage-class specifiers auto and register shall not
552 // appear in the declaration specifiers in an external declaration.
553 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
554 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
555 R.getAsString());
Steve Naroff53a32342007-08-28 18:45:29 +0000556 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 NewVD = new FileVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000559 } else {
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 NewVD = new BlockVarDecl(D.getIdentifierLoc(), II, R, SC, LastDeclarator);
Steve Naroff53a32342007-08-28 18:45:29 +0000561 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 // Handle attributes prior to checking for duplicates in MergeVarDecl
563 HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
564 D.getAttributes());
565
566 // Merge the decl with the existing one if appropriate.
567 if (PrevDecl) {
568 NewVD = MergeVarDecl(NewVD, PrevDecl);
569 if (NewVD == 0) return 0;
570 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 New = NewVD;
572 }
573
574 // If this has an identifier, add it to the scope stack.
575 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000576 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 II->setFETokenInfo(New);
578 S->AddDecl(New);
579 }
580
581 if (S->getParent() == 0)
582 AddTopLevelDecl(New, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +0000583
584 // If any semantic error occurred, mark the decl as invalid.
585 if (D.getInvalidType() || InvalidDecl)
586 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000587
588 return New;
589}
590
Steve Naroffbb204692007-09-12 14:07:44 +0000591void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +0000592 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +0000593 Expr *Init = static_cast<Expr *>(init);
594
Steve Naroff410e3e22007-09-12 20:13:48 +0000595 assert((RealDecl && Init) && "missing decl or initializer");
Steve Naroffbb204692007-09-12 14:07:44 +0000596
Steve Naroff410e3e22007-09-12 20:13:48 +0000597 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
598 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +0000599 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
600 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +0000601 RealDecl->setInvalidDecl();
602 return;
603 }
Steve Naroffbb204692007-09-12 14:07:44 +0000604 // Get the decls type and save a reference for later, since
605 // CheckInitializer may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +0000606 QualType DclT = VDecl->getType(), SavT = DclT;
607 if (BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000608 VarDecl::StorageClass SC = BVD->getStorageClass();
609 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +0000610 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000611 BVD->setInvalidDecl();
612 } else if (!BVD->isInvalidDecl()) {
613 CheckInitializer(Init, DclT, SC == VarDecl::Static);
614 }
Steve Naroff410e3e22007-09-12 20:13:48 +0000615 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(VDecl)) {
Steve Naroffbb204692007-09-12 14:07:44 +0000616 if (FVD->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +0000617 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroffbb204692007-09-12 14:07:44 +0000618 if (!FVD->isInvalidDecl())
619 CheckInitializer(Init, DclT, true);
620 }
621 // If the type changed, it means we had an incomplete type that was
622 // completed by the initializer. For example:
623 // int ary[] = { 1, 3, 5 };
624 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Steve Naroff410e3e22007-09-12 20:13:48 +0000625 if (!VDecl->isInvalidDecl() && (DclT != SavT))
626 VDecl->setType(DclT);
Steve Naroffbb204692007-09-12 14:07:44 +0000627
628 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +0000629 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +0000630 return;
631}
632
Reid Spencer5f016e22007-07-11 17:01:13 +0000633/// The declarators are chained together backwards, reverse the list.
634Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
635 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +0000636 Decl *GroupDecl = static_cast<Decl*>(group);
637 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +0000638 return 0;
Steve Naroff94745042007-09-13 23:52:58 +0000639
640 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
641 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +0000642 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000643 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +0000644 else { // reverse the list.
645 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +0000646 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +0000647 Group->setNextDeclarator(NewGroup);
648 NewGroup = Group;
649 Group = Next;
650 }
651 }
652 // Perform semantic analysis that depends on having fully processed both
653 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +0000654 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +0000655 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
656 if (!IDecl)
657 continue;
658 FileVarDecl *FVD = dyn_cast<FileVarDecl>(IDecl);
659 BlockVarDecl *BVD = dyn_cast<BlockVarDecl>(IDecl);
660 QualType T = IDecl->getType();
661
662 // C99 6.7.5.2p2: If an identifier is declared to be an object with
663 // static storage duration, it shall not have a variable length array.
664 if ((FVD || BVD) && IDecl->getStorageClass() == VarDecl::Static) {
665 if (const VariableArrayType *VLA = T->getAsVariableArrayType()) {
666 if (VLA->getSizeExpr()) {
667 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
668 IDecl->setInvalidDecl();
669 }
670 }
671 }
672 // Block scope. C99 6.7p7: If an identifier for an object is declared with
673 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
674 if (BVD && IDecl->getStorageClass() != VarDecl::Extern) {
675 if (T->isIncompleteType()) {
676 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
677 T.getAsString());
678 IDecl->setInvalidDecl();
679 }
680 }
681 // File scope. C99 6.9.2p2: A declaration of an identifier for and
682 // object that has file scope without an initializer, and without a
683 // storage-class specifier or with the storage-class specifier "static",
684 // constitutes a tentative definition. Note: A tentative definition with
685 // external linkage is valid (C99 6.2.2p5).
686 if (FVD && !FVD->getInit() && FVD->getStorageClass() == VarDecl::Static) {
687 // C99 6.9.2p3: If the declaration of an identifier for an object is
688 // a tentative definition and has internal linkage (C99 6.2.2p3), the
689 // declared type shall not be an incomplete type.
690 if (T->isIncompleteType()) {
691 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
692 T.getAsString());
693 IDecl->setInvalidDecl();
694 }
695 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 }
697 return NewGroup;
698}
Steve Naroffe1223f72007-08-28 03:03:08 +0000699
700// Called from Sema::ParseStartOfFunctionDef().
Reid Spencer5f016e22007-07-11 17:01:13 +0000701ParmVarDecl *
702Sema::ParseParamDeclarator(DeclaratorChunk &FTI, unsigned ArgNo,
703 Scope *FnScope) {
704 const DeclaratorChunk::ParamInfo &PI = FTI.Fun.ArgInfo[ArgNo];
705
706 IdentifierInfo *II = PI.Ident;
707 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
708 // Can this happen for params? We already checked that they don't conflict
709 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner8b9023b2007-07-13 03:05:23 +0000710 if (/*Decl *PrevDecl = */LookupScopedDecl(II, Decl::IDNS_Ordinary,
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 PI.IdentLoc, FnScope)) {
712
713 }
714
715 // FIXME: Handle storage class (auto, register). No declarator?
716 // TODO: Chain to previous parameter with the prevdeclarator chain?
Steve Naroff6a9f3e32007-08-07 22:44:21 +0000717
718 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
719 // Doing the promotion here has a win and a loss. The win is the type for
720 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
721 // code generator). The loss is the orginal type isn't preserved. For example:
722 //
723 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
724 // int blockvardecl[5];
725 // sizeof(parmvardecl); // size == 4
726 // sizeof(blockvardecl); // size == 20
727 // }
728 //
729 // For expressions, all implicit conversions are captured using the
730 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
731 //
732 // FIXME: If a source translation tool needs to see the original type, then
733 // we need to consider storing both types (in ParmVarDecl)...
734 //
735 QualType parmDeclType = QualType::getFromOpaquePtr(PI.TypeInfo);
736 if (const ArrayType *AT = parmDeclType->getAsArrayType())
737 parmDeclType = Context.getPointerType(AT->getElementType());
738 else if (parmDeclType->isFunctionType())
739 parmDeclType = Context.getPointerType(parmDeclType);
740
741 ParmVarDecl *New = new ParmVarDecl(PI.IdentLoc, II, parmDeclType,
Steve Naroff53a32342007-08-28 18:45:29 +0000742 VarDecl::None, 0);
743 if (PI.InvalidType)
744 New->setInvalidDecl();
745
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 // If this has an identifier, add it to the scope stack.
747 if (II) {
Steve Naroffc752d042007-09-13 18:10:37 +0000748 New->setNext(II->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 II->setFETokenInfo(New);
750 FnScope->AddDecl(New);
751 }
752
753 return New;
754}
755
756
757Sema::DeclTy *Sema::ParseStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
758 assert(CurFunctionDecl == 0 && "Function parsing confused");
759 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
760 "Not a function declarator!");
761 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
762
763 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
764 // for a K&R function.
765 if (!FTI.hasPrototype) {
766 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
767 if (FTI.ArgInfo[i].TypeInfo == 0) {
768 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
769 FTI.ArgInfo[i].Ident->getName());
770 // Implicitly declare the argument as type 'int' for lack of a better
771 // type.
772 FTI.ArgInfo[i].TypeInfo = Context.IntTy.getAsOpaquePtr();
773 }
774 }
775
776 // Since this is a function definition, act as though we have information
777 // about the arguments.
778 FTI.hasPrototype = true;
779 } else {
780 // FIXME: Diagnose arguments without names in C.
781
782 }
783
784 Scope *GlobalScope = FnBodyScope->getParent();
785
786 FunctionDecl *FD =
Steve Naroff08d92e42007-09-15 18:49:24 +0000787 static_cast<FunctionDecl*>(ActOnDeclarator(GlobalScope, D, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 CurFunctionDecl = FD;
789
790 // Create Decl objects for each parameter, adding them to the FunctionDecl.
791 llvm::SmallVector<ParmVarDecl*, 16> Params;
792
793 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
794 // no arguments, not a function that takes a single void argument.
795 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
796 FTI.ArgInfo[0].TypeInfo == Context.VoidTy.getAsOpaquePtr()) {
797 // empty arg list, don't push any params.
798 } else {
799 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
800 Params.push_back(ParseParamDeclarator(D.getTypeObject(0), i,FnBodyScope));
801 }
802
803 FD->setParams(&Params[0], Params.size());
804
805 return FD;
806}
807
808Sema::DeclTy *Sema::ParseFunctionDefBody(DeclTy *D, StmtTy *Body) {
809 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
810 FD->setBody((Stmt*)Body);
811
812 assert(FD == CurFunctionDecl && "Function parsing confused");
813 CurFunctionDecl = 0;
814
815 // Verify and clean out per-function state.
816
817 // Check goto/label use.
818 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
819 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
820 // Verify that we have no forward references left. If so, there was a goto
821 // or address of a label taken, but no definition of it. Label fwd
822 // definitions are indicated with a null substmt.
823 if (I->second->getSubStmt() == 0) {
824 LabelStmt *L = I->second;
825 // Emit error.
826 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
827
828 // At this point, we have gotos that use the bogus label. Stitch it into
829 // the function body so that they aren't leaked and that the AST is well
830 // formed.
831 L->setSubStmt(new NullStmt(L->getIdentLoc()));
832 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
833 }
834 }
835 LabelMap.clear();
836
837 return FD;
838}
839
840
841/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
842/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000843ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
844 IdentifierInfo &II, Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 if (getLangOptions().C99) // Extension in C99.
846 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
847 else // Legal in C90, but warn about it.
848 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
849
850 // FIXME: handle stuff like:
851 // void foo() { extern float X(); }
852 // void bar() { X(); } <-- implicit decl for X in another scope.
853
854 // Set a Declarator for the implicit definition: int foo();
855 const char *Dummy;
856 DeclSpec DS;
857 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
858 Error = Error; // Silence warning.
859 assert(!Error && "Error setting up implicit decl!");
860 Declarator D(DS, Declarator::BlockContext);
861 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
862 D.SetIdentifier(&II, Loc);
863
864 // Find translation-unit scope to insert this function into.
Chris Lattner31e05722007-08-26 06:24:45 +0000865 if (Scope *FnS = S->getFnParent())
866 S = FnS->getParent(); // Skip all scopes in a function at once.
Reid Spencer5f016e22007-07-11 17:01:13 +0000867 while (S->getParent())
868 S = S->getParent();
869
Steve Naroff8c9f13e2007-09-16 16:16:00 +0000870 return dyn_cast<ScopedDecl>(static_cast<Decl*>(ActOnDeclarator(S, D, 0)));
Reid Spencer5f016e22007-07-11 17:01:13 +0000871}
872
873
874TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D,
Steve Naroff94745042007-09-13 23:52:58 +0000875 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
877
878 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000879 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +0000880
881 // Scope manipulation handled by caller.
Steve Naroff5912a352007-08-28 20:14:24 +0000882 TypedefDecl *NewTD = new TypedefDecl(D.getIdentifierLoc(), D.getIdentifier(),
883 T, LastDeclarator);
884 if (D.getInvalidType())
885 NewTD->setInvalidDecl();
886 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +0000887}
888
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000889Sema::DeclTy *Sema::ObjcStartClassInterface(Scope* S,
890 SourceLocation AtInterfaceLoc,
Steve Naroff3536b442007-09-06 21:24:23 +0000891 IdentifierInfo *ClassName, SourceLocation ClassLoc,
892 IdentifierInfo *SuperName, SourceLocation SuperLoc,
893 IdentifierInfo **ProtocolNames, unsigned NumProtocols,
894 AttributeList *AttrList) {
895 assert(ClassName && "Missing class identifier");
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000896
897 // Check for another declaration kind with the same name.
898 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
899 ClassLoc, S);
900 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
901 && !isa<ObjcProtocolDecl>(PrevDecl)) {
902 Diag(ClassLoc, diag::err_redefinition_different_kind,
903 ClassName->getName());
904 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
905 }
906
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000907 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000908 if (IDecl) {
909 // Class already seen. Is it a forward declaration?
910 if (!IDecl->getIsForwardDecl())
911 Diag(AtInterfaceLoc, diag::err_duplicate_class_def, ClassName->getName());
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000912 else {
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000913 IDecl->setIsForwardDecl(false);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000914 IDecl->AllocIntfRefProtocols(NumProtocols);
915 }
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000916 }
917 else {
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000918 IDecl = new ObjcInterfaceDecl(AtInterfaceLoc, NumProtocols, ClassName);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000919
Fariborz Jahanianbd51b872007-09-20 20:26:44 +0000920 // Chain & install the interface decl into the identifier.
921 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
922 ClassName->setFETokenInfo(IDecl);
923 }
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000924
925 if (SuperName) {
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000926 ObjcInterfaceDecl* SuperClassEntry = 0;
927 // Check if a different kind of symbol declared in this scope.
928 PrevDecl = LookupScopedDecl(SuperName, Decl::IDNS_Ordinary,
929 SuperLoc, S);
930 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
931 && !isa<ObjcProtocolDecl>(PrevDecl)) {
932 Diag(SuperLoc, diag::err_redefinition_different_kind,
933 SuperName->getName());
934 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000935 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000936 else {
937 // Check that super class is previously defined
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +0000938 SuperClassEntry = getObjCInterfaceDecl(S, SuperName, SuperLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000939
940 if (!SuperClassEntry || SuperClassEntry->getIsForwardDecl()) {
941 Diag(AtInterfaceLoc, diag::err_undef_superclass, SuperName->getName(),
942 ClassName->getName());
943 }
944 }
945 IDecl->setSuperClass(SuperClassEntry);
Fariborz Jahanian1d5b0e32007-09-20 17:54:07 +0000946 }
947
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000948 /// Check then save referenced protocols
949 for (unsigned int i = 0; i != NumProtocols; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000950 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtocolNames[i],
951 ClassLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +0000952 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
953 Diag(ClassLoc, diag::err_undef_protocolref,
954 ProtocolNames[i]->getName(),
955 ClassName->getName());
956 IDecl->setIntfRefProtocols((int)i, RefPDecl);
957 }
958
Steve Naroff3536b442007-09-06 21:24:23 +0000959 return IDecl;
960}
961
Fariborz Jahanianccb4f312007-09-25 18:38:09 +0000962Sema::DeclTy *Sema::ObjcStartProtoInterface(Scope* S,
963 SourceLocation AtProtoInterfaceLoc,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000964 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
965 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
966 assert(ProtocolName && "Missing protocol identifier");
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000967 ObjcProtocolDecl *PDecl = getObjCProtocolDecl(S, ProtocolName, ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000968 if (PDecl) {
969 // Protocol already seen. Better be a forward protocol declaration
970 if (!PDecl->getIsForwardProtoDecl())
971 Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
972 ProtocolName->getName());
973 else {
974 PDecl->setIsForwardProtoDecl(false);
975 PDecl->AllocReferencedProtocols(NumProtoRefs);
976 }
977 }
978 else {
979 PDecl = new ObjcProtocolDecl(AtProtoInterfaceLoc, NumProtoRefs,
980 ProtocolName);
981 PDecl->setIsForwardProtoDecl(false);
982 // Chain & install the protocol decl into the identifier.
983 PDecl->setNext(ProtocolName->getFETokenInfo<ScopedDecl>());
984 ProtocolName->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000985 }
986
987 /// Check then save referenced protocols
988 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +0000989 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
990 ProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +0000991 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
992 Diag(ProtocolLoc, diag::err_undef_protocolref,
993 ProtoRefNames[i]->getName(),
994 ProtocolName->getName());
995 PDecl->setReferencedProtocols((int)i, RefPDecl);
996 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000997
Fariborz Jahanian25e077d2007-09-17 21:07:36 +0000998 return PDecl;
999}
1000
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001001/// ObjcForwardProtocolDeclaration -
1002/// Scope will always be top level file scope.
1003Action::DeclTy *
1004Sema::ObjcForwardProtocolDeclaration(Scope *S, SourceLocation AtProtocolLoc,
1005 IdentifierInfo **IdentList, unsigned NumElts) {
1006 ObjcForwardProtocolDecl *FDecl = new ObjcForwardProtocolDecl(AtProtocolLoc,
1007 NumElts);
1008
1009 for (unsigned i = 0; i != NumElts; ++i) {
1010 ObjcProtocolDecl *PDecl;
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001011 PDecl = getObjCProtocolDecl(S, IdentList[i], AtProtocolLoc);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001012 if (!PDecl) {// Already seen?
1013 PDecl = new ObjcProtocolDecl(SourceLocation(), 0, IdentList[i], true);
1014 // Chain & install the protocol decl into the identifier.
1015 PDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1016 IdentList[i]->setFETokenInfo(PDecl);
Fariborz Jahanian894c57f2007-09-21 15:40:54 +00001017 }
1018 // Remember that this needs to be removed when the scope is popped.
1019 S->AddDecl(IdentList[i]);
1020
1021 FDecl->setForwardProtocolDecl((int)i, PDecl);
1022 }
1023 return FDecl;
1024}
1025
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001026Sema::DeclTy *Sema::ObjcStartCatInterface(Scope* S,
1027 SourceLocation AtInterfaceLoc,
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001028 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1029 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1030 IdentifierInfo **ProtoRefNames, unsigned NumProtoRefs) {
1031 ObjcCategoryDecl *CDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001032 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001033 CDecl = new ObjcCategoryDecl(AtInterfaceLoc, NumProtoRefs, ClassName);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001034 CDecl->setClassInterface(IDecl);
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001035
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001036 /// Check that class of this category is already completely declared.
1037 if (!IDecl || IDecl->getIsForwardDecl())
1038 Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
1039 else {
1040 /// Check for duplicate interface declaration for this category
1041 ObjcCategoryDecl *CDeclChain;
1042 for (CDeclChain = IDecl->getListCategories(); CDeclChain;
1043 CDeclChain = CDeclChain->getNextClassCategory()) {
1044 if (CDeclChain->getCatName() == CategoryName) {
1045 Diag(CategoryLoc, diag::err_dup_category_def, ClassName->getName(),
1046 CategoryName->getName());
1047 break;
1048 }
1049 }
1050 if (!CDeclChain) {
1051 CDecl->setCatName(CategoryName);
1052 CDecl->insertNextClassCategory();
1053 }
1054 }
1055
1056 /// Check then save referenced protocols
1057 for (unsigned int i = 0; i != NumProtoRefs; i++) {
Fariborz Jahanian1b6351f2007-09-29 17:04:06 +00001058 ObjcProtocolDecl* RefPDecl = getObjCProtocolDecl(S, ProtoRefNames[i],
1059 CategoryLoc);
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001060 if (!RefPDecl || RefPDecl->getIsForwardProtoDecl())
1061 Diag(CategoryLoc, diag::err_undef_protocolref,
1062 ProtoRefNames[i]->getName(),
1063 CategoryName->getName());
1064 CDecl->setCatReferencedProtocols((int)i, RefPDecl);
1065 }
1066
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001067 return CDecl;
1068}
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001069
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001070Sema::DeclTy *Sema::ObjcStartClassImplementation(Scope *S,
1071 SourceLocation AtClassImplLoc,
1072 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1073 IdentifierInfo *SuperClassname,
1074 SourceLocation SuperClassLoc) {
1075 ObjcInterfaceDecl* IDecl = 0;
1076 // Check for another declaration kind with the same name.
1077 ScopedDecl *PrevDecl = LookupScopedDecl(ClassName, Decl::IDNS_Ordinary,
1078 ClassLoc, S);
1079 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)) {
1080 Diag(ClassLoc, diag::err_redefinition_different_kind,
1081 ClassName->getName());
1082 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1083 }
1084 else {
1085 // Is there an interface declaration of this class; if not, warn!
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001086 IDecl = getObjCInterfaceDecl(S, ClassName, ClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001087 if (!IDecl)
1088 Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
1089 }
1090
1091 // Check that super class name is valid class name
1092 ObjcInterfaceDecl* SDecl = 0;
1093 if (SuperClassname) {
1094 // Check if a different kind of symbol declared in this scope.
1095 PrevDecl = LookupScopedDecl(SuperClassname, Decl::IDNS_Ordinary,
1096 SuperClassLoc, S);
1097 if (PrevDecl && !isa<ObjcInterfaceDecl>(PrevDecl)
1098 && !isa<ObjcProtocolDecl>(PrevDecl)) {
1099 Diag(SuperClassLoc, diag::err_redefinition_different_kind,
1100 SuperClassname->getName());
1101 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1102 }
1103 else {
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001104 SDecl = getObjCInterfaceDecl(S, SuperClassname, SuperClassLoc);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001105 if (!SDecl)
1106 Diag(SuperClassLoc, diag::err_undef_superclass,
1107 SuperClassname->getName(), ClassName->getName());
1108 else if (IDecl && IDecl->getSuperClass() != SDecl) {
1109 // This implementation and its interface do not have the same
1110 // super class.
1111 Diag(SuperClassLoc, diag::err_conflicting_super_class,
1112 SuperClassname->getName());
1113 Diag(SDecl->getLocation(), diag::err_previous_definition);
1114 }
1115 }
1116 }
1117
1118 ObjcImplementationDecl* IMPDecl =
1119 new ObjcImplementationDecl(AtClassImplLoc, ClassName, SDecl);
Fariborz Jahanian0da1c102007-09-25 21:00:20 +00001120 if (!IDecl) {
1121 // Legacy case of @implementation with no corresponding @interface.
1122 // Build, chain & install the interface decl into the identifier.
1123 IDecl = new ObjcInterfaceDecl(AtClassImplLoc, 0, ClassName);
1124 IDecl->setNext(ClassName->getFETokenInfo<ScopedDecl>());
1125 ClassName->setFETokenInfo(IDecl);
1126
1127 }
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001128
1129 // Check that there is no duplicate implementation of this class.
1130 bool err = false;
1131 for (unsigned i = 0; i != Context.sizeObjcImplementationClass(); i++) {
1132 if (Context.getObjcImplementationClass(i)->getIdentifier() == ClassName) {
1133 Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
1134 err = true;
1135 break;
1136 }
1137 }
1138 if (!err)
1139 Context.setObjcImplementationClass(IMPDecl);
1140
1141 return IMPDecl;
1142}
1143
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001144void Sema::ActOnImpleIvarVsClassIvars(DeclTy *ClassDecl,
1145 DeclTy **Fields, unsigned numIvars) {
1146 ObjcInterfaceDecl* IDecl =
1147 cast<ObjcInterfaceDecl>(static_cast<Decl*>(ClassDecl));
1148 assert(IDecl && "missing named interface class decl");
1149 ObjcIvarDecl** ivars = reinterpret_cast<ObjcIvarDecl**>(Fields);
1150 assert(ivars && "missing @implementation ivars");
1151
1152 // Check interface's Ivar list against those in the implementation.
1153 // names and types must match.
1154 //
1155 ObjcIvarDecl** IntfIvars = IDecl->getIntfDeclIvars();
1156 int IntfNumIvars = IDecl->getIntfDeclNumIvars();
1157 unsigned j = 0;
1158 bool err = false;
1159 while (numIvars > 0 && IntfNumIvars > 0) {
1160 ObjcIvarDecl* ImplIvar = ivars[j];
1161 ObjcIvarDecl* ClsIvar = IntfIvars[j++];
1162 assert (ImplIvar && "missing implementation ivar");
1163 assert (ClsIvar && "missing class ivar");
1164 if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
1165 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
1166 ImplIvar->getIdentifier()->getName());
1167 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1168 ClsIvar->getIdentifier()->getName());
1169 }
1170 // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
1171 // as error.
1172 else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1173 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
1174 ImplIvar->getIdentifier()->getName());
1175 Diag(ClsIvar->getLocation(), diag::err_previous_definition,
1176 ClsIvar->getIdentifier()->getName());
1177 err = true;
1178 break;
1179 }
1180 --numIvars;
1181 --IntfNumIvars;
1182 }
1183 if (!err && (numIvars > 0 || IntfNumIvars > 0))
1184 Diag(numIvars > 0 ? ivars[j]->getLocation() : IntfIvars[j]->getLocation(),
1185 diag::err_inconsistant_ivar);
1186
1187}
1188
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001189/// CheckProtocolMethodDefs - This routine checks unimpletented methods
1190/// Declared in protocol, and those referenced by it.
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001191void Sema::CheckProtocolMethodDefs(ObjcProtocolDecl *PDecl,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001192 const llvm::DenseMap<void *, char>& InsMap,
1193 const llvm::DenseMap<void *, char>& ClsMap) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001194 // check unimplemented instance methods.
1195 ObjcMethodDecl** methods = PDecl->getInsMethods();
1196 for (int j = 0; j < PDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001197 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001198 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001199 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1200 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001201 }
1202 // check unimplemented class methods
1203 methods = PDecl->getClsMethods();
1204 for (int j = 0; j < PDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001205 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001206 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001207 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1208 methods[j]->getSelector().getName(buf));
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001209 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001210
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001211 // Check on this protocols's referenced protocols, recursively
1212 ObjcProtocolDecl** RefPDecl = PDecl->getReferencedProtocols();
1213 for (int i = 0; i < PDecl->getNumReferencedProtocols(); i++)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001214 CheckProtocolMethodDefs(RefPDecl[i], InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001215}
1216
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001217void Sema::ImplMethodsVsClassMethods(ObjcImplementationDecl* IMPDecl,
1218 ObjcInterfaceDecl* IDecl) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001219 llvm::DenseMap<void *, char> InsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001220 // Check and see if instance methods in class interface have been
1221 // implemented in the implementation class.
1222 ObjcMethodDecl **methods = IMPDecl->getInsMethods();
1223 for (int i=0; i < IMPDecl->getNumInsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001224 InsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001225 }
1226
1227 methods = IDecl->getInsMethods();
1228 for (int j = 0; j < IDecl->getNumInsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001229 if (!InsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001230 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001231 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1232 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001233 }
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001234 llvm::DenseMap<void *, char> ClsMap;
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001235 // Check and see if class methods in class interface have been
1236 // implemented in the implementation class.
1237 methods = IMPDecl->getClsMethods();
1238 for (int i=0; i < IMPDecl->getNumClsMethods(); i++) {
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001239 ClsMap[methods[i]->getSelector().getAsOpaquePtr()] = 'a';
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001240 }
1241
1242 methods = IDecl->getClsMethods();
1243 for (int j = 0; j < IDecl->getNumClsMethods(); j++)
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001244 if (!ClsMap.count(methods[j]->getSelector().getAsOpaquePtr())) {
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001245 llvm::SmallString<128> buf;
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001246 Diag(methods[j]->getLocation(), diag::warn_undef_method_impl,
1247 methods[j]->getSelector().getName(buf));
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001248 }
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001249
1250 // Check the protocol list for unimplemented methods in the @implementation
1251 // class.
1252 ObjcProtocolDecl** protocols = IDecl->getIntfRefProtocols();
1253 for (int i = 0; i < IDecl->getNumIntfRefProtocols(); i++) {
1254 ObjcProtocolDecl* PDecl = protocols[i];
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001255 CheckProtocolMethodDefs(PDecl, InsMap, ClsMap);
Fariborz Jahanian00ae8d52007-09-28 17:40:07 +00001256 }
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001257 return;
1258}
1259
Steve Naroff3536b442007-09-06 21:24:23 +00001260/// ObjcClassDeclaration -
1261/// Scope will always be top level file scope.
1262Action::DeclTy *
1263Sema::ObjcClassDeclaration(Scope *S, SourceLocation AtClassLoc,
1264 IdentifierInfo **IdentList, unsigned NumElts) {
1265 ObjcClassDecl *CDecl = new ObjcClassDecl(AtClassLoc, NumElts);
1266
1267 for (unsigned i = 0; i != NumElts; ++i) {
1268 ObjcInterfaceDecl *IDecl;
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001269 IDecl = getObjCInterfaceDecl(S, IdentList[i], AtClassLoc);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001270 if (!IDecl) {// Already seen?
Fariborz Jahanianb27c1562007-09-22 00:01:35 +00001271 IDecl = new ObjcInterfaceDecl(SourceLocation(), 0, IdentList[i], true);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001272 // Chain & install the interface decl into the identifier.
1273 IDecl->setNext(IdentList[i]->getFETokenInfo<ScopedDecl>());
1274 IdentList[i]->setFETokenInfo(IDecl);
Fariborz Jahanianbd51b872007-09-20 20:26:44 +00001275 }
Steve Naroff3536b442007-09-06 21:24:23 +00001276 // Remember that this needs to be removed when the scope is popped.
1277 S->AddDecl(IdentList[i]);
1278
1279 CDecl->setInterfaceDecl((int)i, IDecl);
1280 }
1281 return CDecl;
1282}
1283
Reid Spencer5f016e22007-07-11 17:01:13 +00001284
Steve Naroff08d92e42007-09-15 18:49:24 +00001285/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001286/// former case, Name will be non-null. In the later case, Name will be null.
1287/// TagType indicates what kind of tag this is. TK indicates whether this is a
1288/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001289Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 SourceLocation KWLoc, IdentifierInfo *Name,
1291 SourceLocation NameLoc, AttributeList *Attr) {
1292 // If this is a use of an existing tag, it must have a name.
1293 assert((Name != 0 || TK == TK_Definition) &&
1294 "Nameless record must be a definition!");
1295
1296 Decl::Kind Kind;
1297 switch (TagType) {
1298 default: assert(0 && "Unknown tag type!");
1299 case DeclSpec::TST_struct: Kind = Decl::Struct; break;
1300 case DeclSpec::TST_union: Kind = Decl::Union; break;
1301//case DeclSpec::TST_class: Kind = Decl::Class; break;
1302 case DeclSpec::TST_enum: Kind = Decl::Enum; break;
1303 }
1304
1305 // If this is a named struct, check to see if there was a previous forward
1306 // declaration or definition.
1307 if (TagDecl *PrevDecl =
1308 dyn_cast_or_null<TagDecl>(LookupScopedDecl(Name, Decl::IDNS_Tag,
1309 NameLoc, S))) {
1310
1311 // If this is a use of a previous tag, or if the tag is already declared in
1312 // the same scope (so that the definition/declaration completes or
1313 // rementions the tag), reuse the decl.
1314 if (TK == TK_Reference || S->isDeclScope(PrevDecl)) {
1315 // Make sure that this wasn't declared as an enum and now used as a struct
1316 // or something similar.
1317 if (PrevDecl->getKind() != Kind) {
1318 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1319 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1320 }
1321
1322 // If this is a use or a forward declaration, we're good.
1323 if (TK != TK_Definition)
1324 return PrevDecl;
1325
1326 // Diagnose attempts to redefine a tag.
1327 if (PrevDecl->isDefinition()) {
1328 Diag(NameLoc, diag::err_redefinition, Name->getName());
1329 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1330 // If this is a redefinition, recover by making this struct be
1331 // anonymous, which will make any later references get the previous
1332 // definition.
1333 Name = 0;
1334 } else {
1335 // Okay, this is definition of a previously declared or referenced tag.
1336 // Move the location of the decl to be the definition site.
1337 PrevDecl->setLocation(NameLoc);
1338 return PrevDecl;
1339 }
1340 }
1341 // If we get here, this is a definition of a new struct type in a nested
1342 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1343 // type.
1344 }
1345
1346 // If there is an identifier, use the location of the identifier as the
1347 // location of the decl, otherwise use the location of the struct/union
1348 // keyword.
1349 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1350
1351 // Otherwise, if this is the first time we've seen this tag, create the decl.
1352 TagDecl *New;
1353 switch (Kind) {
1354 default: assert(0 && "Unknown tag kind!");
1355 case Decl::Enum:
1356 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1357 // enum X { A, B, C } D; D should chain to X.
1358 New = new EnumDecl(Loc, Name, 0);
1359 // If this is an undefined enum, warn.
1360 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
1361 break;
1362 case Decl::Union:
1363 case Decl::Struct:
1364 case Decl::Class:
1365 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1366 // struct X { int A; } D; D should chain to X.
1367 New = new RecordDecl(Kind, Loc, Name, 0);
1368 break;
1369 }
1370
1371 // If this has an identifier, add it to the scope stack.
1372 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001373 // The scope passed in may not be a decl scope. Zip up the scope tree until
1374 // we find one that is.
1375 while ((S->getFlags() & Scope::DeclScope) == 0)
1376 S = S->getParent();
1377
1378 // Add it to the decl chain.
Steve Naroffc752d042007-09-13 18:10:37 +00001379 New->setNext(Name->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001380 Name->setFETokenInfo(New);
1381 S->AddDecl(New);
1382 }
1383
1384 return New;
1385}
1386
Steve Naroff08d92e42007-09-15 18:49:24 +00001387/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001388/// to create a FieldDecl object for it.
Steve Naroff08d92e42007-09-15 18:49:24 +00001389Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 SourceLocation DeclStart,
1391 Declarator &D, ExprTy *BitfieldWidth) {
1392 IdentifierInfo *II = D.getIdentifier();
1393 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 SourceLocation Loc = DeclStart;
1395 if (II) Loc = D.getIdentifierLoc();
1396
1397 // FIXME: Unnamed fields can be handled in various different ways, for
1398 // example, unnamed unions inject all members into the struct namespace!
1399
1400
1401 if (BitWidth) {
1402 // TODO: Validate.
1403 //printf("WARNING: BITFIELDS IGNORED!\n");
1404
1405 // 6.7.2.1p3
1406 // 6.7.2.1p4
1407
1408 } else {
1409 // Not a bitfield.
1410
1411 // validate II.
1412
1413 }
1414
1415 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001416 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
1417 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00001418
Reid Spencer5f016e22007-07-11 17:01:13 +00001419 // C99 6.7.2.1p8: A member of a structure or union may have any type other
1420 // than a variably modified type.
Steve Naroffd7444aa2007-08-31 17:20:07 +00001421 if (const VariableArrayType *VAT = T->getAsVariablyModifiedType()) {
1422 Diag(Loc, diag::err_typecheck_illegal_vla,
1423 VAT->getSizeExpr()->getSourceRange());
1424 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 // FIXME: Chain fielddecls together.
Steve Naroff44739212007-09-11 21:17:26 +00001427 FieldDecl *NewFD;
1428
1429 if (isa<RecordDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001430 NewFD = new FieldDecl(Loc, II, T);
Fariborz Jahanianccb4f312007-09-25 18:38:09 +00001431 else if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(TagDecl))
1432 || isa<ObjcImplementationDecl>(static_cast<Decl *>(TagDecl)))
Steve Narofff38661e2007-09-14 02:20:46 +00001433 NewFD = new ObjcIvarDecl(Loc, II, T);
Steve Naroff44739212007-09-11 21:17:26 +00001434 else
Steve Naroff08d92e42007-09-15 18:49:24 +00001435 assert(0 && "Sema::ActOnField(): Unknown TagDecl");
Steve Naroff44739212007-09-11 21:17:26 +00001436
Steve Naroff5912a352007-08-28 20:14:24 +00001437 if (D.getInvalidType() || InvalidDecl)
1438 NewFD->setInvalidDecl();
1439 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001440}
1441
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001442/// TranslateIvarVisibility - Translate visibility from a token ID to an
1443/// AST enum value.
1444static ObjcIvarDecl::AccessControl
1445TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00001446 switch (ivarVisibility) {
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001447 case tok::objc_private: return ObjcIvarDecl::Private;
1448 case tok::objc_public: return ObjcIvarDecl::Public;
1449 case tok::objc_protected: return ObjcIvarDecl::Protected;
1450 case tok::objc_package: return ObjcIvarDecl::Package;
1451 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00001452 }
1453}
1454
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001455void Sema::ActOnFields(Scope* S,
1456 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00001457 DeclTy **Fields, unsigned NumFields,
1458 tok::ObjCKeywordKind *visibility) {
Steve Naroff74216642007-09-14 22:20:54 +00001459 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
1460 assert(EnclosingDecl && "missing record or interface decl");
1461 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
1462
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001463 if (Record && Record->isDefinition()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // Diagnose code like:
1465 // struct S { struct S {} X; };
1466 // We discover this when we complete the outer S. Reject and ignore the
1467 // outer S.
1468 Diag(Record->getLocation(), diag::err_nested_redefinition,
1469 Record->getKindName());
1470 Diag(RecLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001471 Record->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 return;
1473 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001474 // Verify that all the fields are okay.
1475 unsigned NumNamedMembers = 0;
1476 llvm::SmallVector<FieldDecl*, 32> RecFields;
1477 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00001478
Reid Spencer5f016e22007-07-11 17:01:13 +00001479 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001480
Steve Naroff74216642007-09-14 22:20:54 +00001481 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
1482 assert(FD && "missing field decl");
1483
1484 // Remember all fields.
1485 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001486
1487 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00001488 Type *FDTy = FD->getType().getTypePtr();
Reid Spencer5f016e22007-07-11 17:01:13 +00001489
Steve Narofff13271f2007-09-14 23:09:53 +00001490 // If we have visibility info, make sure the AST is set accordingly.
1491 if (visibility)
Fariborz Jahanian89204a12007-10-01 16:53:59 +00001492 cast<ObjcIvarDecl>(FD)->setAccessControl(
1493 TranslateIvarVisibility(visibility[i]));
Steve Narofff13271f2007-09-14 23:09:53 +00001494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00001496 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00001497 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001499 FD->setInvalidDecl();
1500 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 continue;
1502 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
1504 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001505 if (!Record) { // Incomplete ivar type is always an error.
1506 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001507 FD->setInvalidDecl();
1508 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001509 continue;
1510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 if (i != NumFields-1 || // ... that the last member ...
1512 Record->getKind() != Decl::Struct || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00001513 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001514 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001515 FD->setInvalidDecl();
1516 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 continue;
1518 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001519 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00001520 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
1521 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 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001526 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001527 if (Record)
1528 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001529 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
1531 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00001532 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001533 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
1534 // If this is a member of a union, then entire union becomes "flexible".
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001535 if (Record && Record->getKind() == Decl::Union) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001536 Record->setHasFlexibleArrayMember(true);
1537 } else {
1538 // If this is a struct/class and this is not the last element, reject
1539 // it. Note that GCC supports variable sized arrays in the middle of
1540 // structures.
1541 if (i != NumFields-1) {
1542 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
1543 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00001544 FD->setInvalidDecl();
1545 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001546 continue;
1547 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 // We support flexible arrays at the end of structs in other structs
1549 // as an extension.
1550 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
1551 FD->getName());
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001552 if (Record)
1553 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 }
1555 }
1556 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001557 // Keep track of the number of named members.
1558 if (IdentifierInfo *II = FD->getIdentifier()) {
1559 // Detect duplicate member names.
1560 if (!FieldIDs.insert(II)) {
1561 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
1562 // Find the previous decl.
1563 SourceLocation PrevLoc;
1564 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
1565 assert(i != e && "Didn't find previous def!");
1566 if (RecFields[i]->getIdentifier() == II) {
1567 PrevLoc = RecFields[i]->getLocation();
1568 break;
1569 }
1570 }
1571 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00001572 FD->setInvalidDecl();
1573 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 continue;
1575 }
1576 ++NumNamedMembers;
1577 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001578 }
1579
Reid Spencer5f016e22007-07-11 17:01:13 +00001580 // Okay, we successfully defined 'Record'.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00001581 if (Record)
1582 Record->defineBody(&RecFields[0], RecFields.size());
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001583 else {
1584 ObjcIvarDecl **ClsFields =
1585 reinterpret_cast<ObjcIvarDecl**>(&RecFields[0]);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001586 if (isa<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl)))
1587 cast<ObjcInterfaceDecl>(static_cast<Decl*>(RecDecl))->
1588 ObjcAddInstanceVariablesToClass(ClsFields, RecFields.size());
1589 else if (isa<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl))) {
1590 ObjcImplementationDecl* IMPDecl =
1591 cast<ObjcImplementationDecl>(static_cast<Decl*>(RecDecl));
1592 assert(IMPDecl && "ActOnFields - missing ObjcImplementationDecl");
1593 IMPDecl->ObjcAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001594 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1595 IMPDecl->getIdentifier(), RecLoc);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00001596 if (IDecl)
1597 ActOnImpleIvarVsClassIvars(static_cast<DeclTy*>(IDecl),
1598 reinterpret_cast<DeclTy**>(&RecFields[0]), RecFields.size());
1599 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00001600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001601}
1602
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001603void Sema::ObjcAddMethodsToClass(Scope* S, DeclTy *ClassDecl,
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001604 DeclTy **allMethods, unsigned allNum) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001605 // FIXME: Fix this when we can handle methods declared in protocols.
1606 // See Parser::ParseObjCAtProtocolDeclaration
1607 if (!ClassDecl)
1608 return;
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001609 llvm::SmallVector<ObjcMethodDecl*, 32> insMethods;
1610 llvm::SmallVector<ObjcMethodDecl*, 16> clsMethods;
1611
1612 for (unsigned i = 0; i < allNum; i++ ) {
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001613 ObjcMethodDecl *Method =
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001614 cast_or_null<ObjcMethodDecl>(static_cast<Decl*>(allMethods[i]));
1615 if (!Method) continue; // Already issued a diagnostic.
1616 if (Method->isInstance())
1617 insMethods.push_back(Method);
1618 else
1619 clsMethods.push_back(Method);
1620 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001621 if (isa<ObjcInterfaceDecl>(static_cast<Decl *>(ClassDecl))) {
1622 ObjcInterfaceDecl *Interface = cast<ObjcInterfaceDecl>(
1623 static_cast<Decl*>(ClassDecl));
1624 Interface->ObjcAddMethods(&insMethods[0], insMethods.size(),
1625 &clsMethods[0], clsMethods.size());
1626 }
1627 else if (isa<ObjcProtocolDecl>(static_cast<Decl *>(ClassDecl))) {
1628 ObjcProtocolDecl *Protocol = cast<ObjcProtocolDecl>(
1629 static_cast<Decl*>(ClassDecl));
1630 Protocol->ObjcAddProtoMethods(&insMethods[0], insMethods.size(),
1631 &clsMethods[0], clsMethods.size());
1632 }
Fariborz Jahanianfd225cc2007-09-18 20:26:58 +00001633 else if (isa<ObjcCategoryDecl>(static_cast<Decl *>(ClassDecl))) {
1634 ObjcCategoryDecl *Category = cast<ObjcCategoryDecl>(
1635 static_cast<Decl*>(ClassDecl));
1636 Category->ObjcAddCatMethods(&insMethods[0], insMethods.size(),
1637 &clsMethods[0], clsMethods.size());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001638 }
1639 else if (isa<ObjcImplementationDecl>(static_cast<Decl *>(ClassDecl))) {
1640 ObjcImplementationDecl* ImplClass = cast<ObjcImplementationDecl>(
1641 static_cast<Decl*>(ClassDecl));
1642 ImplClass->ObjcAddImplMethods(&insMethods[0], insMethods.size(),
1643 &clsMethods[0], clsMethods.size());
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00001644 ObjcInterfaceDecl* IDecl = getObjCInterfaceDecl(S,
1645 ImplClass->getIdentifier(), SourceLocation());
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001646 if (IDecl)
Fariborz Jahanian8c74fa42007-09-29 17:14:55 +00001647 ImplMethodsVsClassMethods(ImplClass, IDecl);
Fariborz Jahaniand0b01542007-09-27 18:57:03 +00001648 }
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001649 else
1650 assert(0 && "Sema::ObjcAddMethodsToClass(): Unknown DeclTy");
Fariborz Jahaniane3a2ca72007-09-10 20:33:04 +00001651 return;
1652}
1653
Fariborz Jahanian00933592007-09-18 00:25:23 +00001654Sema::DeclTy *Sema::ObjcBuildMethodDeclaration(SourceLocation MethodLoc,
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001655 tok::TokenKind MethodType, TypeTy *ReturnType, Selector Sel,
Steve Naroff68d331a2007-09-27 14:38:14 +00001656 // optional arguments. The number of types/arguments is obtained
1657 // from the Sel.getNumArgs().
1658 TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1659 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001660 llvm::SmallVector<ParmVarDecl*, 16> Params;
1661
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001662 for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001663 // FIXME: arg->AttrList must be stored too!
Steve Naroff68d331a2007-09-27 14:38:14 +00001664 ParmVarDecl* Param = new ParmVarDecl(SourceLocation(/*FIXME*/), ArgNames[i],
1665 QualType::getFromOpaquePtr(ArgTypes[i]),
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001666 VarDecl::None, 0);
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001667 Params.push_back(Param);
1668 }
1669 QualType resultDeclType = QualType::getFromOpaquePtr(ReturnType);
Steve Naroff68d331a2007-09-27 14:38:14 +00001670 ObjcMethodDecl* ObjcMethod = new ObjcMethodDecl(MethodLoc, Sel,
1671 resultDeclType, 0, -1, AttrList,
Fariborz Jahanian3a63da72007-09-29 18:24:58 +00001672 MethodType == tok::minus,
1673 MethodDeclKind == tok::objc_optional ?
1674 ObjcMethodDecl::Optional :
1675 ObjcMethodDecl::Required);
Steve Naroffbcfb06a2007-09-28 22:22:11 +00001676 ObjcMethod->setMethodParams(&Params[0], Sel.getNumArgs());
Fariborz Jahanian25e077d2007-09-17 21:07:36 +00001677 return ObjcMethod;
Fariborz Jahaniane55cd002007-09-12 18:23:47 +00001678}
1679
Steve Naroff08d92e42007-09-15 18:49:24 +00001680Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 DeclTy *lastEnumConst,
1682 SourceLocation IdLoc, IdentifierInfo *Id,
1683 SourceLocation EqualLoc, ExprTy *val) {
1684 theEnumDecl = theEnumDecl; // silence unused warning.
1685 EnumConstantDecl *LastEnumConst =
1686 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
1687 Expr *Val = static_cast<Expr*>(val);
1688
Chris Lattner31e05722007-08-26 06:24:45 +00001689 // The scope passed in may not be a decl scope. Zip up the scope tree until
1690 // we find one that is.
1691 while ((S->getFlags() & Scope::DeclScope) == 0)
1692 S = S->getParent();
1693
Reid Spencer5f016e22007-07-11 17:01:13 +00001694 // Verify that there isn't already something declared with this name in this
1695 // scope.
Steve Naroff8e74c932007-09-13 21:41:19 +00001696 if (ScopedDecl *PrevDecl = LookupScopedDecl(Id, Decl::IDNS_Ordinary,
1697 IdLoc, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 if (S->isDeclScope(PrevDecl)) {
1699 if (isa<EnumConstantDecl>(PrevDecl))
1700 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
1701 else
1702 Diag(IdLoc, diag::err_redefinition, Id->getName());
1703 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1704 // FIXME: Don't leak memory: delete Val;
1705 return 0;
1706 }
1707 }
1708
1709 llvm::APSInt EnumVal(32);
1710 QualType EltTy;
1711 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00001712 // Make sure to promote the operand type to int.
1713 UsualUnaryConversions(Val);
1714
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
1716 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00001717 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001718 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
1719 Id->getName());
1720 // FIXME: Don't leak memory: delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00001721 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00001722 } else {
1723 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00001725 }
1726
1727 if (!Val) {
1728 if (LastEnumConst) {
1729 // Assign the last value + 1.
1730 EnumVal = LastEnumConst->getInitVal();
1731 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00001732
1733 // Check for overflow on increment.
1734 if (EnumVal < LastEnumConst->getInitVal())
1735 Diag(IdLoc, diag::warn_enum_value_overflow);
1736
Chris Lattnerb7416f92007-08-27 17:37:24 +00001737 EltTy = LastEnumConst->getType();
1738 } else {
1739 // First value, set to zero.
1740 EltTy = Context.IntTy;
Chris Lattner701e5eb2007-09-04 02:45:27 +00001741 EnumVal.zextOrTrunc(
1742 static_cast<uint32_t>(Context.getTypeSize(EltTy, IdLoc)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00001743 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001744 }
1745
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 EnumConstantDecl *New = new EnumConstantDecl(IdLoc, Id, EltTy, Val, EnumVal,
1747 LastEnumConst);
1748
1749 // Register this decl in the current scope stack.
Steve Naroffc752d042007-09-13 18:10:37 +00001750 New->setNext(Id->getFETokenInfo<ScopedDecl>());
Reid Spencer5f016e22007-07-11 17:01:13 +00001751 Id->setFETokenInfo(New);
1752 S->AddDecl(New);
1753 return New;
1754}
1755
Steve Naroff08d92e42007-09-15 18:49:24 +00001756void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00001757 DeclTy **Elements, unsigned NumElements) {
1758 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
1759 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
1760
Chris Lattnere37f0be2007-08-28 05:10:31 +00001761 // TODO: If the result value doesn't fit in an int, it must be a long or long
1762 // long value. ISO C does not support this, but GCC does as an extension,
1763 // emit a warning.
Chris Lattnerac609682007-08-28 06:15:15 +00001764 unsigned IntWidth = Context.Target.getIntWidth(Enum->getLocation());
Chris Lattnere37f0be2007-08-28 05:10:31 +00001765
1766
Chris Lattnerac609682007-08-28 06:15:15 +00001767 // Verify that all the values are okay, compute the size of the values, and
1768 // reverse the list.
1769 unsigned NumNegativeBits = 0;
1770 unsigned NumPositiveBits = 0;
1771
1772 // Keep track of whether all elements have type int.
1773 bool AllElementsInt = true;
1774
Reid Spencer5f016e22007-07-11 17:01:13 +00001775 EnumConstantDecl *EltList = 0;
1776 for (unsigned i = 0; i != NumElements; ++i) {
1777 EnumConstantDecl *ECD =
1778 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1779 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00001780
1781 // If the enum value doesn't fit in an int, emit an extension warning.
1782 assert(ECD->getInitVal().getBitWidth() >= IntWidth &&
1783 "Should have promoted value to int");
1784 const llvm::APSInt &InitVal = ECD->getInitVal();
1785 if (InitVal.getBitWidth() > IntWidth) {
1786 llvm::APSInt V(InitVal);
1787 V.trunc(IntWidth);
1788 V.extend(InitVal.getBitWidth());
1789 if (V != InitVal)
1790 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
1791 InitVal.toString());
1792 }
Chris Lattnerac609682007-08-28 06:15:15 +00001793
1794 // Keep track of the size of positive and negative values.
1795 if (InitVal.isUnsigned() || !InitVal.isNegative())
1796 NumPositiveBits = std::max(NumPositiveBits, InitVal.getActiveBits());
1797 else
1798 NumNegativeBits = std::max(NumNegativeBits, InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00001799
Chris Lattnerac609682007-08-28 06:15:15 +00001800 // Keep track of whether every enum element has type int (very commmon).
1801 if (AllElementsInt)
1802 AllElementsInt = ECD->getType() == Context.IntTy;
1803
Reid Spencer5f016e22007-07-11 17:01:13 +00001804 ECD->setNextDeclarator(EltList);
1805 EltList = ECD;
1806 }
1807
Chris Lattnerac609682007-08-28 06:15:15 +00001808 // Figure out the type that should be used for this enum.
1809 // FIXME: Support attribute(packed) on enums and -fshort-enums.
1810 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001811 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00001812
1813 if (NumNegativeBits) {
1814 // If there is a negative value, figure out the smallest integer type (of
1815 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001816 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001817 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001818 BestWidth = IntWidth;
1819 } else {
1820 BestWidth = Context.Target.getLongWidth(Enum->getLocation());
1821 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001822 BestType = Context.LongTy;
1823 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001824 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1825 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00001826 Diag(Enum->getLocation(), diag::warn_enum_too_large);
1827 BestType = Context.LongLongTy;
1828 }
1829 }
1830 } else {
1831 // If there is no negative value, figure out which of uint, ulong, ulonglong
1832 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001833 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00001834 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001835 BestWidth = IntWidth;
1836 } else if (NumPositiveBits <=
1837 (BestWidth = Context.Target.getLongWidth(Enum->getLocation())))
Chris Lattnerac609682007-08-28 06:15:15 +00001838 BestType = Context.UnsignedLongTy;
1839 else {
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001840 BestWidth = Context.Target.getLongLongWidth(Enum->getLocation());
1841 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00001842 "How could an initializer get larger than ULL?");
1843 BestType = Context.UnsignedLongLongTy;
1844 }
1845 }
1846
Chris Lattnerb7f6e082007-08-29 17:31:48 +00001847 // Loop over all of the enumerator constants, changing their types to match
1848 // the type of the enum if needed.
1849 for (unsigned i = 0; i != NumElements; ++i) {
1850 EnumConstantDecl *ECD =
1851 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
1852 if (!ECD) continue; // Already issued a diagnostic.
1853
1854 // Standard C says the enumerators have int type, but we allow, as an
1855 // extension, the enumerators to be larger than int size. If each
1856 // enumerator value fits in an int, type it as an int, otherwise type it the
1857 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
1858 // that X has type 'int', not 'unsigned'.
1859 if (ECD->getType() == Context.IntTy)
1860 continue; // Already int type.
1861
1862 // Determine whether the value fits into an int.
1863 llvm::APSInt InitVal = ECD->getInitVal();
1864 bool FitsInInt;
1865 if (InitVal.isUnsigned() || !InitVal.isNegative())
1866 FitsInInt = InitVal.getActiveBits() < IntWidth;
1867 else
1868 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
1869
1870 // If it fits into an integer type, force it. Otherwise force it to match
1871 // the enum decl type.
1872 QualType NewTy;
1873 unsigned NewWidth;
1874 bool NewSign;
1875 if (FitsInInt) {
1876 NewTy = Context.IntTy;
1877 NewWidth = IntWidth;
1878 NewSign = true;
1879 } else if (ECD->getType() == BestType) {
1880 // Already the right type!
1881 continue;
1882 } else {
1883 NewTy = BestType;
1884 NewWidth = BestWidth;
1885 NewSign = BestType->isSignedIntegerType();
1886 }
1887
1888 // Adjust the APSInt value.
1889 InitVal.extOrTrunc(NewWidth);
1890 InitVal.setIsSigned(NewSign);
1891 ECD->setInitVal(InitVal);
1892
1893 // Adjust the Expr initializer and type.
1894 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
1895 ECD->setType(NewTy);
1896 }
Chris Lattnerac609682007-08-28 06:15:15 +00001897
Chris Lattnere00b18c2007-08-28 18:24:31 +00001898 Enum->defineElements(EltList, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00001899}
1900
1901void Sema::AddTopLevelDecl(Decl *current, Decl *last) {
1902 if (!current) return;
1903
1904 // If this is a top-level decl that is chained to some other (e.g. int A,B,C;)
1905 // remember this in the LastInGroupList list.
1906 if (last)
1907 LastInGroupList.push_back((Decl*)last);
1908}
1909
1910void Sema::HandleDeclAttribute(Decl *New, AttributeList *rawAttr) {
1911 if (strcmp(rawAttr->getAttributeName()->getName(), "vector_size") == 0) {
1912 if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
1913 QualType newType = HandleVectorTypeAttribute(vDecl->getType(), rawAttr);
1914 if (!newType.isNull()) // install the new vector type into the decl
1915 vDecl->setType(newType);
1916 }
1917 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
1918 QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
1919 rawAttr);
1920 if (!newType.isNull()) // install the new vector type into the decl
1921 tDecl->setUnderlyingType(newType);
1922 }
1923 }
Steve Naroff73322922007-07-18 18:00:27 +00001924 if (strcmp(rawAttr->getAttributeName()->getName(), "ocu_vector_type") == 0) {
Steve Naroffbea0b342007-07-29 16:33:31 +00001925 if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
1926 HandleOCUVectorTypeAttribute(tDecl, rawAttr);
1927 else
Steve Naroff73322922007-07-18 18:00:27 +00001928 Diag(rawAttr->getAttributeLoc(),
1929 diag::err_typecheck_ocu_vector_not_typedef);
Steve Naroff73322922007-07-18 18:00:27 +00001930 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 // FIXME: add other attributes...
1932}
1933
1934void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
1935 AttributeList *declarator_postfix) {
1936 while (declspec_prefix) {
1937 HandleDeclAttribute(New, declspec_prefix);
1938 declspec_prefix = declspec_prefix->getNext();
1939 }
1940 while (declarator_postfix) {
1941 HandleDeclAttribute(New, declarator_postfix);
1942 declarator_postfix = declarator_postfix->getNext();
1943 }
1944}
1945
Steve Naroffbea0b342007-07-29 16:33:31 +00001946void Sema::HandleOCUVectorTypeAttribute(TypedefDecl *tDecl,
1947 AttributeList *rawAttr) {
1948 QualType curType = tDecl->getUnderlyingType();
Steve Naroff73322922007-07-18 18:00:27 +00001949 // check the attribute arugments.
1950 if (rawAttr->getNumArgs() != 1) {
1951 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1952 std::string("1"));
Steve Naroffbea0b342007-07-29 16:33:31 +00001953 return;
Steve Naroff73322922007-07-18 18:00:27 +00001954 }
1955 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1956 llvm::APSInt vecSize(32);
1957 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
1958 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1959 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001960 return;
Steve Naroff73322922007-07-18 18:00:27 +00001961 }
1962 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1963 // in conjunction with complex types (pointers, arrays, functions, etc.).
1964 Type *canonType = curType.getCanonicalType().getTypePtr();
1965 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
1966 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
1967 curType.getCanonicalType().getAsString());
Steve Naroffbea0b342007-07-29 16:33:31 +00001968 return;
Steve Naroff73322922007-07-18 18:00:27 +00001969 }
1970 // unlike gcc's vector_size attribute, the size is specified as the
1971 // number of elements, not the number of bytes.
Chris Lattner701e5eb2007-09-04 02:45:27 +00001972 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
Steve Naroff73322922007-07-18 18:00:27 +00001973
1974 if (vectorSize == 0) {
1975 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
1976 sizeExpr->getSourceRange());
Steve Naroffbea0b342007-07-29 16:33:31 +00001977 return;
Steve Naroff73322922007-07-18 18:00:27 +00001978 }
Steve Naroffbea0b342007-07-29 16:33:31 +00001979 // Instantiate/Install the vector type, the number of elements is > 0.
1980 tDecl->setUnderlyingType(Context.getOCUVectorType(curType, vectorSize));
1981 // Remember this typedef decl, we will need it later for diagnostics.
1982 OCUVectorDecls.push_back(tDecl);
Steve Naroff73322922007-07-18 18:00:27 +00001983}
1984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985QualType Sema::HandleVectorTypeAttribute(QualType curType,
Chris Lattnera7674d82007-07-13 22:13:22 +00001986 AttributeList *rawAttr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 // check the attribute arugments.
1988 if (rawAttr->getNumArgs() != 1) {
1989 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_wrong_number_arguments,
1990 std::string("1"));
1991 return QualType();
1992 }
1993 Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
1994 llvm::APSInt vecSize(32);
Chris Lattner590b6642007-07-15 23:26:56 +00001995 if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_vector_size_not_int,
1997 sizeExpr->getSourceRange());
1998 return QualType();
1999 }
2000 // navigate to the base type - we need to provide for vector pointers,
2001 // vector arrays, and functions returning vectors.
2002 Type *canonType = curType.getCanonicalType().getTypePtr();
2003
Steve Naroff73322922007-07-18 18:00:27 +00002004 if (canonType->isPointerType() || canonType->isArrayType() ||
2005 canonType->isFunctionType()) {
2006 assert(1 && "HandleVector(): Complex type construction unimplemented");
2007 /* FIXME: rebuild the type from the inside out, vectorizing the inner type.
2008 do {
2009 if (PointerType *PT = dyn_cast<PointerType>(canonType))
2010 canonType = PT->getPointeeType().getTypePtr();
2011 else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
2012 canonType = AT->getElementType().getTypePtr();
2013 else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
2014 canonType = FT->getResultType().getTypePtr();
2015 } while (canonType->isPointerType() || canonType->isArrayType() ||
2016 canonType->isFunctionType());
2017 */
Reid Spencer5f016e22007-07-11 17:01:13 +00002018 }
2019 // the base type must be integer or float.
2020 if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
2021 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_vector_type,
2022 curType.getCanonicalType().getAsString());
2023 return QualType();
2024 }
Chris Lattner701e5eb2007-09-04 02:45:27 +00002025 unsigned typeSize = static_cast<unsigned>(
2026 Context.getTypeSize(curType, rawAttr->getAttributeLoc()));
Reid Spencer5f016e22007-07-11 17:01:13 +00002027 // vecSize is specified in bytes - convert to bits.
Chris Lattner701e5eb2007-09-04 02:45:27 +00002028 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029
2030 // the vector size needs to be an integral multiple of the type size.
2031 if (vectorSize % typeSize) {
2032 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_invalid_size,
2033 sizeExpr->getSourceRange());
2034 return QualType();
2035 }
2036 if (vectorSize == 0) {
2037 Diag(rawAttr->getAttributeLoc(), diag::err_attribute_zero_size,
2038 sizeExpr->getSourceRange());
2039 return QualType();
2040 }
2041 // Since OpenCU requires 3 element vectors (OpenCU 5.1.2), we don't restrict
2042 // the number of elements to be a power of two (unlike GCC).
2043 // Instantiate the vector type, the number of elements is > 0.
Steve Naroff73322922007-07-18 18:00:27 +00002044 return Context.getVectorType(curType, vectorSize/typeSize);
Reid Spencer5f016e22007-07-11 17:01:13 +00002045}
2046