1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/Parse/DeclSpec.h"
19 #include "clang/Basic/LangOptions.h"
20 using namespace clang;
22 /// ConvertDeclSpecToType - Convert the specified declspec to the appropriate
23 /// type object. This returns null on error.
24 QualType Sema::ConvertDeclSpecToType(DeclSpec &DS) {
25 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
29 switch (DS.getTypeSpecType()) {
30 default: return QualType(); // FIXME: Handle unimp cases!
31 case DeclSpec::TST_void: return Context.VoidTy;
32 case DeclSpec::TST_char:
33 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
34 Result = Context.CharTy;
35 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
36 Result = Context.SignedCharTy;
38 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
40 Result = Context.UnsignedCharTy;
43 case DeclSpec::TST_unspecified: // Unspecific typespec defaults to int.
44 case DeclSpec::TST_int: {
45 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
46 switch (DS.getTypeSpecWidth()) {
47 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
48 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
49 case DeclSpec::TSW_long: Result = Context.LongTy; break;
50 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break;
53 switch (DS.getTypeSpecWidth()) {
54 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
55 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
56 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
57 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break;
62 case DeclSpec::TST_float: Result = Context.FloatTy; break;
63 case DeclSpec::TST_double:
64 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
65 Result = Context.LongDoubleTy;
67 Result = Context.DoubleTy;
69 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
70 case DeclSpec::TST_decimal32: // _Decimal32
71 case DeclSpec::TST_decimal64: // _Decimal64
72 case DeclSpec::TST_decimal128: // _Decimal128
73 assert(0 && "FIXME: GNU decimal extensions not supported yet!");
74 case DeclSpec::TST_enum:
75 case DeclSpec::TST_union:
76 case DeclSpec::TST_struct: {
77 Decl *D = static_cast<Decl *>(DS.getTypeRep());
78 assert(D && "Didn't get a decl for a enum/union/struct?");
79 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
80 DS.getTypeSpecSign() == 0 &&
81 "Can't handle qualifiers on typedef names yet!");
82 // TypeQuals handled by caller.
83 Result = Context.getTagDeclType(cast<TagDecl>(D));
86 case DeclSpec::TST_typedef: {
87 Decl *D = static_cast<Decl *>(DS.getTypeRep());
88 assert(D && "Didn't get a decl for a typedef?");
89 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
90 DS.getTypeSpecSign() == 0 &&
91 "Can't handle qualifiers on typedef names yet!");
92 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so
93 // we have this "hack" for now...
94 if (ObjCInterfaceDecl *ObjCIntDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
95 if (DS.getProtocolQualifiers() == 0) {
96 Result = Context.getObjCInterfaceType(ObjCIntDecl);
100 Action::DeclTy **PPDecl = &(*DS.getProtocolQualifiers())[0];
101 Result = Context.getObjCQualifiedInterfaceType(ObjCIntDecl,
102 reinterpret_cast<ObjCProtocolDecl**>(PPDecl),
103 DS.NumProtocolQualifiers());
106 else if (TypedefDecl *typeDecl = dyn_cast<TypedefDecl>(D)) {
107 if (Context.getObjCIdType() == Context.getTypedefType(typeDecl)
108 && DS.getProtocolQualifiers()) {
110 Action::DeclTy **PPDecl = &(*DS.getProtocolQualifiers())[0];
111 Result = Context.getObjCQualifiedIdType(typeDecl->getUnderlyingType(),
112 reinterpret_cast<ObjCProtocolDecl**>(PPDecl),
113 DS.NumProtocolQualifiers());
117 // TypeQuals handled by caller.
118 Result = Context.getTypedefType(cast<TypedefDecl>(D));
121 case DeclSpec::TST_typeofType:
122 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
123 assert(!Result.isNull() && "Didn't get a type for typeof?");
124 // TypeQuals handled by caller.
125 Result = Context.getTypeOfType(Result);
127 case DeclSpec::TST_typeofExpr: {
128 Expr *E = static_cast<Expr *>(DS.getTypeRep());
129 assert(E && "Didn't get an expression for typeof?");
130 // TypeQuals handled by caller.
131 Result = Context.getTypeOfExpr(E);
136 // Handle complex types.
137 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex)
138 Result = Context.getComplexType(Result);
140 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
141 "FIXME: imaginary types not supported yet!");
143 // See if there are any attributes on the declspec that apply to the type (as
144 // opposed to the decl).
145 if (AttributeList *AL = DS.getAttributes())
146 DS.SetAttributes(ProcessTypeAttributes(Result, AL));
151 AttributeList *Sema::ProcessTypeAttributes(QualType &Result, AttributeList *AL){
152 // Scan through and apply attributes to this type where it makes sense. Some
153 // attributes (such as __address_space__, __vector_size__, etc) apply to the
154 // type, but others can be present in the type specifiers even though they
155 // apply to the decl. Here we apply and delete attributes that apply to the
156 // type and leave the others alone.
157 llvm::SmallVector<AttributeList *, 8> LeftOverAttrs;
159 // Unlink this attribute from the chain, so we can process it independently.
160 AttributeList *ThisAttr = AL;
162 ThisAttr->setNext(0);
164 // If this is an attribute we can handle, do so now, otherwise, add it to
165 // the LeftOverAttrs list for rechaining.
166 switch (ThisAttr->getKind()) {
168 case AttributeList::AT_address_space:
169 Result = HandleAddressSpaceTypeAttribute(Result, ThisAttr);
170 delete ThisAttr; // Consume the attribute.
174 LeftOverAttrs.push_back(ThisAttr);
177 // Rechain any attributes that haven't been deleted to the DeclSpec.
178 AttributeList *List = 0;
179 for (unsigned i = 0, e = LeftOverAttrs.size(); i != e; ++i) {
180 LeftOverAttrs[i]->setNext(List);
181 List = LeftOverAttrs[i];
187 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
189 QualType Sema::HandleAddressSpaceTypeAttribute(QualType Type,
190 AttributeList *Attr) {
191 // If this type is already address space qualified, reject it.
192 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
193 // for two or more different address spaces."
194 if (Type.getAddressSpace()) {
195 Diag(Attr->getLoc(), diag::err_attribute_address_multiple_qualifiers);
199 // Check the attribute arguments.
200 if (Attr->getNumArgs() != 1) {
201 Diag(Attr->getLoc(), diag::err_attribute_wrong_number_arguments,
205 Expr *ASArgExpr = static_cast<Expr *>(Attr->getArg(0));
206 llvm::APSInt addrSpace(32);
207 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, Context)) {
208 Diag(Attr->getLoc(), diag::err_attribute_address_space_not_int,
209 ASArgExpr->getSourceRange());
213 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
214 return Context.getASQualType(Type, ASIdx);
218 /// GetTypeForDeclarator - Convert the type for the specified declarator to Type
220 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
221 // long long is a C99 feature.
222 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
223 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
224 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
226 QualType T = ConvertDeclSpecToType(D.getDeclSpec());
228 // Apply const/volatile/restrict qualifiers to T.
229 T = T.getQualifiedType(D.getDeclSpec().getTypeQualifiers());
231 // Walk the DeclTypeInfo, building the recursive type as we go. DeclTypeInfos
232 // are ordered from the identifier out, which is opposite of what we want :).
233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
234 const DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
235 switch (DeclType.Kind) {
236 default: assert(0 && "Unknown decltype!");
237 case DeclaratorChunk::Pointer:
238 if (T->isReferenceType()) {
239 // C++ 8.3.2p4: There shall be no ... pointers to references ...
240 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_pointer_to_reference,
241 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
242 D.setInvalidType(true);
246 // Apply the pointer typequals to the pointer object.
247 T = Context.getPointerType(T).getQualifiedType(DeclType.Ptr.TypeQuals);
249 case DeclaratorChunk::Reference:
250 if (const ReferenceType *RT = T->getAsReferenceType()) {
251 // C++ 8.3.2p4: There shall be no references to references ...
252 Diag(D.getIdentifierLoc(),
253 diag::err_illegal_decl_reference_to_reference,
254 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
255 D.setInvalidType(true);
256 T = RT->getReferenceeType();
259 T = Context.getReferenceType(T);
261 case DeclaratorChunk::Array: {
262 const DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
263 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
264 ArrayType::ArraySizeModifier ASM;
266 ASM = ArrayType::Star;
267 else if (ATI.hasStatic)
268 ASM = ArrayType::Static;
270 ASM = ArrayType::Normal;
272 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
273 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
274 if (T->isIncompleteType()) {
275 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_incomplete_type,
278 D.setInvalidType(true);
279 } else if (T->isFunctionType()) {
280 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_functions,
281 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
282 T = Context.getPointerType(T);
283 D.setInvalidType(true);
284 } else if (const ReferenceType *RT = T->getAsReferenceType()) {
285 // C++ 8.3.2p4: There shall be no ... arrays of references ...
286 Diag(D.getIdentifierLoc(), diag::err_illegal_decl_array_of_references,
287 D.getIdentifier() ? D.getIdentifier()->getName() : "type name");
288 T = RT->getReferenceeType();
289 D.setInvalidType(true);
290 } else if (const RecordType *EltTy = T->getAsRecordType()) {
291 // If the element type is a struct or union that contains a variadic
292 // array, reject it: C99 6.7.2.1p2.
293 if (EltTy->getDecl()->hasFlexibleArrayMember()) {
294 Diag(DeclType.Loc, diag::err_flexible_array_in_array,
297 D.setInvalidType(true);
300 // C99 6.7.5.2p1: The size expression shall have integer type.
301 if (ArraySize && !ArraySize->getType()->isIntegerType()) {
302 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int,
303 ArraySize->getType().getAsString(), ArraySize->getSourceRange());
304 D.setInvalidType(true);
306 llvm::APSInt ConstVal(32);
307 // If no expression was provided, we consider it a VLA.
309 T = Context.getIncompleteArrayType(T, ASM, ATI.TypeQuals);
310 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context)) {
311 T = Context.getVariableArrayType(T, ArraySize, ASM, ATI.TypeQuals);
313 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
314 // have a value greater than zero.
315 if (ConstVal.isSigned()) {
316 if (ConstVal.isNegative()) {
317 Diag(ArraySize->getLocStart(),
318 diag::err_typecheck_negative_array_size,
319 ArraySize->getSourceRange());
320 D.setInvalidType(true);
321 } else if (ConstVal == 0) {
322 // GCC accepts zero sized static arrays.
323 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size,
324 ArraySize->getSourceRange());
327 T = Context.getConstantArrayType(T, ConstVal, ASM, ATI.TypeQuals);
329 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
330 if (!getLangOptions().C99 &&
331 (ASM != ArrayType::Normal ||
332 (ArraySize && !ArraySize->isIntegerConstantExpr(Context))))
333 Diag(D.getIdentifierLoc(), diag::ext_vla);
336 case DeclaratorChunk::Function:
337 // If the function declarator has a prototype (i.e. it is not () and
338 // does not have a K&R-style identifier list), then the arguments are part
339 // of the type, otherwise the argument list is ().
340 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
342 // C99 6.7.5.3p1: The return type may not be a function or array type.
343 if (T->isArrayType() || T->isFunctionType()) {
344 Diag(DeclType.Loc, diag::err_func_returning_array_function,
347 D.setInvalidType(true);
350 if (!FTI.hasPrototype) {
351 // Simple void foo(), where the incoming T is the result type.
352 T = Context.getFunctionTypeNoProto(T);
354 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
355 if (FTI.NumArgs != 0)
356 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
359 // Otherwise, we have a function with an argument list that is
360 // potentially variadic.
361 llvm::SmallVector<QualType, 16> ArgTys;
363 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
364 QualType ArgTy = QualType::getFromOpaquePtr(FTI.ArgInfo[i].TypeInfo);
365 assert(!ArgTy.isNull() && "Couldn't parse type?");
367 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
368 // This matches the conversion that is done in
369 // Sema::ActOnParamDeclarator(). Without this conversion, the
370 // argument type in the function prototype *will not* match the
371 // type in ParmVarDecl (which makes the code generator unhappy).
373 // FIXME: We still apparently need the conversion in
374 // Sema::ParseParamDeclarator(). This doesn't make any sense, since
375 // it should be driving off the type being created here.
377 // FIXME: If a source translation tool needs to see the original type,
378 // then we need to consider storing both types somewhere...
380 if (const ArrayType *AT = ArgTy->getAsArrayType()) {
381 // int x[restrict 4] -> int *restrict
382 ArgTy = Context.getPointerType(AT->getElementType());
383 ArgTy = ArgTy.getQualifiedType(AT->getIndexTypeQualifier());
384 } else if (ArgTy->isFunctionType())
385 ArgTy = Context.getPointerType(ArgTy);
386 // Look for 'void'. void is allowed only as a single argument to a
387 // function with no other parameters (C99 6.7.5.3p10). We record
388 // int(void) as a FunctionTypeProto with an empty argument list.
389 else if (ArgTy->isVoidType()) {
390 // If this is something like 'float(int, void)', reject it. 'void'
391 // is an incomplete type (C99 6.2.5p19) and function decls cannot
392 // have arguments of incomplete type.
393 if (FTI.NumArgs != 1 || FTI.isVariadic) {
394 Diag(DeclType.Loc, diag::err_void_only_param);
395 ArgTy = Context.IntTy;
396 FTI.ArgInfo[i].TypeInfo = ArgTy.getAsOpaquePtr();
397 } else if (FTI.ArgInfo[i].Ident) {
398 // Reject, but continue to parse 'int(void abc)'.
399 Diag(FTI.ArgInfo[i].IdentLoc,
400 diag::err_param_with_void_type);
401 ArgTy = Context.IntTy;
402 FTI.ArgInfo[i].TypeInfo = ArgTy.getAsOpaquePtr();
404 // Reject, but continue to parse 'float(const void)'.
405 if (ArgTy.getCVRQualifiers())
406 Diag(DeclType.Loc, diag::err_void_param_qualified);
408 // Do not add 'void' to the ArgTys list.
413 ArgTys.push_back(ArgTy);
415 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
425 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
427 QualType Sema::ObjCGetTypeForMethodDefinition(DeclTy *D) {
428 ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(static_cast<Decl *>(D));
429 QualType T = MDecl->getResultType();
430 llvm::SmallVector<QualType, 16> ArgTys;
432 // Add the first two invisible argument types for self and _cmd.
433 if (MDecl->isInstance()) {
434 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
435 selfTy = Context.getPointerType(selfTy);
436 ArgTys.push_back(selfTy);
439 ArgTys.push_back(Context.getObjCIdType());
440 ArgTys.push_back(Context.getObjCSelType());
442 for (int i = 0; i < MDecl->getNumParams(); i++) {
443 ParmVarDecl *PDecl = MDecl->getParamDecl(i);
444 QualType ArgTy = PDecl->getType();
445 assert(!ArgTy.isNull() && "Couldn't parse type?");
446 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
447 // This matches the conversion that is done in
448 // Sema::ParseParamDeclarator().
449 if (const ArrayType *AT = ArgTy->getAsArrayType())
450 ArgTy = Context.getPointerType(AT->getElementType());
451 else if (ArgTy->isFunctionType())
452 ArgTy = Context.getPointerType(ArgTy);
453 ArgTys.push_back(ArgTy);
455 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
456 MDecl->isVariadic());
460 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
461 // C99 6.7.6: Type names have no identifier. This is already validated by
463 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
465 QualType T = GetTypeForDeclarator(D, S);
467 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
469 // In this context, we *do not* check D.getInvalidType(). If the declarator
470 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
471 // though it will not reflect the user specified type.
472 return T.getAsOpaquePtr();
475 // Called from Parser::ParseParenDeclarator().
476 Sema::TypeResult Sema::ActOnParamDeclaratorType(Scope *S, Declarator &D) {
477 // Note: parameters have identifiers, but we don't care about them here, we
478 // just want the type converted.
479 QualType T = GetTypeForDeclarator(D, S);
481 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
483 // In this context, we *do not* check D.getInvalidType(). If the declarator
484 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
485 // though it will not reflect the user specified type.
486 return T.getAsOpaquePtr();