1 //===--- Type.cpp - Type representation and manipulation ------------------===//
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 functionality.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/Type.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/Basic/Specifiers.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
28 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
29 if (T.isConstQualified())
32 if (const ArrayType *AT = Ctx.getAsArrayType(T))
33 return AT->getElementType().isConstant(Ctx);
40 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
42 const llvm::APInt &NumElements) {
43 llvm::APSInt SizeExtended(NumElements, true);
44 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
45 SizeExtended.extend(std::max(SizeTypeBits, SizeExtended.getBitWidth()) * 2);
48 = Context.getTypeSizeInChars(ElementType).getQuantity();
49 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
50 TotalSize *= SizeExtended;
52 return TotalSize.getActiveBits();
55 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
56 unsigned Bits = Context.getTypeSize(Context.getSizeType());
58 // GCC appears to only allow 63 bits worth of address space when compiling
59 // for 64-bit, so we do the same.
66 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
69 ArraySizeModifier SizeMod,
72 ID.AddPointer(ET.getAsOpaquePtr());
73 ID.AddInteger(SizeMod);
74 ID.AddInteger(TypeQuals);
75 E->Profile(ID, Context, true);
79 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
81 QualType ElementType, Expr *SizeExpr) {
82 ID.AddPointer(ElementType.getAsOpaquePtr());
83 SizeExpr->Profile(ID, Context, true);
86 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
87 /// element type of the array, potentially with type qualifiers missing.
88 /// This method should never be used when type qualifiers are meaningful.
89 const Type *Type::getArrayElementTypeNoTypeQual() const {
90 // If this is directly an array type, return it.
91 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
92 return ATy->getElementType().getTypePtr();
94 // If the canonical form of this type isn't the right kind, reject it.
95 if (!isa<ArrayType>(CanonicalType))
98 // If this is a typedef for an array type, strip the typedef off without
99 // losing all typedef information.
100 return cast<ArrayType>(getUnqualifiedDesugaredType())
101 ->getElementType().getTypePtr();
104 /// \brief Retrieve the unqualified variant of the given type, removing as
105 /// little sugar as possible.
107 /// This routine looks through various kinds of sugar to find the
108 /// least-desuraged type that is unqualified. For example, given:
111 /// typedef int Integer;
112 /// typedef const Integer CInteger;
113 /// typedef CInteger DifferenceType;
116 /// Executing \c getUnqualifiedTypeSlow() on the type \c DifferenceType will
117 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
118 QualType QualType::getUnqualifiedTypeSlow() const {
119 QualType Cur = *this;
121 if (!Cur.hasQualifiers())
124 const Type *CurTy = Cur.getTypePtr();
125 switch (CurTy->getTypeClass()) {
126 #define ABSTRACT_TYPE(Class, Parent)
127 #define TYPE(Class, Parent) \
128 case Type::Class: { \
129 const Class##Type *Ty = cast<Class##Type>(CurTy); \
130 if (!Ty->isSugared()) \
131 return Cur.getLocalUnqualifiedType(); \
132 Cur = Ty->desugar(); \
135 #include "clang/AST/TypeNodes.def"
139 return Cur.getUnqualifiedType();
142 /// getDesugaredType - Return the specified type with any "sugar" removed from
143 /// the type. This takes off typedefs, typeof's etc. If the outer level of
144 /// the type is already concrete, it returns it unmodified. This is similar
145 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
146 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
148 QualType QualType::getDesugaredType(QualType T) {
149 QualifierCollector Qs;
153 const Type *CurTy = Qs.strip(Cur);
154 switch (CurTy->getTypeClass()) {
155 #define ABSTRACT_TYPE(Class, Parent)
156 #define TYPE(Class, Parent) \
157 case Type::Class: { \
158 const Class##Type *Ty = cast<Class##Type>(CurTy); \
159 if (!Ty->isSugared()) \
160 return Qs.apply(Cur); \
161 Cur = Ty->desugar(); \
164 #include "clang/AST/TypeNodes.def"
169 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
170 /// sugar off the given type. This should produce an object of the
171 /// same dynamic type as the canonical type.
172 const Type *Type::getUnqualifiedDesugaredType() const {
173 const Type *Cur = this;
176 switch (Cur->getTypeClass()) {
177 #define ABSTRACT_TYPE(Class, Parent)
178 #define TYPE(Class, Parent) \
180 const Class##Type *Ty = cast<Class##Type>(Cur); \
181 if (!Ty->isSugared()) return Cur; \
182 Cur = Ty->desugar().getTypePtr(); \
185 #include "clang/AST/TypeNodes.def"
190 /// isVoidType - Helper method to determine if this is the 'void' type.
191 bool Type::isVoidType() const {
192 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
193 return BT->getKind() == BuiltinType::Void;
197 bool Type::isDerivedType() const {
198 switch (CanonicalType->getTypeClass()) {
202 case IncompleteArray:
204 case FunctionNoProto:
205 case LValueReference:
206 case RValueReference:
214 bool Type::isClassType() const {
215 if (const RecordType *RT = getAs<RecordType>())
216 return RT->getDecl()->isClass();
219 bool Type::isStructureType() const {
220 if (const RecordType *RT = getAs<RecordType>())
221 return RT->getDecl()->isStruct();
224 bool Type::isStructureOrClassType() const {
225 if (const RecordType *RT = getAs<RecordType>())
226 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
229 bool Type::isVoidPointerType() const {
230 if (const PointerType *PT = getAs<PointerType>())
231 return PT->getPointeeType()->isVoidType();
235 bool Type::isUnionType() const {
236 if (const RecordType *RT = getAs<RecordType>())
237 return RT->getDecl()->isUnion();
241 bool Type::isComplexType() const {
242 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
243 return CT->getElementType()->isFloatingType();
247 bool Type::isComplexIntegerType() const {
248 // Check for GCC complex integer extension.
249 return getAsComplexIntegerType();
252 const ComplexType *Type::getAsComplexIntegerType() const {
253 if (const ComplexType *Complex = getAs<ComplexType>())
254 if (Complex->getElementType()->isIntegerType())
259 QualType Type::getPointeeType() const {
260 if (const PointerType *PT = getAs<PointerType>())
261 return PT->getPointeeType();
262 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
263 return OPT->getPointeeType();
264 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
265 return BPT->getPointeeType();
266 if (const ReferenceType *RT = getAs<ReferenceType>())
267 return RT->getPointeeType();
271 /// isVariablyModifiedType (C99 6.7.5p3) - Return true for variable length
272 /// array types and types that contain variable array types in their
274 bool Type::isVariablyModifiedType() const {
275 // FIXME: We should really keep a "variably modified" bit in Type, rather
276 // than walking the type hierarchy to recompute it.
278 // A VLA is a variably modified type.
279 if (isVariableArrayType())
282 // An array can contain a variably modified type
283 if (const Type *T = getArrayElementTypeNoTypeQual())
284 return T->isVariablyModifiedType();
286 // A pointer can point to a variably modified type.
287 // Also, C++ references and member pointers can point to a variably modified
288 // type, where VLAs appear as an extension to C++, and should be treated
290 if (const PointerType *PT = getAs<PointerType>())
291 return PT->getPointeeType()->isVariablyModifiedType();
292 if (const ReferenceType *RT = getAs<ReferenceType>())
293 return RT->getPointeeType()->isVariablyModifiedType();
294 if (const MemberPointerType *PT = getAs<MemberPointerType>())
295 return PT->getPointeeType()->isVariablyModifiedType();
297 // A function can return a variably modified type
298 // This one isn't completely obvious, but it follows from the
299 // definition in C99 6.7.5p3. Because of this rule, it's
300 // illegal to declare a function returning a variably modified type.
301 if (const FunctionType *FT = getAs<FunctionType>())
302 return FT->getResultType()->isVariablyModifiedType();
307 const RecordType *Type::getAsStructureType() const {
308 // If this is directly a structure type, return it.
309 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
310 if (RT->getDecl()->isStruct())
314 // If the canonical form of this type isn't the right kind, reject it.
315 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
316 if (!RT->getDecl()->isStruct())
319 // If this is a typedef for a structure type, strip the typedef off without
320 // losing all typedef information.
321 return cast<RecordType>(getUnqualifiedDesugaredType());
326 const RecordType *Type::getAsUnionType() const {
327 // If this is directly a union type, return it.
328 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
329 if (RT->getDecl()->isUnion())
333 // If the canonical form of this type isn't the right kind, reject it.
334 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
335 if (!RT->getDecl()->isUnion())
338 // If this is a typedef for a union type, strip the typedef off without
339 // losing all typedef information.
340 return cast<RecordType>(getUnqualifiedDesugaredType());
346 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
347 ObjCProtocolDecl * const *Protocols,
348 unsigned NumProtocols)
349 : Type(ObjCObject, Canonical, false),
350 NumProtocols(NumProtocols),
352 assert(this->NumProtocols == NumProtocols &&
353 "bitfield overflow in protocol count");
355 memcpy(getProtocolStorage(), Protocols,
356 NumProtocols * sizeof(ObjCProtocolDecl*));
359 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
360 // There is no sugar for ObjCObjectType's, just return the canonical
361 // type pointer if it is the right class. There is no typedef information to
362 // return and these cannot be Address-space qualified.
363 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
364 if (T->getNumProtocols() && T->getInterface())
369 bool Type::isObjCQualifiedInterfaceType() const {
370 return getAsObjCQualifiedInterfaceType() != 0;
373 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
374 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
375 // type pointer if it is the right class.
376 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
377 if (OPT->isObjCQualifiedIdType())
383 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
384 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
385 if (OPT->getInterfaceType())
391 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
392 if (const PointerType *PT = getAs<PointerType>())
393 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
394 return dyn_cast<CXXRecordDecl>(RT->getDecl());
398 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
399 if (const RecordType *RT = getAs<RecordType>())
400 return dyn_cast<CXXRecordDecl>(RT->getDecl());
401 else if (const InjectedClassNameType *Injected
402 = getAs<InjectedClassNameType>())
403 return Injected->getDecl();
408 bool Type::isIntegerType() const {
409 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
410 return BT->getKind() >= BuiltinType::Bool &&
411 BT->getKind() <= BuiltinType::Int128;
412 if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
413 // Incomplete enum types are not treated as integer types.
414 // FIXME: In C++, enum types are never integer types.
415 if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
420 bool Type::hasIntegerRepresentation() const {
421 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
422 return VT->getElementType()->isIntegerType();
424 return isIntegerType();
427 /// \brief Determine whether this type is an integral type.
429 /// This routine determines whether the given type is an integral type per
430 /// C++ [basic.fundamental]p7. Although the C standard does not define the
431 /// term "integral type", it has a similar term "integer type", and in C++
432 /// the two terms are equivalent. However, C's "integer type" includes
433 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
434 /// parameter is used to determine whether we should be following the C or
435 /// C++ rules when determining whether this type is an integral/integer type.
437 /// For cases where C permits "an integer type" and C++ permits "an integral
438 /// type", use this routine.
440 /// For cases where C permits "an integer type" and C++ permits "an integral
441 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
443 /// \param Ctx The context in which this type occurs.
445 /// \returns true if the type is considered an integral type, false otherwise.
446 bool Type::isIntegralType(ASTContext &Ctx) const {
447 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
448 return BT->getKind() >= BuiltinType::Bool &&
449 BT->getKind() <= BuiltinType::Int128;
451 if (!Ctx.getLangOptions().CPlusPlus)
452 if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
453 if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
454 return true; // Complete enum types are integral in C.
459 bool Type::isIntegralOrEnumerationType() const {
460 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
461 return BT->getKind() >= BuiltinType::Bool &&
462 BT->getKind() <= BuiltinType::Int128;
464 // Check for a complete enum type; incomplete enum types are not properly an
465 // enumeration type in the sense required here.
466 if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
467 if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
473 bool Type::isEnumeralType() const {
474 if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
475 return TT->getDecl()->isEnum();
479 bool Type::isBooleanType() const {
480 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
481 return BT->getKind() == BuiltinType::Bool;
485 bool Type::isCharType() const {
486 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
487 return BT->getKind() == BuiltinType::Char_U ||
488 BT->getKind() == BuiltinType::UChar ||
489 BT->getKind() == BuiltinType::Char_S ||
490 BT->getKind() == BuiltinType::SChar;
494 bool Type::isWideCharType() const {
495 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
496 return BT->getKind() == BuiltinType::WChar;
500 /// \brief Determine whether this type is any of the built-in character
502 bool Type::isAnyCharacterType() const {
503 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
504 return (BT->getKind() >= BuiltinType::Char_U &&
505 BT->getKind() <= BuiltinType::Char32) ||
506 (BT->getKind() >= BuiltinType::Char_S &&
507 BT->getKind() <= BuiltinType::WChar);
512 /// isSignedIntegerType - Return true if this is an integer type that is
513 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
514 /// an enum decl which has a signed representation
515 bool Type::isSignedIntegerType() const {
516 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
517 return BT->getKind() >= BuiltinType::Char_S &&
518 BT->getKind() <= BuiltinType::Int128;
521 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
522 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
527 bool Type::hasSignedIntegerRepresentation() const {
528 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
529 return VT->getElementType()->isSignedIntegerType();
531 return isSignedIntegerType();
534 /// isUnsignedIntegerType - Return true if this is an integer type that is
535 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
536 /// decl which has an unsigned representation
537 bool Type::isUnsignedIntegerType() const {
538 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
539 return BT->getKind() >= BuiltinType::Bool &&
540 BT->getKind() <= BuiltinType::UInt128;
543 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
544 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
549 bool Type::hasUnsignedIntegerRepresentation() const {
550 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
551 return VT->getElementType()->isUnsignedIntegerType();
553 return isUnsignedIntegerType();
556 bool Type::isFloatingType() const {
557 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
558 return BT->getKind() >= BuiltinType::Float &&
559 BT->getKind() <= BuiltinType::LongDouble;
560 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
561 return CT->getElementType()->isFloatingType();
565 bool Type::hasFloatingRepresentation() const {
566 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
567 return VT->getElementType()->isFloatingType();
569 return isFloatingType();
572 bool Type::isRealFloatingType() const {
573 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
574 return BT->isFloatingPoint();
578 bool Type::isRealType() const {
579 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
580 return BT->getKind() >= BuiltinType::Bool &&
581 BT->getKind() <= BuiltinType::LongDouble;
582 if (const TagType *TT = dyn_cast<TagType>(CanonicalType))
583 return TT->getDecl()->isEnum() && TT->getDecl()->isDefinition();
587 bool Type::isArithmeticType() const {
588 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
589 return BT->getKind() >= BuiltinType::Bool &&
590 BT->getKind() <= BuiltinType::LongDouble;
591 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
592 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
593 // If a body isn't seen by the time we get here, return false.
594 return ET->getDecl()->isDefinition();
595 return isa<ComplexType>(CanonicalType);
598 bool Type::isScalarType() const {
599 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
600 return BT->getKind() != BuiltinType::Void;
601 if (const TagType *TT = dyn_cast<TagType>(CanonicalType)) {
602 // Enums are scalar types, but only if they are defined. Incomplete enums
603 // are not treated as scalar types.
604 if (TT->getDecl()->isEnum() && TT->getDecl()->isDefinition())
608 return isa<PointerType>(CanonicalType) ||
609 isa<BlockPointerType>(CanonicalType) ||
610 isa<MemberPointerType>(CanonicalType) ||
611 isa<ComplexType>(CanonicalType) ||
612 isa<ObjCObjectPointerType>(CanonicalType);
615 /// \brief Determines whether the type is a C++ aggregate type or C
616 /// aggregate or union type.
618 /// An aggregate type is an array or a class type (struct, union, or
619 /// class) that has no user-declared constructors, no private or
620 /// protected non-static data members, no base classes, and no virtual
621 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
622 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
623 /// includes union types.
624 bool Type::isAggregateType() const {
625 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
626 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
627 return ClassDecl->isAggregate();
632 return isa<ArrayType>(CanonicalType);
635 /// isConstantSizeType - Return true if this is not a variable sized type,
636 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
637 /// incomplete types or dependent types.
638 bool Type::isConstantSizeType() const {
639 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
640 assert(!isDependentType() && "This doesn't make sense for dependent types");
641 // The VAT must have a size, as it is known to be complete.
642 return !isa<VariableArrayType>(CanonicalType);
645 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
646 /// - a type that can describe objects, but which lacks information needed to
647 /// determine its size.
648 bool Type::isIncompleteType() const {
649 switch (CanonicalType->getTypeClass()) {
650 default: return false;
652 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
657 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
658 // forward declaration, but not a full definition (C99 6.2.5p22).
659 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
661 // An array is incomplete if its element type is incomplete
662 // (C++ [dcl.array]p1).
663 // We don't handle variable arrays (they're not allowed in C++) or
664 // dependent-sized arrays (dependent types are never treated as incomplete).
665 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
666 case IncompleteArray:
667 // An array of unknown size is an incomplete type (C99 6.2.5p22).
670 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
671 ->isIncompleteType();
673 // ObjC interfaces are incomplete if they are @class, not @interface.
674 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
678 /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
679 bool Type::isPODType() const {
680 // The compiler shouldn't query this for incomplete types, but the user might.
681 // We return false for that case.
682 if (isIncompleteType())
685 switch (CanonicalType->getTypeClass()) {
686 // Everything not explicitly mentioned is not POD.
687 default: return false;
690 // IncompleteArray is caught by isIncompleteType() above.
691 return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
699 case ObjCObjectPointer:
707 if (CXXRecordDecl *ClassDecl
708 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
709 return ClassDecl->isPOD();
711 // C struct/union is POD.
716 bool Type::isLiteralType() const {
717 if (isIncompleteType())
720 // C++0x [basic.types]p10:
721 // A type is a literal type if it is:
722 switch (CanonicalType->getTypeClass()) {
723 // We're whitelisting
724 default: return false;
733 case ObjCObjectPointer:
737 // -- a class type with ...
739 // FIXME: Do the tests
742 // -- an array of literal type
743 // Extension: variable arrays cannot be literal types, since they're
746 return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType();
750 bool Type::isPromotableIntegerType() const {
751 if (const BuiltinType *BT = getAs<BuiltinType>())
752 switch (BT->getKind()) {
753 case BuiltinType::Bool:
754 case BuiltinType::Char_S:
755 case BuiltinType::Char_U:
756 case BuiltinType::SChar:
757 case BuiltinType::UChar:
758 case BuiltinType::Short:
759 case BuiltinType::UShort:
765 // Enumerated types are promotable to their compatible integer types
766 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
767 if (const EnumType *ET = getAs<EnumType>()){
768 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull())
771 const BuiltinType *BT
772 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
773 return BT->getKind() == BuiltinType::Int
774 || BT->getKind() == BuiltinType::UInt;
780 bool Type::isNullPtrType() const {
781 if (const BuiltinType *BT = getAs<BuiltinType>())
782 return BT->getKind() == BuiltinType::NullPtr;
786 bool Type::isSpecifierType() const {
787 // Note that this intentionally does not use the canonical type.
788 switch (getTypeClass()) {
796 case TemplateTypeParm:
797 case SubstTemplateTypeParm:
798 case TemplateSpecialization:
801 case DependentTemplateSpecialization:
804 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
811 TypeWithKeyword::~TypeWithKeyword() {
814 ElaboratedTypeKeyword
815 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
817 default: return ETK_None;
818 case TST_typename: return ETK_Typename;
819 case TST_class: return ETK_Class;
820 case TST_struct: return ETK_Struct;
821 case TST_union: return ETK_Union;
822 case TST_enum: return ETK_Enum;
827 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
829 case TST_class: return TTK_Class;
830 case TST_struct: return TTK_Struct;
831 case TST_union: return TTK_Union;
832 case TST_enum: return TTK_Enum;
833 default: llvm_unreachable("Type specifier is not a tag type kind.");
837 ElaboratedTypeKeyword
838 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
840 case TTK_Class: return ETK_Class;
841 case TTK_Struct: return ETK_Struct;
842 case TTK_Union: return ETK_Union;
843 case TTK_Enum: return ETK_Enum;
845 llvm_unreachable("Unknown tag type kind.");
849 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
851 case ETK_Class: return TTK_Class;
852 case ETK_Struct: return TTK_Struct;
853 case ETK_Union: return TTK_Union;
854 case ETK_Enum: return TTK_Enum;
855 case ETK_None: // Fall through.
857 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
859 llvm_unreachable("Unknown elaborated type keyword.");
863 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
874 llvm_unreachable("Unknown elaborated type keyword.");
878 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
880 default: llvm_unreachable("Unknown elaborated type keyword.");
881 case ETK_None: return "";
882 case ETK_Typename: return "typename";
883 case ETK_Class: return "class";
884 case ETK_Struct: return "struct";
885 case ETK_Union: return "union";
886 case ETK_Enum: return "enum";
890 ElaboratedType::~ElaboratedType() {}
891 DependentNameType::~DependentNameType() {}
892 DependentTemplateSpecializationType::~DependentTemplateSpecializationType() {}
894 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
895 ElaboratedTypeKeyword Keyword,
896 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
897 unsigned NumArgs, const TemplateArgument *Args,
899 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true),
900 NNS(NNS), Name(Name), NumArgs(NumArgs) {
901 assert(NNS && NNS->isDependent() &&
902 "DependentTemplateSpecializatonType requires dependent qualifier");
903 for (unsigned I = 0; I != NumArgs; ++I)
904 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
908 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
910 ElaboratedTypeKeyword Keyword,
911 NestedNameSpecifier *Qualifier,
912 const IdentifierInfo *Name,
914 const TemplateArgument *Args) {
915 ID.AddInteger(Keyword);
916 ID.AddPointer(Qualifier);
918 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
919 Args[Idx].Profile(ID, Context);
922 bool Type::isElaboratedTypeSpecifier() const {
923 ElaboratedTypeKeyword Keyword;
924 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
925 Keyword = Elab->getKeyword();
926 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
927 Keyword = DepName->getKeyword();
928 else if (const DependentTemplateSpecializationType *DepTST =
929 dyn_cast<DependentTemplateSpecializationType>(this))
930 Keyword = DepTST->getKeyword();
934 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
937 const char *Type::getTypeClassName() const {
939 default: assert(0 && "Type class not in TypeNodes.def!");
940 #define ABSTRACT_TYPE(Derived, Base)
941 #define TYPE(Derived, Base) case Derived: return #Derived;
942 #include "clang/AST/TypeNodes.def"
946 const char *BuiltinType::getName(const LangOptions &LO) const {
948 default: assert(0 && "Unknown builtin type!");
949 case Void: return "void";
950 case Bool: return LO.Bool ? "bool" : "_Bool";
951 case Char_S: return "char";
952 case Char_U: return "char";
953 case SChar: return "signed char";
954 case Short: return "short";
955 case Int: return "int";
956 case Long: return "long";
957 case LongLong: return "long long";
958 case Int128: return "__int128_t";
959 case UChar: return "unsigned char";
960 case UShort: return "unsigned short";
961 case UInt: return "unsigned int";
962 case ULong: return "unsigned long";
963 case ULongLong: return "unsigned long long";
964 case UInt128: return "__uint128_t";
965 case Float: return "float";
966 case Double: return "double";
967 case LongDouble: return "long double";
968 case WChar: return "wchar_t";
969 case Char16: return "char16_t";
970 case Char32: return "char32_t";
971 case NullPtr: return "nullptr_t";
972 case Overload: return "<overloaded function type>";
973 case Dependent: return "<dependent type>";
974 case UndeducedAuto: return "auto";
975 case ObjCId: return "id";
976 case ObjCClass: return "Class";
977 case ObjCSel: return "SEL";
981 void FunctionType::ANCHOR() {} // Key function for FunctionType.
983 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
984 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
985 return RefType->getPointeeType();
987 // C++0x [basic.lval]:
988 // Class prvalues can have cv-qualified types; non-class prvalues always
989 // have cv-unqualified types.
991 // See also C99 6.3.2.1p2.
992 if (!Context.getLangOptions().CPlusPlus ||
993 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
994 return getUnqualifiedType();
999 llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1001 case CC_Default: llvm_unreachable("no name for default cc");
1004 case CC_C: return "cdecl";
1005 case CC_X86StdCall: return "stdcall";
1006 case CC_X86FastCall: return "fastcall";
1007 case CC_X86ThisCall: return "thiscall";
1008 case CC_X86Pascal: return "pascal";
1012 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1013 arg_type_iterator ArgTys,
1014 unsigned NumArgs, bool isVariadic,
1015 unsigned TypeQuals, bool hasExceptionSpec,
1016 bool anyExceptionSpec, unsigned NumExceptions,
1017 exception_iterator Exs,
1018 const FunctionType::ExtInfo &Info) {
1019 ID.AddPointer(Result.getAsOpaquePtr());
1020 for (unsigned i = 0; i != NumArgs; ++i)
1021 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1022 ID.AddInteger(isVariadic);
1023 ID.AddInteger(TypeQuals);
1024 ID.AddInteger(hasExceptionSpec);
1025 if (hasExceptionSpec) {
1026 ID.AddInteger(anyExceptionSpec);
1027 for (unsigned i = 0; i != NumExceptions; ++i)
1028 ID.AddPointer(Exs[i].getAsOpaquePtr());
1030 ID.AddInteger(Info.getNoReturn());
1031 ID.AddInteger(Info.getRegParm());
1032 ID.AddInteger(Info.getCC());
1035 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
1036 Profile(ID, getResultType(), arg_type_begin(), NumArgs, isVariadic(),
1037 getTypeQuals(), hasExceptionSpec(), hasAnyExceptionSpec(),
1038 getNumExceptions(), exception_begin(),
1042 /// LookThroughTypedefs - Return the ultimate type this typedef corresponds to
1043 /// potentially looking through *all* consequtive typedefs. This returns the
1044 /// sum of the type qualifiers, so if you have:
1045 /// typedef const int A;
1046 /// typedef volatile A B;
1047 /// looking through the typedefs for B will give you "const volatile A".
1049 QualType TypedefType::LookThroughTypedefs() const {
1050 // Usually, there is only a single level of typedefs, be fast in that case.
1051 QualType FirstType = getDecl()->getUnderlyingType();
1052 if (!isa<TypedefType>(FirstType))
1055 // Otherwise, do the fully general loop.
1056 QualifierCollector Qs;
1059 const TypedefType *TDT = this;
1061 CurType = TDT->getDecl()->getUnderlyingType();
1062 TDT = dyn_cast<TypedefType>(Qs.strip(CurType));
1065 return Qs.apply(CurType);
1068 QualType TypedefType::desugar() const {
1069 return getDecl()->getUnderlyingType();
1072 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1073 : Type(TypeOfExpr, can, E->isTypeDependent()), TOExpr(E) {
1076 QualType TypeOfExprType::desugar() const {
1077 return getUnderlyingExpr()->getType();
1080 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1081 ASTContext &Context, Expr *E) {
1082 E->Profile(ID, Context, true);
1085 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1086 : Type(Decltype, can, E->isTypeDependent()), E(E),
1087 UnderlyingType(underlyingType) {
1090 DependentDecltypeType::DependentDecltypeType(ASTContext &Context, Expr *E)
1091 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1093 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1094 ASTContext &Context, Expr *E) {
1095 E->Profile(ID, Context, true);
1098 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1099 : Type(TC, can, D->isDependentType()),
1100 decl(const_cast<TagDecl*>(D)) {}
1102 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1103 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1104 E = decl->redecls_end();
1106 if (I->isDefinition() || I->isBeingDefined())
1109 // If there's no definition (not even in progress), return what we have.
1113 TagDecl *TagType::getDecl() const {
1114 return getInterestingTagDecl(decl);
1117 bool TagType::isBeingDefined() const {
1118 return getDecl()->isBeingDefined();
1121 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1122 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1125 bool RecordType::classof(const TagType *TT) {
1126 return isa<RecordDecl>(TT->getDecl());
1129 bool EnumType::classof(const TagType *TT) {
1130 return isa<EnumDecl>(TT->getDecl());
1133 static bool isDependent(const TemplateArgument &Arg) {
1134 switch (Arg.getKind()) {
1135 case TemplateArgument::Null:
1136 assert(false && "Should not have a NULL template argument");
1139 case TemplateArgument::Type:
1140 return Arg.getAsType()->isDependentType();
1142 case TemplateArgument::Template:
1143 return Arg.getAsTemplate().isDependent();
1145 case TemplateArgument::Declaration:
1146 if (DeclContext *DC = dyn_cast<DeclContext>(Arg.getAsDecl()))
1147 return DC->isDependentContext();
1148 return Arg.getAsDecl()->getDeclContext()->isDependentContext();
1150 case TemplateArgument::Integral:
1154 case TemplateArgument::Expression:
1155 return (Arg.getAsExpr()->isTypeDependent() ||
1156 Arg.getAsExpr()->isValueDependent());
1158 case TemplateArgument::Pack:
1159 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1160 PEnd = Arg.pack_end();
1162 if (isDependent(*P))
1172 bool TemplateSpecializationType::
1173 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1174 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1177 bool TemplateSpecializationType::
1178 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1179 for (unsigned i = 0; i != N; ++i)
1180 if (isDependent(Args[i].getArgument()))
1185 bool TemplateSpecializationType::
1186 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1187 for (unsigned i = 0; i != N; ++i)
1188 if (isDependent(Args[i]))
1193 TemplateSpecializationType::
1194 TemplateSpecializationType(TemplateName T,
1195 const TemplateArgument *Args,
1196 unsigned NumArgs, QualType Canon)
1197 : Type(TemplateSpecialization,
1198 Canon.isNull()? QualType(this, 0) : Canon,
1199 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)),
1200 Template(T), NumArgs(NumArgs) {
1201 assert((!Canon.isNull() ||
1202 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1203 "No canonical type for non-dependent class template specialization");
1205 TemplateArgument *TemplateArgs
1206 = reinterpret_cast<TemplateArgument *>(this + 1);
1207 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
1208 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1212 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1214 const TemplateArgument *Args,
1216 ASTContext &Context) {
1218 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1219 Args[Idx].Profile(ID, Context);
1222 QualType QualifierCollector::apply(QualType QT) const {
1223 if (!hasNonFastQualifiers())
1224 return QT.withFastQualifiers(getFastQualifiers());
1226 assert(Context && "extended qualifiers but no context!");
1227 return Context->getQualifiedType(QT, *this);
1230 QualType QualifierCollector::apply(const Type *T) const {
1231 if (!hasNonFastQualifiers())
1232 return QualType(T, getFastQualifiers());
1234 assert(Context && "extended qualifiers but no context!");
1235 return Context->getQualifiedType(T, *this);
1238 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1240 ObjCProtocolDecl * const *Protocols,
1241 unsigned NumProtocols) {
1242 ID.AddPointer(BaseType.getAsOpaquePtr());
1243 for (unsigned i = 0; i != NumProtocols; i++)
1244 ID.AddPointer(Protocols[i]);
1247 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1248 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1251 /// \brief Determine the linkage of this type.
1252 Linkage Type::getLinkage() const {
1253 if (this != CanonicalType.getTypePtr())
1254 return CanonicalType->getLinkage();
1256 if (!LinkageKnown) {
1257 CachedLinkage = getLinkageImpl();
1258 LinkageKnown = true;
1261 return static_cast<clang::Linkage>(CachedLinkage);
1264 Linkage Type::getLinkageImpl() const {
1265 // C++ [basic.link]p8:
1266 // Names not covered by these rules have no linkage.
1270 void Type::ClearLinkageCache() {
1271 if (this != CanonicalType.getTypePtr())
1272 CanonicalType->ClearLinkageCache();
1274 LinkageKnown = false;
1277 Linkage BuiltinType::getLinkageImpl() const {
1278 // C++ [basic.link]p8:
1279 // A type is said to have linkage if and only if:
1280 // - it is a fundamental type (3.9.1); or
1281 return ExternalLinkage;
1284 Linkage TagType::getLinkageImpl() const {
1285 // C++ [basic.link]p8:
1286 // - it is a class or enumeration type that is named (or has a name for
1287 // linkage purposes (7.1.3)) and the name has linkage; or
1288 // - it is a specialization of a class template (14); or
1289 return getDecl()->getLinkage();
1292 // C++ [basic.link]p8:
1293 // - it is a compound type (3.9.2) other than a class or enumeration,
1294 // compounded exclusively from types that have linkage; or
1295 Linkage ComplexType::getLinkageImpl() const {
1296 return ElementType->getLinkage();
1299 Linkage PointerType::getLinkageImpl() const {
1300 return PointeeType->getLinkage();
1303 Linkage BlockPointerType::getLinkageImpl() const {
1304 return PointeeType->getLinkage();
1307 Linkage ReferenceType::getLinkageImpl() const {
1308 return PointeeType->getLinkage();
1311 Linkage MemberPointerType::getLinkageImpl() const {
1312 return minLinkage(Class->getLinkage(), PointeeType->getLinkage());
1315 Linkage ArrayType::getLinkageImpl() const {
1316 return ElementType->getLinkage();
1319 Linkage VectorType::getLinkageImpl() const {
1320 return ElementType->getLinkage();
1323 Linkage FunctionNoProtoType::getLinkageImpl() const {
1324 return getResultType()->getLinkage();
1327 Linkage FunctionProtoType::getLinkageImpl() const {
1328 Linkage L = getResultType()->getLinkage();
1329 for (arg_type_iterator A = arg_type_begin(), AEnd = arg_type_end();
1331 L = minLinkage(L, (*A)->getLinkage());
1336 Linkage ObjCObjectType::getLinkageImpl() const {
1337 return ExternalLinkage;
1340 Linkage ObjCObjectPointerType::getLinkageImpl() const {
1341 return ExternalLinkage;