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/Attr.h"
16 #include "clang/AST/CharUnits.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/AST/Type.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
32 return (*this != Other) &&
33 // CVR qualifiers superset
34 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
35 // ObjC GC qualifiers superset
36 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
37 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
38 // Address space superset.
39 ((getAddressSpace() == Other.getAddressSpace()) ||
40 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
41 // Lifetime qualifier superset.
42 ((getObjCLifetime() == Other.getObjCLifetime()) ||
43 (hasObjCLifetime() && !Other.hasObjCLifetime()));
46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
47 const Type* ty = getTypePtr();
49 if (ty->isPointerType() || ty->isReferenceType())
50 return ty->getPointeeType().getBaseTypeIdentifier();
51 else if (ty->isRecordType())
52 ND = ty->getAs<RecordType>()->getDecl();
53 else if (ty->isEnumeralType())
54 ND = ty->getAs<EnumType>()->getDecl();
55 else if (ty->getTypeClass() == Type::Typedef)
56 ND = ty->getAs<TypedefType>()->getDecl();
57 else if (ty->isArrayType())
58 return ty->castAsArrayTypeUnsafe()->
59 getElementType().getBaseTypeIdentifier();
62 return ND->getIdentifier();
66 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
67 if (T.isConstQualified())
70 if (const ArrayType *AT = Ctx.getAsArrayType(T))
71 return AT->getElementType().isConstant(Ctx);
76 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
78 const llvm::APInt &NumElements) {
79 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
81 // Fast path the common cases so we can avoid the conservative computation
82 // below, which in common cases allocates "large" APSInt values, which are
85 // If the element size is a power of 2, we can directly compute the additional
86 // number of addressing bits beyond those required for the element count.
87 if (llvm::isPowerOf2_64(ElementSize)) {
88 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
91 // If both the element count and element size fit in 32-bits, we can do the
92 // computation directly in 64-bits.
93 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
94 (NumElements.getZExtValue() >> 32) == 0) {
95 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
96 return 64 - llvm::countLeadingZeros(TotalSize);
99 // Otherwise, use APSInt to handle arbitrary sized values.
100 llvm::APSInt SizeExtended(NumElements, true);
101 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
102 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
103 SizeExtended.getBitWidth()) * 2);
105 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
106 TotalSize *= SizeExtended;
108 return TotalSize.getActiveBits();
111 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
112 unsigned Bits = Context.getTypeSize(Context.getSizeType());
114 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
115 // integer (see PR8256). We can do this as currently there is no hardware
116 // that supports full 64-bit virtual space.
123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
124 QualType et, QualType can,
125 Expr *e, ArraySizeModifier sm,
127 SourceRange brackets)
128 : ArrayType(DependentSizedArray, et, can, sm, tq,
129 (et->containsUnexpandedParameterPack() ||
130 (e && e->containsUnexpandedParameterPack()))),
131 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
136 const ASTContext &Context,
138 ArraySizeModifier SizeMod,
141 ID.AddPointer(ET.getAsOpaquePtr());
142 ID.AddInteger(SizeMod);
143 ID.AddInteger(TypeQuals);
144 E->Profile(ID, Context, true);
147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
149 QualType ElementType,
153 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
154 /*InstantiationDependent=*/true,
155 ElementType->isVariablyModifiedType(),
156 (ElementType->containsUnexpandedParameterPack() ||
157 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
158 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
165 const ASTContext &Context,
166 QualType ElementType, Expr *SizeExpr) {
167 ID.AddPointer(ElementType.getAsOpaquePtr());
168 SizeExpr->Profile(ID, Context, true);
171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
173 : Type(Vector, canonType, vecType->isDependentType(),
174 vecType->isInstantiationDependentType(),
175 vecType->isVariablyModifiedType(),
176 vecType->containsUnexpandedParameterPack()),
179 VectorTypeBits.VecKind = vecKind;
180 VectorTypeBits.NumElements = nElements;
183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
184 QualType canonType, VectorKind vecKind)
185 : Type(tc, canonType, vecType->isDependentType(),
186 vecType->isInstantiationDependentType(),
187 vecType->isVariablyModifiedType(),
188 vecType->containsUnexpandedParameterPack()),
191 VectorTypeBits.VecKind = vecKind;
192 VectorTypeBits.NumElements = nElements;
195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
196 /// element type of the array, potentially with type qualifiers missing.
197 /// This method should never be used when type qualifiers are meaningful.
198 const Type *Type::getArrayElementTypeNoTypeQual() const {
199 // If this is directly an array type, return it.
200 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
201 return ATy->getElementType().getTypePtr();
203 // If the canonical form of this type isn't the right kind, reject it.
204 if (!isa<ArrayType>(CanonicalType))
207 // If this is a typedef for an array type, strip the typedef off without
208 // losing all typedef information.
209 return cast<ArrayType>(getUnqualifiedDesugaredType())
210 ->getElementType().getTypePtr();
213 /// getDesugaredType - Return the specified type with any "sugar" removed from
214 /// the type. This takes off typedefs, typeof's etc. If the outer level of
215 /// the type is already concrete, it returns it unmodified. This is similar
216 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
220 SplitQualType split = getSplitDesugaredType(T);
221 return Context.getQualifiedType(split.Ty, split.Quals);
224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
225 const ASTContext &Context) {
226 SplitQualType split = type.split();
227 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
228 return Context.getQualifiedType(desugar, split.Quals);
231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
232 switch (getTypeClass()) {
233 #define ABSTRACT_TYPE(Class, Parent)
234 #define TYPE(Class, Parent) \
235 case Type::Class: { \
236 const Class##Type *ty = cast<Class##Type>(this); \
237 if (!ty->isSugared()) return QualType(ty, 0); \
238 return ty->desugar(); \
240 #include "clang/AST/TypeNodes.def"
242 llvm_unreachable("bad type kind!");
245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
246 QualifierCollector Qs;
250 const Type *CurTy = Qs.strip(Cur);
251 switch (CurTy->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
254 case Type::Class: { \
255 const Class##Type *Ty = cast<Class##Type>(CurTy); \
256 if (!Ty->isSugared()) \
257 return SplitQualType(Ty, Qs); \
258 Cur = Ty->desugar(); \
261 #include "clang/AST/TypeNodes.def"
266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
267 SplitQualType split = type.split();
269 // All the qualifiers we've seen so far.
270 Qualifiers quals = split.Quals;
272 // The last type node we saw with any nodes inside it.
273 const Type *lastTypeWithQuals = split.Ty;
278 // Do a single-step desugar, aborting the loop if the type isn't
280 switch (split.Ty->getTypeClass()) {
281 #define ABSTRACT_TYPE(Class, Parent)
282 #define TYPE(Class, Parent) \
283 case Type::Class: { \
284 const Class##Type *ty = cast<Class##Type>(split.Ty); \
285 if (!ty->isSugared()) goto done; \
286 next = ty->desugar(); \
289 #include "clang/AST/TypeNodes.def"
292 // Otherwise, split the underlying type. If that yields qualifiers,
293 // update the information.
294 split = next.split();
295 if (!split.Quals.empty()) {
296 lastTypeWithQuals = split.Ty;
297 quals.addConsistentQualifiers(split.Quals);
302 return SplitQualType(lastTypeWithQuals, quals);
305 QualType QualType::IgnoreParens(QualType T) {
306 // FIXME: this seems inherently un-qualifiers-safe.
307 while (const ParenType *PT = T->getAs<ParenType>())
308 T = PT->getInnerType();
312 /// \brief This will check for a T (which should be a Type which can act as
313 /// sugar, such as a TypedefType) by removing any existing sugar until it
314 /// reaches a T or a non-sugared type.
315 template<typename T> static const T *getAsSugar(const Type *Cur) {
317 if (const T *Sugar = dyn_cast<T>(Cur))
319 switch (Cur->getTypeClass()) {
320 #define ABSTRACT_TYPE(Class, Parent)
321 #define TYPE(Class, Parent) \
322 case Type::Class: { \
323 const Class##Type *Ty = cast<Class##Type>(Cur); \
324 if (!Ty->isSugared()) return 0; \
325 Cur = Ty->desugar().getTypePtr(); \
328 #include "clang/AST/TypeNodes.def"
333 template <> const TypedefType *Type::getAs() const {
334 return getAsSugar<TypedefType>(this);
337 template <> const TemplateSpecializationType *Type::getAs() const {
338 return getAsSugar<TemplateSpecializationType>(this);
341 template <> const AttributedType *Type::getAs() const {
342 return getAsSugar<AttributedType>(this);
345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
346 /// sugar off the given type. This should produce an object of the
347 /// same dynamic type as the canonical type.
348 const Type *Type::getUnqualifiedDesugaredType() const {
349 const Type *Cur = this;
352 switch (Cur->getTypeClass()) {
353 #define ABSTRACT_TYPE(Class, Parent)
354 #define TYPE(Class, Parent) \
356 const Class##Type *Ty = cast<Class##Type>(Cur); \
357 if (!Ty->isSugared()) return Cur; \
358 Cur = Ty->desugar().getTypePtr(); \
361 #include "clang/AST/TypeNodes.def"
365 bool Type::isClassType() const {
366 if (const RecordType *RT = getAs<RecordType>())
367 return RT->getDecl()->isClass();
370 bool Type::isStructureType() const {
371 if (const RecordType *RT = getAs<RecordType>())
372 return RT->getDecl()->isStruct();
375 bool Type::isInterfaceType() const {
376 if (const RecordType *RT = getAs<RecordType>())
377 return RT->getDecl()->isInterface();
380 bool Type::isStructureOrClassType() const {
381 if (const RecordType *RT = getAs<RecordType>())
382 return RT->getDecl()->isStruct() || RT->getDecl()->isClass() ||
383 RT->getDecl()->isInterface();
386 bool Type::isVoidPointerType() const {
387 if (const PointerType *PT = getAs<PointerType>())
388 return PT->getPointeeType()->isVoidType();
392 bool Type::isUnionType() const {
393 if (const RecordType *RT = getAs<RecordType>())
394 return RT->getDecl()->isUnion();
398 bool Type::isComplexType() const {
399 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
400 return CT->getElementType()->isFloatingType();
404 bool Type::isComplexIntegerType() const {
405 // Check for GCC complex integer extension.
406 return getAsComplexIntegerType();
409 const ComplexType *Type::getAsComplexIntegerType() const {
410 if (const ComplexType *Complex = getAs<ComplexType>())
411 if (Complex->getElementType()->isIntegerType())
416 QualType Type::getPointeeType() const {
417 if (const PointerType *PT = getAs<PointerType>())
418 return PT->getPointeeType();
419 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
420 return OPT->getPointeeType();
421 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
422 return BPT->getPointeeType();
423 if (const ReferenceType *RT = getAs<ReferenceType>())
424 return RT->getPointeeType();
428 const RecordType *Type::getAsStructureType() const {
429 // If this is directly a structure type, return it.
430 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
431 if (RT->getDecl()->isStruct())
435 // If the canonical form of this type isn't the right kind, reject it.
436 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
437 if (!RT->getDecl()->isStruct())
440 // If this is a typedef for a structure type, strip the typedef off without
441 // losing all typedef information.
442 return cast<RecordType>(getUnqualifiedDesugaredType());
447 const RecordType *Type::getAsUnionType() const {
448 // If this is directly a union type, return it.
449 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
450 if (RT->getDecl()->isUnion())
454 // If the canonical form of this type isn't the right kind, reject it.
455 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
456 if (!RT->getDecl()->isUnion())
459 // If this is a typedef for a union type, strip the typedef off without
460 // losing all typedef information.
461 return cast<RecordType>(getUnqualifiedDesugaredType());
467 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
468 ObjCProtocolDecl * const *Protocols,
469 unsigned NumProtocols)
470 : Type(ObjCObject, Canonical, false, false, false, false),
473 ObjCObjectTypeBits.NumProtocols = NumProtocols;
474 assert(getNumProtocols() == NumProtocols &&
475 "bitfield overflow in protocol count");
477 memcpy(getProtocolStorage(), Protocols,
478 NumProtocols * sizeof(ObjCProtocolDecl*));
481 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
482 // There is no sugar for ObjCObjectType's, just return the canonical
483 // type pointer if it is the right class. There is no typedef information to
484 // return and these cannot be Address-space qualified.
485 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
486 if (T->getNumProtocols() && T->getInterface())
491 bool Type::isObjCQualifiedInterfaceType() const {
492 return getAsObjCQualifiedInterfaceType() != 0;
495 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
496 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
497 // type pointer if it is the right class.
498 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
499 if (OPT->isObjCQualifiedIdType())
505 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
506 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
507 // type pointer if it is the right class.
508 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
509 if (OPT->isObjCQualifiedClassType())
515 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
516 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
517 if (OPT->getInterfaceType())
523 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
524 QualType PointeeType;
525 if (const PointerType *PT = getAs<PointerType>())
526 PointeeType = PT->getPointeeType();
527 else if (const ReferenceType *RT = getAs<ReferenceType>())
528 PointeeType = RT->getPointeeType();
532 if (const RecordType *RT = PointeeType->getAs<RecordType>())
533 return dyn_cast<CXXRecordDecl>(RT->getDecl());
538 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
539 if (const RecordType *RT = getAs<RecordType>())
540 return dyn_cast<CXXRecordDecl>(RT->getDecl());
541 else if (const InjectedClassNameType *Injected
542 = getAs<InjectedClassNameType>())
543 return Injected->getDecl();
549 class GetContainedAutoVisitor :
550 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
552 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
553 AutoType *Visit(QualType T) {
556 return Visit(T.getTypePtr());
559 // The 'auto' type itself.
560 AutoType *VisitAutoType(const AutoType *AT) {
561 return const_cast<AutoType*>(AT);
564 // Only these types can contain the desired 'auto' type.
565 AutoType *VisitPointerType(const PointerType *T) {
566 return Visit(T->getPointeeType());
568 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
569 return Visit(T->getPointeeType());
571 AutoType *VisitReferenceType(const ReferenceType *T) {
572 return Visit(T->getPointeeTypeAsWritten());
574 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
575 return Visit(T->getPointeeType());
577 AutoType *VisitArrayType(const ArrayType *T) {
578 return Visit(T->getElementType());
580 AutoType *VisitDependentSizedExtVectorType(
581 const DependentSizedExtVectorType *T) {
582 return Visit(T->getElementType());
584 AutoType *VisitVectorType(const VectorType *T) {
585 return Visit(T->getElementType());
587 AutoType *VisitFunctionType(const FunctionType *T) {
588 return Visit(T->getResultType());
590 AutoType *VisitParenType(const ParenType *T) {
591 return Visit(T->getInnerType());
593 AutoType *VisitAttributedType(const AttributedType *T) {
594 return Visit(T->getModifiedType());
599 AutoType *Type::getContainedAutoType() const {
600 return GetContainedAutoVisitor().Visit(this);
603 bool Type::hasIntegerRepresentation() const {
604 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
605 return VT->getElementType()->isIntegerType();
607 return isIntegerType();
610 /// \brief Determine whether this type is an integral type.
612 /// This routine determines whether the given type is an integral type per
613 /// C++ [basic.fundamental]p7. Although the C standard does not define the
614 /// term "integral type", it has a similar term "integer type", and in C++
615 /// the two terms are equivalent. However, C's "integer type" includes
616 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
617 /// parameter is used to determine whether we should be following the C or
618 /// C++ rules when determining whether this type is an integral/integer type.
620 /// For cases where C permits "an integer type" and C++ permits "an integral
621 /// type", use this routine.
623 /// For cases where C permits "an integer type" and C++ permits "an integral
624 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
626 /// \param Ctx The context in which this type occurs.
628 /// \returns true if the type is considered an integral type, false otherwise.
629 bool Type::isIntegralType(ASTContext &Ctx) const {
630 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
631 return BT->getKind() >= BuiltinType::Bool &&
632 BT->getKind() <= BuiltinType::Int128;
634 if (!Ctx.getLangOpts().CPlusPlus)
635 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
636 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
642 bool Type::isIntegralOrUnscopedEnumerationType() const {
643 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
644 return BT->getKind() >= BuiltinType::Bool &&
645 BT->getKind() <= BuiltinType::Int128;
647 // Check for a complete enum type; incomplete enum types are not properly an
648 // enumeration type in the sense required here.
649 // C++0x: However, if the underlying type of the enum is fixed, it is
650 // considered complete.
651 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
652 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
659 bool Type::isCharType() const {
660 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
661 return BT->getKind() == BuiltinType::Char_U ||
662 BT->getKind() == BuiltinType::UChar ||
663 BT->getKind() == BuiltinType::Char_S ||
664 BT->getKind() == BuiltinType::SChar;
668 bool Type::isWideCharType() const {
669 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
670 return BT->getKind() == BuiltinType::WChar_S ||
671 BT->getKind() == BuiltinType::WChar_U;
675 bool Type::isChar16Type() const {
676 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
677 return BT->getKind() == BuiltinType::Char16;
681 bool Type::isChar32Type() const {
682 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
683 return BT->getKind() == BuiltinType::Char32;
687 /// \brief Determine whether this type is any of the built-in character
689 bool Type::isAnyCharacterType() const {
690 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
691 if (BT == 0) return false;
692 switch (BT->getKind()) {
693 default: return false;
694 case BuiltinType::Char_U:
695 case BuiltinType::UChar:
696 case BuiltinType::WChar_U:
697 case BuiltinType::Char16:
698 case BuiltinType::Char32:
699 case BuiltinType::Char_S:
700 case BuiltinType::SChar:
701 case BuiltinType::WChar_S:
706 /// isSignedIntegerType - Return true if this is an integer type that is
707 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
708 /// an enum decl which has a signed representation
709 bool Type::isSignedIntegerType() const {
710 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
711 return BT->getKind() >= BuiltinType::Char_S &&
712 BT->getKind() <= BuiltinType::Int128;
715 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
716 // Incomplete enum types are not treated as integer types.
717 // FIXME: In C++, enum types are never integer types.
718 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
719 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
725 bool Type::isSignedIntegerOrEnumerationType() const {
726 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
727 return BT->getKind() >= BuiltinType::Char_S &&
728 BT->getKind() <= BuiltinType::Int128;
731 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
732 if (ET->getDecl()->isComplete())
733 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
739 bool Type::hasSignedIntegerRepresentation() const {
740 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
741 return VT->getElementType()->isSignedIntegerOrEnumerationType();
743 return isSignedIntegerOrEnumerationType();
746 /// isUnsignedIntegerType - Return true if this is an integer type that is
747 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
748 /// decl which has an unsigned representation
749 bool Type::isUnsignedIntegerType() const {
750 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
751 return BT->getKind() >= BuiltinType::Bool &&
752 BT->getKind() <= BuiltinType::UInt128;
755 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
756 // Incomplete enum types are not treated as integer types.
757 // FIXME: In C++, enum types are never integer types.
758 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
759 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
765 bool Type::isUnsignedIntegerOrEnumerationType() const {
766 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
767 return BT->getKind() >= BuiltinType::Bool &&
768 BT->getKind() <= BuiltinType::UInt128;
771 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
772 if (ET->getDecl()->isComplete())
773 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
779 bool Type::hasUnsignedIntegerRepresentation() const {
780 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
781 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
783 return isUnsignedIntegerOrEnumerationType();
786 bool Type::isFloatingType() const {
787 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
788 return BT->getKind() >= BuiltinType::Half &&
789 BT->getKind() <= BuiltinType::LongDouble;
790 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
791 return CT->getElementType()->isFloatingType();
795 bool Type::hasFloatingRepresentation() const {
796 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
797 return VT->getElementType()->isFloatingType();
799 return isFloatingType();
802 bool Type::isRealFloatingType() const {
803 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
804 return BT->isFloatingPoint();
808 bool Type::isRealType() const {
809 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
810 return BT->getKind() >= BuiltinType::Bool &&
811 BT->getKind() <= BuiltinType::LongDouble;
812 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
813 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
817 bool Type::isArithmeticType() const {
818 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
819 return BT->getKind() >= BuiltinType::Bool &&
820 BT->getKind() <= BuiltinType::LongDouble;
821 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
822 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
823 // If a body isn't seen by the time we get here, return false.
825 // C++0x: Enumerations are not arithmetic types. For now, just return
826 // false for scoped enumerations since that will disable any
827 // unwanted implicit conversions.
828 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
829 return isa<ComplexType>(CanonicalType);
832 Type::ScalarTypeKind Type::getScalarTypeKind() const {
833 assert(isScalarType());
835 const Type *T = CanonicalType.getTypePtr();
836 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
837 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
838 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
839 if (BT->isInteger()) return STK_Integral;
840 if (BT->isFloatingPoint()) return STK_Floating;
841 llvm_unreachable("unknown scalar builtin type");
842 } else if (isa<PointerType>(T)) {
844 } else if (isa<BlockPointerType>(T)) {
845 return STK_BlockPointer;
846 } else if (isa<ObjCObjectPointerType>(T)) {
847 return STK_ObjCObjectPointer;
848 } else if (isa<MemberPointerType>(T)) {
849 return STK_MemberPointer;
850 } else if (isa<EnumType>(T)) {
851 assert(cast<EnumType>(T)->getDecl()->isComplete());
853 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
854 if (CT->getElementType()->isRealFloatingType())
855 return STK_FloatingComplex;
856 return STK_IntegralComplex;
859 llvm_unreachable("unknown scalar type");
862 /// \brief Determines whether the type is a C++ aggregate type or C
863 /// aggregate or union type.
865 /// An aggregate type is an array or a class type (struct, union, or
866 /// class) that has no user-declared constructors, no private or
867 /// protected non-static data members, no base classes, and no virtual
868 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
869 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
870 /// includes union types.
871 bool Type::isAggregateType() const {
872 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
873 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
874 return ClassDecl->isAggregate();
879 return isa<ArrayType>(CanonicalType);
882 /// isConstantSizeType - Return true if this is not a variable sized type,
883 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
884 /// incomplete types or dependent types.
885 bool Type::isConstantSizeType() const {
886 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
887 assert(!isDependentType() && "This doesn't make sense for dependent types");
888 // The VAT must have a size, as it is known to be complete.
889 return !isa<VariableArrayType>(CanonicalType);
892 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
893 /// - a type that can describe objects, but which lacks information needed to
894 /// determine its size.
895 bool Type::isIncompleteType(NamedDecl **Def) const {
899 switch (CanonicalType->getTypeClass()) {
900 default: return false;
902 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
906 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
910 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
911 if (EnumD->isFixed())
914 return !EnumD->isCompleteDefinition();
917 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
918 // forward declaration, but not a full definition (C99 6.2.5p22).
919 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
922 return !Rec->isCompleteDefinition();
925 // An array is incomplete if its element type is incomplete
926 // (C++ [dcl.array]p1).
927 // We don't handle variable arrays (they're not allowed in C++) or
928 // dependent-sized arrays (dependent types are never treated as incomplete).
929 return cast<ArrayType>(CanonicalType)->getElementType()
930 ->isIncompleteType(Def);
931 case IncompleteArray:
932 // An array of unknown size is an incomplete type (C99 6.2.5p22).
935 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
936 ->isIncompleteType(Def);
937 case ObjCInterface: {
938 // ObjC interfaces are incomplete if they are @class, not @interface.
939 ObjCInterfaceDecl *Interface
940 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
943 return !Interface->hasDefinition();
948 bool QualType::isPODType(ASTContext &Context) const {
949 // C++11 has a more relaxed definition of POD.
950 if (Context.getLangOpts().CPlusPlus11)
951 return isCXX11PODType(Context);
953 return isCXX98PODType(Context);
956 bool QualType::isCXX98PODType(ASTContext &Context) const {
957 // The compiler shouldn't query this for incomplete types, but the user might.
958 // We return false for that case. Except for incomplete arrays of PODs, which
959 // are PODs according to the standard.
963 if ((*this)->isIncompleteArrayType())
964 return Context.getBaseElementType(*this).isCXX98PODType(Context);
966 if ((*this)->isIncompleteType())
969 if (Context.getLangOpts().ObjCAutoRefCount) {
970 switch (getObjCLifetime()) {
971 case Qualifiers::OCL_ExplicitNone:
974 case Qualifiers::OCL_Strong:
975 case Qualifiers::OCL_Weak:
976 case Qualifiers::OCL_Autoreleasing:
979 case Qualifiers::OCL_None:
984 QualType CanonicalType = getTypePtr()->CanonicalType;
985 switch (CanonicalType->getTypeClass()) {
986 // Everything not explicitly mentioned is not POD.
987 default: return false;
988 case Type::VariableArray:
989 case Type::ConstantArray:
990 // IncompleteArray is handled above.
991 return Context.getBaseElementType(*this).isCXX98PODType(Context);
993 case Type::ObjCObjectPointer:
994 case Type::BlockPointer:
998 case Type::MemberPointer:
1000 case Type::ExtVector:
1007 if (CXXRecordDecl *ClassDecl
1008 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1009 return ClassDecl->isPOD();
1011 // C struct/union is POD.
1016 bool QualType::isTrivialType(ASTContext &Context) const {
1017 // The compiler shouldn't query this for incomplete types, but the user might.
1018 // We return false for that case. Except for incomplete arrays of PODs, which
1019 // are PODs according to the standard.
1023 if ((*this)->isArrayType())
1024 return Context.getBaseElementType(*this).isTrivialType(Context);
1026 // Return false for incomplete types after skipping any incomplete array
1027 // types which are expressly allowed by the standard and thus our API.
1028 if ((*this)->isIncompleteType())
1031 if (Context.getLangOpts().ObjCAutoRefCount) {
1032 switch (getObjCLifetime()) {
1033 case Qualifiers::OCL_ExplicitNone:
1036 case Qualifiers::OCL_Strong:
1037 case Qualifiers::OCL_Weak:
1038 case Qualifiers::OCL_Autoreleasing:
1041 case Qualifiers::OCL_None:
1042 if ((*this)->isObjCLifetimeType())
1048 QualType CanonicalType = getTypePtr()->CanonicalType;
1049 if (CanonicalType->isDependentType())
1052 // C++0x [basic.types]p9:
1053 // Scalar types, trivial class types, arrays of such types, and
1054 // cv-qualified versions of these types are collectively called trivial
1057 // As an extension, Clang treats vector types as Scalar types.
1058 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1060 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1061 if (const CXXRecordDecl *ClassDecl =
1062 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1064 // A trivial class is a class that has a default constructor,
1065 // has no non-trivial default constructors, and is trivially
1067 return ClassDecl->hasDefaultConstructor() &&
1068 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1069 ClassDecl->isTriviallyCopyable();
1075 // No other types can match.
1079 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1080 if ((*this)->isArrayType())
1081 return Context.getBaseElementType(*this).isTrivialType(Context);
1083 if (Context.getLangOpts().ObjCAutoRefCount) {
1084 switch (getObjCLifetime()) {
1085 case Qualifiers::OCL_ExplicitNone:
1088 case Qualifiers::OCL_Strong:
1089 case Qualifiers::OCL_Weak:
1090 case Qualifiers::OCL_Autoreleasing:
1093 case Qualifiers::OCL_None:
1094 if ((*this)->isObjCLifetimeType())
1100 // C++11 [basic.types]p9
1101 // Scalar types, trivially copyable class types, arrays of such types, and
1102 // non-volatile const-qualified versions of these types are collectively
1103 // called trivially copyable types.
1105 QualType CanonicalType = getCanonicalType();
1106 if (CanonicalType->isDependentType())
1109 if (CanonicalType.isVolatileQualified())
1112 // Return false for incomplete types after skipping any incomplete array types
1113 // which are expressly allowed by the standard and thus our API.
1114 if (CanonicalType->isIncompleteType())
1117 // As an extension, Clang treats vector types as Scalar types.
1118 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1121 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1122 if (const CXXRecordDecl *ClassDecl =
1123 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1124 if (!ClassDecl->isTriviallyCopyable()) return false;
1130 // No other types can match.
1136 bool Type::isLiteralType(const ASTContext &Ctx) const {
1137 if (isDependentType())
1140 // C++1y [basic.types]p10:
1141 // A type is a literal type if it is:
1143 if (Ctx.getLangOpts().CPlusPlus1y && isVoidType())
1146 // C++11 [basic.types]p10:
1147 // A type is a literal type if it is:
1149 // -- an array of literal type other than an array of runtime bound; or
1150 if (isVariableArrayType())
1152 const Type *BaseTy = getBaseElementTypeUnsafe();
1153 assert(BaseTy && "NULL element type");
1155 // Return false for incomplete types after skipping any incomplete array
1156 // types; those are expressly allowed by the standard and thus our API.
1157 if (BaseTy->isIncompleteType())
1160 // C++11 [basic.types]p10:
1161 // A type is a literal type if it is:
1162 // -- a scalar type; or
1163 // As an extension, Clang treats vector types and complex types as
1165 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1166 BaseTy->isAnyComplexType())
1168 // -- a reference type; or
1169 if (BaseTy->isReferenceType())
1171 // -- a class type that has all of the following properties:
1172 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1173 // -- a trivial destructor,
1174 // -- every constructor call and full-expression in the
1175 // brace-or-equal-initializers for non-static data members (if any)
1176 // is a constant expression,
1177 // -- it is an aggregate type or has at least one constexpr
1178 // constructor or constructor template that is not a copy or move
1180 // -- all non-static data members and base classes of literal types
1182 // We resolve DR1361 by ignoring the second bullet.
1183 if (const CXXRecordDecl *ClassDecl =
1184 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1185 return ClassDecl->isLiteral();
1190 // We treat _Atomic T as a literal type if T is a literal type.
1191 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1192 return AT->getValueType()->isLiteralType(Ctx);
1194 // If this type hasn't been deduced yet, then conservatively assume that
1195 // it'll work out to be a literal type.
1196 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1202 bool Type::isStandardLayoutType() const {
1203 if (isDependentType())
1206 // C++0x [basic.types]p9:
1207 // Scalar types, standard-layout class types, arrays of such types, and
1208 // cv-qualified versions of these types are collectively called
1209 // standard-layout types.
1210 const Type *BaseTy = getBaseElementTypeUnsafe();
1211 assert(BaseTy && "NULL element type");
1213 // Return false for incomplete types after skipping any incomplete array
1214 // types which are expressly allowed by the standard and thus our API.
1215 if (BaseTy->isIncompleteType())
1218 // As an extension, Clang treats vector types as Scalar types.
1219 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1220 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1221 if (const CXXRecordDecl *ClassDecl =
1222 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1223 if (!ClassDecl->isStandardLayout())
1226 // Default to 'true' for non-C++ class types.
1227 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1228 // all the requirements of standard layout classes.
1232 // No other types can match.
1236 // This is effectively the intersection of isTrivialType and
1237 // isStandardLayoutType. We implement it directly to avoid redundant
1238 // conversions from a type to a CXXRecordDecl.
1239 bool QualType::isCXX11PODType(ASTContext &Context) const {
1240 const Type *ty = getTypePtr();
1241 if (ty->isDependentType())
1244 if (Context.getLangOpts().ObjCAutoRefCount) {
1245 switch (getObjCLifetime()) {
1246 case Qualifiers::OCL_ExplicitNone:
1249 case Qualifiers::OCL_Strong:
1250 case Qualifiers::OCL_Weak:
1251 case Qualifiers::OCL_Autoreleasing:
1254 case Qualifiers::OCL_None:
1259 // C++11 [basic.types]p9:
1260 // Scalar types, POD classes, arrays of such types, and cv-qualified
1261 // versions of these types are collectively called trivial types.
1262 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1263 assert(BaseTy && "NULL element type");
1265 // Return false for incomplete types after skipping any incomplete array
1266 // types which are expressly allowed by the standard and thus our API.
1267 if (BaseTy->isIncompleteType())
1270 // As an extension, Clang treats vector types as Scalar types.
1271 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1272 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1273 if (const CXXRecordDecl *ClassDecl =
1274 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1275 // C++11 [class]p10:
1276 // A POD struct is a non-union class that is both a trivial class [...]
1277 if (!ClassDecl->isTrivial()) return false;
1279 // C++11 [class]p10:
1280 // A POD struct is a non-union class that is both a trivial class and
1281 // a standard-layout class [...]
1282 if (!ClassDecl->isStandardLayout()) return false;
1284 // C++11 [class]p10:
1285 // A POD struct is a non-union class that is both a trivial class and
1286 // a standard-layout class, and has no non-static data members of type
1287 // non-POD struct, non-POD union (or array of such types). [...]
1289 // We don't directly query the recursive aspect as the requiremets for
1290 // both standard-layout classes and trivial classes apply recursively
1297 // No other types can match.
1301 bool Type::isPromotableIntegerType() const {
1302 if (const BuiltinType *BT = getAs<BuiltinType>())
1303 switch (BT->getKind()) {
1304 case BuiltinType::Bool:
1305 case BuiltinType::Char_S:
1306 case BuiltinType::Char_U:
1307 case BuiltinType::SChar:
1308 case BuiltinType::UChar:
1309 case BuiltinType::Short:
1310 case BuiltinType::UShort:
1311 case BuiltinType::WChar_S:
1312 case BuiltinType::WChar_U:
1313 case BuiltinType::Char16:
1314 case BuiltinType::Char32:
1320 // Enumerated types are promotable to their compatible integer types
1321 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1322 if (const EnumType *ET = getAs<EnumType>()){
1323 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1324 || ET->getDecl()->isScoped())
1333 bool Type::isSpecifierType() const {
1334 // Note that this intentionally does not use the canonical type.
1335 switch (getTypeClass()) {
1343 case TemplateTypeParm:
1344 case SubstTemplateTypeParm:
1345 case TemplateSpecialization:
1348 case DependentTemplateSpecialization:
1351 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1358 ElaboratedTypeKeyword
1359 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1361 default: return ETK_None;
1362 case TST_typename: return ETK_Typename;
1363 case TST_class: return ETK_Class;
1364 case TST_struct: return ETK_Struct;
1365 case TST_interface: return ETK_Interface;
1366 case TST_union: return ETK_Union;
1367 case TST_enum: return ETK_Enum;
1372 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1374 case TST_class: return TTK_Class;
1375 case TST_struct: return TTK_Struct;
1376 case TST_interface: return TTK_Interface;
1377 case TST_union: return TTK_Union;
1378 case TST_enum: return TTK_Enum;
1381 llvm_unreachable("Type specifier is not a tag type kind.");
1384 ElaboratedTypeKeyword
1385 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1387 case TTK_Class: return ETK_Class;
1388 case TTK_Struct: return ETK_Struct;
1389 case TTK_Interface: return ETK_Interface;
1390 case TTK_Union: return ETK_Union;
1391 case TTK_Enum: return ETK_Enum;
1393 llvm_unreachable("Unknown tag type kind.");
1397 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1399 case ETK_Class: return TTK_Class;
1400 case ETK_Struct: return TTK_Struct;
1401 case ETK_Interface: return TTK_Interface;
1402 case ETK_Union: return TTK_Union;
1403 case ETK_Enum: return TTK_Enum;
1404 case ETK_None: // Fall through.
1406 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1408 llvm_unreachable("Unknown elaborated type keyword.");
1412 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1424 llvm_unreachable("Unknown elaborated type keyword.");
1428 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1430 case ETK_None: return "";
1431 case ETK_Typename: return "typename";
1432 case ETK_Class: return "class";
1433 case ETK_Struct: return "struct";
1434 case ETK_Interface: return "__interface";
1435 case ETK_Union: return "union";
1436 case ETK_Enum: return "enum";
1439 llvm_unreachable("Unknown elaborated type keyword.");
1442 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1443 ElaboratedTypeKeyword Keyword,
1444 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1445 unsigned NumArgs, const TemplateArgument *Args,
1447 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1448 /*VariablyModified=*/false,
1449 NNS && NNS->containsUnexpandedParameterPack()),
1450 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1451 assert((!NNS || NNS->isDependent()) &&
1452 "DependentTemplateSpecializatonType requires dependent qualifier");
1453 for (unsigned I = 0; I != NumArgs; ++I) {
1454 if (Args[I].containsUnexpandedParameterPack())
1455 setContainsUnexpandedParameterPack();
1457 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1462 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1463 const ASTContext &Context,
1464 ElaboratedTypeKeyword Keyword,
1465 NestedNameSpecifier *Qualifier,
1466 const IdentifierInfo *Name,
1468 const TemplateArgument *Args) {
1469 ID.AddInteger(Keyword);
1470 ID.AddPointer(Qualifier);
1471 ID.AddPointer(Name);
1472 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1473 Args[Idx].Profile(ID, Context);
1476 bool Type::isElaboratedTypeSpecifier() const {
1477 ElaboratedTypeKeyword Keyword;
1478 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1479 Keyword = Elab->getKeyword();
1480 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1481 Keyword = DepName->getKeyword();
1482 else if (const DependentTemplateSpecializationType *DepTST =
1483 dyn_cast<DependentTemplateSpecializationType>(this))
1484 Keyword = DepTST->getKeyword();
1488 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1491 const char *Type::getTypeClassName() const {
1492 switch (TypeBits.TC) {
1493 #define ABSTRACT_TYPE(Derived, Base)
1494 #define TYPE(Derived, Base) case Derived: return #Derived;
1495 #include "clang/AST/TypeNodes.def"
1498 llvm_unreachable("Invalid type class.");
1501 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1502 switch (getKind()) {
1503 case Void: return "void";
1504 case Bool: return Policy.Bool ? "bool" : "_Bool";
1505 case Char_S: return "char";
1506 case Char_U: return "char";
1507 case SChar: return "signed char";
1508 case Short: return "short";
1509 case Int: return "int";
1510 case Long: return "long";
1511 case LongLong: return "long long";
1512 case Int128: return "__int128";
1513 case UChar: return "unsigned char";
1514 case UShort: return "unsigned short";
1515 case UInt: return "unsigned int";
1516 case ULong: return "unsigned long";
1517 case ULongLong: return "unsigned long long";
1518 case UInt128: return "unsigned __int128";
1519 case Half: return "half";
1520 case Float: return "float";
1521 case Double: return "double";
1522 case LongDouble: return "long double";
1524 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1525 case Char16: return "char16_t";
1526 case Char32: return "char32_t";
1527 case NullPtr: return "nullptr_t";
1528 case Overload: return "<overloaded function type>";
1529 case BoundMember: return "<bound member function type>";
1530 case PseudoObject: return "<pseudo-object type>";
1531 case Dependent: return "<dependent type>";
1532 case UnknownAny: return "<unknown type>";
1533 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1534 case BuiltinFn: return "<builtin fn type>";
1535 case ObjCId: return "id";
1536 case ObjCClass: return "Class";
1537 case ObjCSel: return "SEL";
1538 case OCLImage1d: return "image1d_t";
1539 case OCLImage1dArray: return "image1d_array_t";
1540 case OCLImage1dBuffer: return "image1d_buffer_t";
1541 case OCLImage2d: return "image2d_t";
1542 case OCLImage2dArray: return "image2d_array_t";
1543 case OCLImage3d: return "image3d_t";
1544 case OCLSampler: return "sampler_t";
1545 case OCLEvent: return "event_t";
1548 llvm_unreachable("Invalid builtin type.");
1551 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1552 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1553 return RefType->getPointeeType();
1555 // C++0x [basic.lval]:
1556 // Class prvalues can have cv-qualified types; non-class prvalues always
1557 // have cv-unqualified types.
1559 // See also C99 6.3.2.1p2.
1560 if (!Context.getLangOpts().CPlusPlus ||
1561 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1562 return getUnqualifiedType();
1567 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1569 case CC_C: return "cdecl";
1570 case CC_X86StdCall: return "stdcall";
1571 case CC_X86FastCall: return "fastcall";
1572 case CC_X86ThisCall: return "thiscall";
1573 case CC_X86Pascal: return "pascal";
1574 case CC_X86_64Win64: return "ms_abi";
1575 case CC_X86_64SysV: return "sysv_abi";
1576 case CC_AAPCS: return "aapcs";
1577 case CC_AAPCS_VFP: return "aapcs-vfp";
1578 case CC_PnaclCall: return "pnaclcall";
1579 case CC_IntelOclBicc: return "intel_ocl_bicc";
1582 llvm_unreachable("Invalid calling convention.");
1585 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> args,
1587 const ExtProtoInfo &epi)
1588 : FunctionType(FunctionProto, result, epi.TypeQuals,
1590 result->isDependentType(),
1591 result->isInstantiationDependentType(),
1592 result->isVariablyModifiedType(),
1593 result->containsUnexpandedParameterPack(),
1595 NumArgs(args.size()), NumExceptions(epi.NumExceptions),
1596 ExceptionSpecType(epi.ExceptionSpecType),
1597 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1598 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn),
1599 RefQualifier(epi.RefQualifier)
1601 assert(NumArgs == args.size() && "function has too many parameters");
1603 // Fill in the trailing argument array.
1604 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1605 for (unsigned i = 0; i != NumArgs; ++i) {
1606 if (args[i]->isDependentType())
1608 else if (args[i]->isInstantiationDependentType())
1609 setInstantiationDependent();
1611 if (args[i]->containsUnexpandedParameterPack())
1612 setContainsUnexpandedParameterPack();
1614 argSlot[i] = args[i];
1617 if (getExceptionSpecType() == EST_Dynamic) {
1618 // Fill in the exception array.
1619 QualType *exnSlot = argSlot + NumArgs;
1620 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1621 if (epi.Exceptions[i]->isDependentType())
1623 else if (epi.Exceptions[i]->isInstantiationDependentType())
1624 setInstantiationDependent();
1626 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1627 setContainsUnexpandedParameterPack();
1629 exnSlot[i] = epi.Exceptions[i];
1631 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1632 // Store the noexcept expression and context.
1633 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + NumArgs);
1634 *noexSlot = epi.NoexceptExpr;
1636 if (epi.NoexceptExpr) {
1637 if (epi.NoexceptExpr->isValueDependent()
1638 || epi.NoexceptExpr->isTypeDependent())
1640 else if (epi.NoexceptExpr->isInstantiationDependent())
1641 setInstantiationDependent();
1643 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1644 // Store the function decl from which we will resolve our
1645 // exception specification.
1646 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1647 slot[0] = epi.ExceptionSpecDecl;
1648 slot[1] = epi.ExceptionSpecTemplate;
1649 // This exception specification doesn't make the type dependent, because
1650 // it's not instantiated as part of instantiating the type.
1651 } else if (getExceptionSpecType() == EST_Unevaluated) {
1652 // Store the function decl from which we will resolve our
1653 // exception specification.
1654 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1655 slot[0] = epi.ExceptionSpecDecl;
1658 if (epi.ConsumedArguments) {
1659 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1660 for (unsigned i = 0; i != NumArgs; ++i)
1661 consumedArgs[i] = epi.ConsumedArguments[i];
1665 FunctionProtoType::NoexceptResult
1666 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1667 ExceptionSpecificationType est = getExceptionSpecType();
1668 if (est == EST_BasicNoexcept)
1671 if (est != EST_ComputedNoexcept)
1672 return NR_NoNoexcept;
1674 Expr *noexceptExpr = getNoexceptExpr();
1676 return NR_BadNoexcept;
1677 if (noexceptExpr->isValueDependent())
1678 return NR_Dependent;
1681 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1682 /*evaluated*/false);
1684 assert(isICE && "AST should not contain bad noexcept expressions.");
1686 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1689 bool FunctionProtoType::isTemplateVariadic() const {
1690 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1691 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1697 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1698 const QualType *ArgTys, unsigned NumArgs,
1699 const ExtProtoInfo &epi,
1700 const ASTContext &Context) {
1702 // We have to be careful not to get ambiguous profile encodings.
1703 // Note that valid type pointers are never ambiguous with anything else.
1705 // The encoding grammar begins:
1706 // type type* bool int bool
1707 // If that final bool is true, then there is a section for the EH spec:
1709 // This is followed by an optional "consumed argument" section of the
1710 // same length as the first type sequence:
1712 // Finally, we have the ext info and trailing return type flag:
1715 // There is no ambiguity between the consumed arguments and an empty EH
1716 // spec because of the leading 'bool' which unambiguously indicates
1717 // whether the following bool is the EH spec or part of the arguments.
1719 ID.AddPointer(Result.getAsOpaquePtr());
1720 for (unsigned i = 0; i != NumArgs; ++i)
1721 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1722 // This method is relatively performance sensitive, so as a performance
1723 // shortcut, use one AddInteger call instead of four for the next four
1725 assert(!(unsigned(epi.Variadic) & ~1) &&
1726 !(unsigned(epi.TypeQuals) & ~255) &&
1727 !(unsigned(epi.RefQualifier) & ~3) &&
1728 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1729 "Values larger than expected.");
1730 ID.AddInteger(unsigned(epi.Variadic) +
1731 (epi.TypeQuals << 1) +
1732 (epi.RefQualifier << 9) +
1733 (epi.ExceptionSpecType << 11));
1734 if (epi.ExceptionSpecType == EST_Dynamic) {
1735 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1736 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1737 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1738 epi.NoexceptExpr->Profile(ID, Context, false);
1739 } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1740 epi.ExceptionSpecType == EST_Unevaluated) {
1741 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1743 if (epi.ConsumedArguments) {
1744 for (unsigned i = 0; i != NumArgs; ++i)
1745 ID.AddBoolean(epi.ConsumedArguments[i]);
1747 epi.ExtInfo.Profile(ID);
1748 ID.AddBoolean(epi.HasTrailingReturn);
1751 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1752 const ASTContext &Ctx) {
1753 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1757 QualType TypedefType::desugar() const {
1758 return getDecl()->getUnderlyingType();
1761 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1762 : Type(TypeOfExpr, can, E->isTypeDependent(),
1763 E->isInstantiationDependent(),
1764 E->getType()->isVariablyModifiedType(),
1765 E->containsUnexpandedParameterPack()),
1769 bool TypeOfExprType::isSugared() const {
1770 return !TOExpr->isTypeDependent();
1773 QualType TypeOfExprType::desugar() const {
1775 return getUnderlyingExpr()->getType();
1777 return QualType(this, 0);
1780 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1781 const ASTContext &Context, Expr *E) {
1782 E->Profile(ID, Context, true);
1785 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1786 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1787 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1788 // type-dependent even if its expression is only instantiation-dependent.
1789 : Type(Decltype, can, E->isInstantiationDependent(),
1790 E->isInstantiationDependent(),
1791 E->getType()->isVariablyModifiedType(),
1792 E->containsUnexpandedParameterPack()),
1794 UnderlyingType(underlyingType) {
1797 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1799 QualType DecltypeType::desugar() const {
1801 return getUnderlyingType();
1803 return QualType(this, 0);
1806 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1807 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1809 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1810 const ASTContext &Context, Expr *E) {
1811 E->Profile(ID, Context, true);
1814 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1815 : Type(TC, can, D->isDependentType(),
1816 /*InstantiationDependent=*/D->isDependentType(),
1817 /*VariablyModified=*/false,
1818 /*ContainsUnexpandedParameterPack=*/false),
1819 decl(const_cast<TagDecl*>(D)) {}
1821 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1822 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1823 E = decl->redecls_end();
1825 if (I->isCompleteDefinition() || I->isBeingDefined())
1828 // If there's no definition (not even in progress), return what we have.
1832 UnaryTransformType::UnaryTransformType(QualType BaseType,
1833 QualType UnderlyingType,
1835 QualType CanonicalType)
1836 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1837 UnderlyingType->isInstantiationDependentType(),
1838 UnderlyingType->isVariablyModifiedType(),
1839 BaseType->containsUnexpandedParameterPack())
1840 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1843 TagDecl *TagType::getDecl() const {
1844 return getInterestingTagDecl(decl);
1847 bool TagType::isBeingDefined() const {
1848 return getDecl()->isBeingDefined();
1851 bool AttributedType::isMSTypeSpec() const {
1852 switch (getAttrKind()) {
1853 default: return false;
1860 llvm_unreachable("invalid attr kind");
1863 bool AttributedType::isCallingConv() const {
1864 switch (getAttrKind()) {
1869 case attr_address_space:
1871 case attr_vector_size:
1872 case attr_neon_vector_type:
1873 case attr_neon_polyvector_type:
1875 case attr_objc_ownership:
1887 case attr_pnaclcall:
1888 case attr_inteloclbicc:
1891 llvm_unreachable("invalid attr kind");
1894 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1895 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1898 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1899 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1902 SubstTemplateTypeParmPackType::
1903 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1905 const TemplateArgument &ArgPack)
1906 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1908 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1912 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1913 return TemplateArgument(Arguments, NumArguments);
1916 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1917 Profile(ID, getReplacedParameter(), getArgumentPack());
1920 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1921 const TemplateTypeParmType *Replaced,
1922 const TemplateArgument &ArgPack) {
1923 ID.AddPointer(Replaced);
1924 ID.AddInteger(ArgPack.pack_size());
1925 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1926 PEnd = ArgPack.pack_end();
1928 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1931 bool TemplateSpecializationType::
1932 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1933 bool &InstantiationDependent) {
1934 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1935 InstantiationDependent);
1938 bool TemplateSpecializationType::
1939 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1940 bool &InstantiationDependent) {
1941 for (unsigned i = 0; i != N; ++i) {
1942 if (Args[i].getArgument().isDependent()) {
1943 InstantiationDependent = true;
1947 if (Args[i].getArgument().isInstantiationDependent())
1948 InstantiationDependent = true;
1955 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1956 bool &InstantiationDependent) {
1957 for (unsigned i = 0; i != N; ++i) {
1958 if (Args[i].isDependent()) {
1959 InstantiationDependent = true;
1963 if (Args[i].isInstantiationDependent())
1964 InstantiationDependent = true;
1970 TemplateSpecializationType::
1971 TemplateSpecializationType(TemplateName T,
1972 const TemplateArgument *Args, unsigned NumArgs,
1973 QualType Canon, QualType AliasedType)
1974 : Type(TemplateSpecialization,
1975 Canon.isNull()? QualType(this, 0) : Canon,
1976 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1977 Canon.isNull()? T.isDependent()
1978 : Canon->isInstantiationDependentType(),
1980 T.containsUnexpandedParameterPack()),
1981 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1982 assert(!T.getAsDependentTemplateName() &&
1983 "Use DependentTemplateSpecializationType for dependent template-name");
1984 assert((T.getKind() == TemplateName::Template ||
1985 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1986 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1987 "Unexpected template name for TemplateSpecializationType");
1988 bool InstantiationDependent;
1989 (void)InstantiationDependent;
1990 assert((!Canon.isNull() ||
1992 ::anyDependentTemplateArguments(Args, NumArgs,
1993 InstantiationDependent)) &&
1994 "No canonical type for non-dependent class template specialization");
1996 TemplateArgument *TemplateArgs
1997 = reinterpret_cast<TemplateArgument *>(this + 1);
1998 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1999 // Update dependent and variably-modified bits.
2000 // If the canonical type exists and is non-dependent, the template
2001 // specialization type can be non-dependent even if one of the type
2002 // arguments is. Given:
2003 // template<typename T> using U = int;
2004 // U<T> is always non-dependent, irrespective of the type T.
2005 // However, U<Ts> contains an unexpanded parameter pack, even though
2006 // its expansion (and thus its desugared type) doesn't.
2007 if (Canon.isNull() && Args[Arg].isDependent())
2009 else if (Args[Arg].isInstantiationDependent())
2010 setInstantiationDependent();
2012 if (Args[Arg].getKind() == TemplateArgument::Type &&
2013 Args[Arg].getAsType()->isVariablyModifiedType())
2014 setVariablyModified();
2015 if (Args[Arg].containsUnexpandedParameterPack())
2016 setContainsUnexpandedParameterPack();
2018 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2021 // Store the aliased type if this is a type alias template specialization.
2023 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2024 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2029 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2031 const TemplateArgument *Args,
2033 const ASTContext &Context) {
2035 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2036 Args[Idx].Profile(ID, Context);
2040 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2041 if (!hasNonFastQualifiers())
2042 return QT.withFastQualifiers(getFastQualifiers());
2044 return Context.getQualifiedType(QT, *this);
2048 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2049 if (!hasNonFastQualifiers())
2050 return QualType(T, getFastQualifiers());
2052 return Context.getQualifiedType(T, *this);
2055 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2057 ObjCProtocolDecl * const *Protocols,
2058 unsigned NumProtocols) {
2059 ID.AddPointer(BaseType.getAsOpaquePtr());
2060 for (unsigned i = 0; i != NumProtocols; i++)
2061 ID.AddPointer(Protocols[i]);
2064 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2065 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2070 /// \brief The cached properties of a type.
2071 class CachedProperties {
2076 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2078 Linkage getLinkage() const { return L; }
2079 bool hasLocalOrUnnamedType() const { return local; }
2081 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2082 Linkage MergedLinkage = minLinkage(L.L, R.L);
2083 return CachedProperties(MergedLinkage,
2084 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2089 static CachedProperties computeCachedProperties(const Type *T);
2092 /// The type-property cache. This is templated so as to be
2093 /// instantiated at an internal type to prevent unnecessary symbol
2095 template <class Private> class TypePropertyCache {
2097 static CachedProperties get(QualType T) {
2098 return get(T.getTypePtr());
2101 static CachedProperties get(const Type *T) {
2103 return CachedProperties(T->TypeBits.getLinkage(),
2104 T->TypeBits.hasLocalOrUnnamedType());
2107 static void ensure(const Type *T) {
2108 // If the cache is valid, we're okay.
2109 if (T->TypeBits.isCacheValid()) return;
2111 // If this type is non-canonical, ask its canonical type for the
2112 // relevant information.
2113 if (!T->isCanonicalUnqualified()) {
2114 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2116 T->TypeBits.CacheValid = true;
2117 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2118 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2122 // Compute the cached properties and then set the cache.
2123 CachedProperties Result = computeCachedProperties(T);
2124 T->TypeBits.CacheValid = true;
2125 T->TypeBits.CachedLinkage = Result.getLinkage();
2126 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2131 // Instantiate the friend template at a private class. In a
2132 // reasonable implementation, these symbols will be internal.
2133 // It is terrible that this is the best way to accomplish this.
2134 namespace { class Private {}; }
2135 typedef TypePropertyCache<Private> Cache;
2137 static CachedProperties computeCachedProperties(const Type *T) {
2138 switch (T->getTypeClass()) {
2139 #define TYPE(Class,Base)
2140 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2141 #include "clang/AST/TypeNodes.def"
2142 llvm_unreachable("didn't expect a non-canonical type here");
2144 #define TYPE(Class,Base)
2145 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2146 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2147 #include "clang/AST/TypeNodes.def"
2148 // Treat instantiation-dependent types as external.
2149 assert(T->isInstantiationDependentType());
2150 return CachedProperties(ExternalLinkage, false);
2153 // Give non-deduced 'auto' types external linkage. We should only see them
2154 // here in error recovery.
2155 return CachedProperties(ExternalLinkage, false);
2158 // C++ [basic.link]p8:
2159 // A type is said to have linkage if and only if:
2160 // - it is a fundamental type (3.9.1); or
2161 return CachedProperties(ExternalLinkage, false);
2165 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2167 // C++ [basic.link]p8:
2168 // - it is a class or enumeration type that is named (or has a name
2169 // for linkage purposes (7.1.3)) and the name has linkage; or
2170 // - it is a specialization of a class template (14); or
2171 Linkage L = Tag->getLinkageInternal();
2172 bool IsLocalOrUnnamed =
2173 Tag->getDeclContext()->isFunctionOrMethod() ||
2174 !Tag->hasNameForLinkage();
2175 return CachedProperties(L, IsLocalOrUnnamed);
2178 // C++ [basic.link]p8:
2179 // - it is a compound type (3.9.2) other than a class or enumeration,
2180 // compounded exclusively from types that have linkage; or
2182 return Cache::get(cast<ComplexType>(T)->getElementType());
2184 return Cache::get(cast<PointerType>(T)->getPointeeType());
2185 case Type::BlockPointer:
2186 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2187 case Type::LValueReference:
2188 case Type::RValueReference:
2189 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2190 case Type::MemberPointer: {
2191 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2192 return merge(Cache::get(MPT->getClass()),
2193 Cache::get(MPT->getPointeeType()));
2195 case Type::ConstantArray:
2196 case Type::IncompleteArray:
2197 case Type::VariableArray:
2198 return Cache::get(cast<ArrayType>(T)->getElementType());
2200 case Type::ExtVector:
2201 return Cache::get(cast<VectorType>(T)->getElementType());
2202 case Type::FunctionNoProto:
2203 return Cache::get(cast<FunctionType>(T)->getResultType());
2204 case Type::FunctionProto: {
2205 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2206 CachedProperties result = Cache::get(FPT->getResultType());
2207 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2208 ae = FPT->arg_type_end(); ai != ae; ++ai)
2209 result = merge(result, Cache::get(*ai));
2212 case Type::ObjCInterface: {
2213 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2214 return CachedProperties(L, false);
2216 case Type::ObjCObject:
2217 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2218 case Type::ObjCObjectPointer:
2219 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2221 return Cache::get(cast<AtomicType>(T)->getValueType());
2224 llvm_unreachable("unhandled type class");
2227 /// \brief Determine the linkage of this type.
2228 Linkage Type::getLinkage() const {
2229 Cache::ensure(this);
2230 return TypeBits.getLinkage();
2233 bool Type::hasUnnamedOrLocalType() const {
2234 Cache::ensure(this);
2235 return TypeBits.hasLocalOrUnnamedType();
2238 static LinkageInfo computeLinkageInfo(QualType T);
2240 static LinkageInfo computeLinkageInfo(const Type *T) {
2241 switch (T->getTypeClass()) {
2242 #define TYPE(Class,Base)
2243 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2244 #include "clang/AST/TypeNodes.def"
2245 llvm_unreachable("didn't expect a non-canonical type here");
2247 #define TYPE(Class,Base)
2248 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2249 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2250 #include "clang/AST/TypeNodes.def"
2251 // Treat instantiation-dependent types as external.
2252 assert(T->isInstantiationDependentType());
2253 return LinkageInfo::external();
2256 return LinkageInfo::external();
2259 return LinkageInfo::external();
2263 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2266 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2268 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2269 case Type::BlockPointer:
2270 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2271 case Type::LValueReference:
2272 case Type::RValueReference:
2273 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2274 case Type::MemberPointer: {
2275 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2276 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2277 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2280 case Type::ConstantArray:
2281 case Type::IncompleteArray:
2282 case Type::VariableArray:
2283 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2285 case Type::ExtVector:
2286 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2287 case Type::FunctionNoProto:
2288 return computeLinkageInfo(cast<FunctionType>(T)->getResultType());
2289 case Type::FunctionProto: {
2290 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2291 LinkageInfo LV = computeLinkageInfo(FPT->getResultType());
2292 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2293 ae = FPT->arg_type_end(); ai != ae; ++ai)
2294 LV.merge(computeLinkageInfo(*ai));
2297 case Type::ObjCInterface:
2298 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2299 case Type::ObjCObject:
2300 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2301 case Type::ObjCObjectPointer:
2302 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2304 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2307 llvm_unreachable("unhandled type class");
2310 static LinkageInfo computeLinkageInfo(QualType T) {
2311 return computeLinkageInfo(T.getTypePtr());
2314 bool Type::isLinkageValid() const {
2315 if (!TypeBits.isCacheValid())
2318 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2319 TypeBits.getLinkage();
2322 LinkageInfo Type::getLinkageAndVisibility() const {
2323 if (!isCanonicalUnqualified())
2324 return computeLinkageInfo(getCanonicalTypeInternal());
2326 LinkageInfo LV = computeLinkageInfo(this);
2327 assert(LV.getLinkage() == getLinkage());
2331 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2332 if (isObjCARCImplicitlyUnretainedType())
2333 return Qualifiers::OCL_ExplicitNone;
2334 return Qualifiers::OCL_Strong;
2337 bool Type::isObjCARCImplicitlyUnretainedType() const {
2338 assert(isObjCLifetimeType() &&
2339 "cannot query implicit lifetime for non-inferrable type");
2341 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2343 // Walk down to the base type. We don't care about qualifiers for this.
2344 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2345 canon = array->getElementType().getTypePtr();
2347 if (const ObjCObjectPointerType *opt
2348 = dyn_cast<ObjCObjectPointerType>(canon)) {
2349 // Class and Class<Protocol> don't require retension.
2350 if (opt->getObjectType()->isObjCClass())
2357 bool Type::isObjCNSObjectType() const {
2358 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2359 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2362 bool Type::isObjCRetainableType() const {
2363 return isObjCObjectPointerType() ||
2364 isBlockPointerType() ||
2365 isObjCNSObjectType();
2367 bool Type::isObjCIndirectLifetimeType() const {
2368 if (isObjCLifetimeType())
2370 if (const PointerType *OPT = getAs<PointerType>())
2371 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2372 if (const ReferenceType *Ref = getAs<ReferenceType>())
2373 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2374 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2375 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2379 /// Returns true if objects of this type have lifetime semantics under
2381 bool Type::isObjCLifetimeType() const {
2382 const Type *type = this;
2383 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2384 type = array->getElementType().getTypePtr();
2385 return type->isObjCRetainableType();
2388 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2389 /// which is either an Objective-C object pointer type or an
2390 bool Type::isObjCARCBridgableType() const {
2391 return isObjCObjectPointerType() || isBlockPointerType();
2394 /// \brief Determine whether the given type T is a "bridgeable" C type.
2395 bool Type::isCARCBridgableType() const {
2396 const PointerType *Pointer = getAs<PointerType>();
2400 QualType Pointee = Pointer->getPointeeType();
2401 return Pointee->isVoidType() || Pointee->isRecordType();
2404 bool Type::hasSizedVLAType() const {
2405 if (!isVariablyModifiedType()) return false;
2407 if (const PointerType *ptr = getAs<PointerType>())
2408 return ptr->getPointeeType()->hasSizedVLAType();
2409 if (const ReferenceType *ref = getAs<ReferenceType>())
2410 return ref->getPointeeType()->hasSizedVLAType();
2411 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2412 if (isa<VariableArrayType>(arr) &&
2413 cast<VariableArrayType>(arr)->getSizeExpr())
2416 return arr->getElementType()->hasSizedVLAType();
2422 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2423 switch (type.getObjCLifetime()) {
2424 case Qualifiers::OCL_None:
2425 case Qualifiers::OCL_ExplicitNone:
2426 case Qualifiers::OCL_Autoreleasing:
2429 case Qualifiers::OCL_Strong:
2430 return DK_objc_strong_lifetime;
2431 case Qualifiers::OCL_Weak:
2432 return DK_objc_weak_lifetime;
2435 /// Currently, the only destruction kind we recognize is C++ objects
2436 /// with non-trivial destructors.
2437 const CXXRecordDecl *record =
2438 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2439 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2440 return DK_cxx_destructor;