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_64(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 // GCC appears to only allow 63 bits worth of address space when compiling
115 // for 64-bit, so we do the same.
122 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
123 QualType et, QualType can,
124 Expr *e, ArraySizeModifier sm,
126 SourceRange brackets)
127 : ArrayType(DependentSizedArray, et, can, sm, tq,
128 (et->containsUnexpandedParameterPack() ||
129 (e && e->containsUnexpandedParameterPack()))),
130 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
134 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
135 const ASTContext &Context,
137 ArraySizeModifier SizeMod,
140 ID.AddPointer(ET.getAsOpaquePtr());
141 ID.AddInteger(SizeMod);
142 ID.AddInteger(TypeQuals);
143 E->Profile(ID, Context, true);
146 DependentSizedExtVectorType::DependentSizedExtVectorType(const
148 QualType ElementType,
152 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
153 /*InstantiationDependent=*/true,
154 ElementType->isVariablyModifiedType(),
155 (ElementType->containsUnexpandedParameterPack() ||
156 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
157 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
163 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
164 const ASTContext &Context,
165 QualType ElementType, Expr *SizeExpr) {
166 ID.AddPointer(ElementType.getAsOpaquePtr());
167 SizeExpr->Profile(ID, Context, true);
170 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
172 : Type(Vector, canonType, vecType->isDependentType(),
173 vecType->isInstantiationDependentType(),
174 vecType->isVariablyModifiedType(),
175 vecType->containsUnexpandedParameterPack()),
178 VectorTypeBits.VecKind = vecKind;
179 VectorTypeBits.NumElements = nElements;
182 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
183 QualType canonType, VectorKind vecKind)
184 : Type(tc, canonType, vecType->isDependentType(),
185 vecType->isInstantiationDependentType(),
186 vecType->isVariablyModifiedType(),
187 vecType->containsUnexpandedParameterPack()),
190 VectorTypeBits.VecKind = vecKind;
191 VectorTypeBits.NumElements = nElements;
194 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
195 /// element type of the array, potentially with type qualifiers missing.
196 /// This method should never be used when type qualifiers are meaningful.
197 const Type *Type::getArrayElementTypeNoTypeQual() const {
198 // If this is directly an array type, return it.
199 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
200 return ATy->getElementType().getTypePtr();
202 // If the canonical form of this type isn't the right kind, reject it.
203 if (!isa<ArrayType>(CanonicalType))
206 // If this is a typedef for an array type, strip the typedef off without
207 // losing all typedef information.
208 return cast<ArrayType>(getUnqualifiedDesugaredType())
209 ->getElementType().getTypePtr();
212 /// getDesugaredType - Return the specified type with any "sugar" removed from
213 /// the type. This takes off typedefs, typeof's etc. If the outer level of
214 /// the type is already concrete, it returns it unmodified. This is similar
215 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
216 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
218 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
219 SplitQualType split = getSplitDesugaredType(T);
220 return Context.getQualifiedType(split.Ty, split.Quals);
223 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
224 const ASTContext &Context) {
225 SplitQualType split = type.split();
226 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
227 return Context.getQualifiedType(desugar, split.Quals);
230 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
231 switch (getTypeClass()) {
232 #define ABSTRACT_TYPE(Class, Parent)
233 #define TYPE(Class, Parent) \
234 case Type::Class: { \
235 const Class##Type *ty = cast<Class##Type>(this); \
236 if (!ty->isSugared()) return QualType(ty, 0); \
237 return ty->desugar(); \
239 #include "clang/AST/TypeNodes.def"
241 llvm_unreachable("bad type kind!");
244 SplitQualType QualType::getSplitDesugaredType(QualType T) {
245 QualifierCollector Qs;
249 const Type *CurTy = Qs.strip(Cur);
250 switch (CurTy->getTypeClass()) {
251 #define ABSTRACT_TYPE(Class, Parent)
252 #define TYPE(Class, Parent) \
253 case Type::Class: { \
254 const Class##Type *Ty = cast<Class##Type>(CurTy); \
255 if (!Ty->isSugared()) \
256 return SplitQualType(Ty, Qs); \
257 Cur = Ty->desugar(); \
260 #include "clang/AST/TypeNodes.def"
265 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
266 SplitQualType split = type.split();
268 // All the qualifiers we've seen so far.
269 Qualifiers quals = split.Quals;
271 // The last type node we saw with any nodes inside it.
272 const Type *lastTypeWithQuals = split.Ty;
277 // Do a single-step desugar, aborting the loop if the type isn't
279 switch (split.Ty->getTypeClass()) {
280 #define ABSTRACT_TYPE(Class, Parent)
281 #define TYPE(Class, Parent) \
282 case Type::Class: { \
283 const Class##Type *ty = cast<Class##Type>(split.Ty); \
284 if (!ty->isSugared()) goto done; \
285 next = ty->desugar(); \
288 #include "clang/AST/TypeNodes.def"
291 // Otherwise, split the underlying type. If that yields qualifiers,
292 // update the information.
293 split = next.split();
294 if (!split.Quals.empty()) {
295 lastTypeWithQuals = split.Ty;
296 quals.addConsistentQualifiers(split.Quals);
301 return SplitQualType(lastTypeWithQuals, quals);
304 QualType QualType::IgnoreParens(QualType T) {
305 // FIXME: this seems inherently un-qualifiers-safe.
306 while (const ParenType *PT = T->getAs<ParenType>())
307 T = PT->getInnerType();
311 /// \brief This will check for a T (which should be a Type which can act as
312 /// sugar, such as a TypedefType) by removing any existing sugar until it
313 /// reaches a T or a non-sugared type.
314 template<typename T> static const T *getAsSugar(const Type *Cur) {
316 if (const T *Sugar = dyn_cast<T>(Cur))
318 switch (Cur->getTypeClass()) {
319 #define ABSTRACT_TYPE(Class, Parent)
320 #define TYPE(Class, Parent) \
321 case Type::Class: { \
322 const Class##Type *Ty = cast<Class##Type>(Cur); \
323 if (!Ty->isSugared()) return 0; \
324 Cur = Ty->desugar().getTypePtr(); \
327 #include "clang/AST/TypeNodes.def"
332 template <> const TypedefType *Type::getAs() const {
333 return getAsSugar<TypedefType>(this);
336 template <> const TemplateSpecializationType *Type::getAs() const {
337 return getAsSugar<TemplateSpecializationType>(this);
340 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
341 /// sugar off the given type. This should produce an object of the
342 /// same dynamic type as the canonical type.
343 const Type *Type::getUnqualifiedDesugaredType() const {
344 const Type *Cur = this;
347 switch (Cur->getTypeClass()) {
348 #define ABSTRACT_TYPE(Class, Parent)
349 #define TYPE(Class, Parent) \
351 const Class##Type *Ty = cast<Class##Type>(Cur); \
352 if (!Ty->isSugared()) return Cur; \
353 Cur = Ty->desugar().getTypePtr(); \
356 #include "clang/AST/TypeNodes.def"
361 bool Type::isDerivedType() const {
362 switch (CanonicalType->getTypeClass()) {
366 case IncompleteArray:
368 case FunctionNoProto:
369 case LValueReference:
370 case RValueReference:
377 bool Type::isClassType() const {
378 if (const RecordType *RT = getAs<RecordType>())
379 return RT->getDecl()->isClass();
382 bool Type::isStructureType() const {
383 if (const RecordType *RT = getAs<RecordType>())
384 return RT->getDecl()->isStruct();
387 bool Type::isInterfaceType() const {
388 if (const RecordType *RT = getAs<RecordType>())
389 return RT->getDecl()->isInterface();
392 bool Type::isStructureOrClassType() const {
393 if (const RecordType *RT = getAs<RecordType>())
394 return RT->getDecl()->isStruct() || RT->getDecl()->isClass() ||
395 RT->getDecl()->isInterface();
398 bool Type::isVoidPointerType() const {
399 if (const PointerType *PT = getAs<PointerType>())
400 return PT->getPointeeType()->isVoidType();
404 bool Type::isUnionType() const {
405 if (const RecordType *RT = getAs<RecordType>())
406 return RT->getDecl()->isUnion();
410 bool Type::isComplexType() const {
411 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
412 return CT->getElementType()->isFloatingType();
416 bool Type::isComplexIntegerType() const {
417 // Check for GCC complex integer extension.
418 return getAsComplexIntegerType();
421 const ComplexType *Type::getAsComplexIntegerType() const {
422 if (const ComplexType *Complex = getAs<ComplexType>())
423 if (Complex->getElementType()->isIntegerType())
428 QualType Type::getPointeeType() const {
429 if (const PointerType *PT = getAs<PointerType>())
430 return PT->getPointeeType();
431 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
432 return OPT->getPointeeType();
433 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
434 return BPT->getPointeeType();
435 if (const ReferenceType *RT = getAs<ReferenceType>())
436 return RT->getPointeeType();
440 const RecordType *Type::getAsStructureType() const {
441 // If this is directly a structure type, return it.
442 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
443 if (RT->getDecl()->isStruct())
447 // If the canonical form of this type isn't the right kind, reject it.
448 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
449 if (!RT->getDecl()->isStruct())
452 // If this is a typedef for a structure type, strip the typedef off without
453 // losing all typedef information.
454 return cast<RecordType>(getUnqualifiedDesugaredType());
459 const RecordType *Type::getAsUnionType() const {
460 // If this is directly a union type, return it.
461 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
462 if (RT->getDecl()->isUnion())
466 // If the canonical form of this type isn't the right kind, reject it.
467 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
468 if (!RT->getDecl()->isUnion())
471 // If this is a typedef for a union type, strip the typedef off without
472 // losing all typedef information.
473 return cast<RecordType>(getUnqualifiedDesugaredType());
479 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
480 ObjCProtocolDecl * const *Protocols,
481 unsigned NumProtocols)
482 : Type(ObjCObject, Canonical, false, false, false, false),
485 ObjCObjectTypeBits.NumProtocols = NumProtocols;
486 assert(getNumProtocols() == NumProtocols &&
487 "bitfield overflow in protocol count");
489 memcpy(getProtocolStorage(), Protocols,
490 NumProtocols * sizeof(ObjCProtocolDecl*));
493 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
494 // There is no sugar for ObjCObjectType's, just return the canonical
495 // type pointer if it is the right class. There is no typedef information to
496 // return and these cannot be Address-space qualified.
497 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
498 if (T->getNumProtocols() && T->getInterface())
503 bool Type::isObjCQualifiedInterfaceType() const {
504 return getAsObjCQualifiedInterfaceType() != 0;
507 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
508 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
509 // type pointer if it is the right class.
510 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
511 if (OPT->isObjCQualifiedIdType())
517 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
518 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
519 // type pointer if it is the right class.
520 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
521 if (OPT->isObjCQualifiedClassType())
527 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
528 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
529 if (OPT->getInterfaceType())
535 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
536 QualType PointeeType;
537 if (const PointerType *PT = getAs<PointerType>())
538 PointeeType = PT->getPointeeType();
539 else if (const ReferenceType *RT = getAs<ReferenceType>())
540 PointeeType = RT->getPointeeType();
544 if (const RecordType *RT = PointeeType->getAs<RecordType>())
545 return dyn_cast<CXXRecordDecl>(RT->getDecl());
550 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
551 if (const RecordType *RT = getAs<RecordType>())
552 return dyn_cast<CXXRecordDecl>(RT->getDecl());
553 else if (const InjectedClassNameType *Injected
554 = getAs<InjectedClassNameType>())
555 return Injected->getDecl();
561 class GetContainedAutoVisitor :
562 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
564 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
565 AutoType *Visit(QualType T) {
568 return Visit(T.getTypePtr());
571 // The 'auto' type itself.
572 AutoType *VisitAutoType(const AutoType *AT) {
573 return const_cast<AutoType*>(AT);
576 // Only these types can contain the desired 'auto' type.
577 AutoType *VisitPointerType(const PointerType *T) {
578 return Visit(T->getPointeeType());
580 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
581 return Visit(T->getPointeeType());
583 AutoType *VisitReferenceType(const ReferenceType *T) {
584 return Visit(T->getPointeeTypeAsWritten());
586 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
587 return Visit(T->getPointeeType());
589 AutoType *VisitArrayType(const ArrayType *T) {
590 return Visit(T->getElementType());
592 AutoType *VisitDependentSizedExtVectorType(
593 const DependentSizedExtVectorType *T) {
594 return Visit(T->getElementType());
596 AutoType *VisitVectorType(const VectorType *T) {
597 return Visit(T->getElementType());
599 AutoType *VisitFunctionType(const FunctionType *T) {
600 return Visit(T->getResultType());
602 AutoType *VisitParenType(const ParenType *T) {
603 return Visit(T->getInnerType());
605 AutoType *VisitAttributedType(const AttributedType *T) {
606 return Visit(T->getModifiedType());
611 AutoType *Type::getContainedAutoType() const {
612 return GetContainedAutoVisitor().Visit(this);
615 bool Type::hasIntegerRepresentation() const {
616 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
617 return VT->getElementType()->isIntegerType();
619 return isIntegerType();
622 /// \brief Determine whether this type is an integral type.
624 /// This routine determines whether the given type is an integral type per
625 /// C++ [basic.fundamental]p7. Although the C standard does not define the
626 /// term "integral type", it has a similar term "integer type", and in C++
627 /// the two terms are equivalent. However, C's "integer type" includes
628 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
629 /// parameter is used to determine whether we should be following the C or
630 /// C++ rules when determining whether this type is an integral/integer type.
632 /// For cases where C permits "an integer type" and C++ permits "an integral
633 /// type", use this routine.
635 /// For cases where C permits "an integer type" and C++ permits "an integral
636 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
638 /// \param Ctx The context in which this type occurs.
640 /// \returns true if the type is considered an integral type, false otherwise.
641 bool Type::isIntegralType(ASTContext &Ctx) const {
642 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
643 return BT->getKind() >= BuiltinType::Bool &&
644 BT->getKind() <= BuiltinType::Int128;
646 if (!Ctx.getLangOpts().CPlusPlus)
647 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
648 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
654 bool Type::isIntegralOrUnscopedEnumerationType() const {
655 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
656 return BT->getKind() >= BuiltinType::Bool &&
657 BT->getKind() <= BuiltinType::Int128;
659 // Check for a complete enum type; incomplete enum types are not properly an
660 // enumeration type in the sense required here.
661 // C++0x: However, if the underlying type of the enum is fixed, it is
662 // considered complete.
663 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
664 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
671 bool Type::isCharType() const {
672 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
673 return BT->getKind() == BuiltinType::Char_U ||
674 BT->getKind() == BuiltinType::UChar ||
675 BT->getKind() == BuiltinType::Char_S ||
676 BT->getKind() == BuiltinType::SChar;
680 bool Type::isWideCharType() const {
681 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
682 return BT->getKind() == BuiltinType::WChar_S ||
683 BT->getKind() == BuiltinType::WChar_U;
687 bool Type::isChar16Type() const {
688 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
689 return BT->getKind() == BuiltinType::Char16;
693 bool Type::isChar32Type() const {
694 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
695 return BT->getKind() == BuiltinType::Char32;
699 /// \brief Determine whether this type is any of the built-in character
701 bool Type::isAnyCharacterType() const {
702 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
703 if (BT == 0) return false;
704 switch (BT->getKind()) {
705 default: return false;
706 case BuiltinType::Char_U:
707 case BuiltinType::UChar:
708 case BuiltinType::WChar_U:
709 case BuiltinType::Char16:
710 case BuiltinType::Char32:
711 case BuiltinType::Char_S:
712 case BuiltinType::SChar:
713 case BuiltinType::WChar_S:
718 /// isSignedIntegerType - Return true if this is an integer type that is
719 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
720 /// an enum decl which has a signed representation
721 bool Type::isSignedIntegerType() const {
722 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
723 return BT->getKind() >= BuiltinType::Char_S &&
724 BT->getKind() <= BuiltinType::Int128;
727 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
728 // Incomplete enum types are not treated as integer types.
729 // FIXME: In C++, enum types are never integer types.
730 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
731 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
737 bool Type::isSignedIntegerOrEnumerationType() const {
738 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
739 return BT->getKind() >= BuiltinType::Char_S &&
740 BT->getKind() <= BuiltinType::Int128;
743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
744 if (ET->getDecl()->isComplete())
745 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
751 bool Type::hasSignedIntegerRepresentation() const {
752 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
753 return VT->getElementType()->isSignedIntegerType();
755 return isSignedIntegerType();
758 /// isUnsignedIntegerType - Return true if this is an integer type that is
759 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
760 /// decl which has an unsigned representation
761 bool Type::isUnsignedIntegerType() const {
762 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
763 return BT->getKind() >= BuiltinType::Bool &&
764 BT->getKind() <= BuiltinType::UInt128;
767 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
768 // Incomplete enum types are not treated as integer types.
769 // FIXME: In C++, enum types are never integer types.
770 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
771 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
777 bool Type::isUnsignedIntegerOrEnumerationType() const {
778 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
779 return BT->getKind() >= BuiltinType::Bool &&
780 BT->getKind() <= BuiltinType::UInt128;
783 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
784 if (ET->getDecl()->isComplete())
785 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
791 bool Type::hasUnsignedIntegerRepresentation() const {
792 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
793 return VT->getElementType()->isUnsignedIntegerType();
795 return isUnsignedIntegerType();
798 bool Type::isFloatingType() const {
799 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
800 return BT->getKind() >= BuiltinType::Half &&
801 BT->getKind() <= BuiltinType::LongDouble;
802 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
803 return CT->getElementType()->isFloatingType();
807 bool Type::hasFloatingRepresentation() const {
808 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
809 return VT->getElementType()->isFloatingType();
811 return isFloatingType();
814 bool Type::isRealFloatingType() const {
815 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
816 return BT->isFloatingPoint();
820 bool Type::isRealType() const {
821 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
822 return BT->getKind() >= BuiltinType::Bool &&
823 BT->getKind() <= BuiltinType::LongDouble;
824 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
825 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
829 bool Type::isArithmeticType() const {
830 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
831 return BT->getKind() >= BuiltinType::Bool &&
832 BT->getKind() <= BuiltinType::LongDouble;
833 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
834 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
835 // If a body isn't seen by the time we get here, return false.
837 // C++0x: Enumerations are not arithmetic types. For now, just return
838 // false for scoped enumerations since that will disable any
839 // unwanted implicit conversions.
840 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
841 return isa<ComplexType>(CanonicalType);
844 Type::ScalarTypeKind Type::getScalarTypeKind() const {
845 assert(isScalarType());
847 const Type *T = CanonicalType.getTypePtr();
848 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
849 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
850 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
851 if (BT->isInteger()) return STK_Integral;
852 if (BT->isFloatingPoint()) return STK_Floating;
853 llvm_unreachable("unknown scalar builtin type");
854 } else if (isa<PointerType>(T)) {
856 } else if (isa<BlockPointerType>(T)) {
857 return STK_BlockPointer;
858 } else if (isa<ObjCObjectPointerType>(T)) {
859 return STK_ObjCObjectPointer;
860 } else if (isa<MemberPointerType>(T)) {
861 return STK_MemberPointer;
862 } else if (isa<EnumType>(T)) {
863 assert(cast<EnumType>(T)->getDecl()->isComplete());
865 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
866 if (CT->getElementType()->isRealFloatingType())
867 return STK_FloatingComplex;
868 return STK_IntegralComplex;
871 llvm_unreachable("unknown scalar type");
874 /// \brief Determines whether the type is a C++ aggregate type or C
875 /// aggregate or union type.
877 /// An aggregate type is an array or a class type (struct, union, or
878 /// class) that has no user-declared constructors, no private or
879 /// protected non-static data members, no base classes, and no virtual
880 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
881 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
882 /// includes union types.
883 bool Type::isAggregateType() const {
884 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
885 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
886 return ClassDecl->isAggregate();
891 return isa<ArrayType>(CanonicalType);
894 /// isConstantSizeType - Return true if this is not a variable sized type,
895 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
896 /// incomplete types or dependent types.
897 bool Type::isConstantSizeType() const {
898 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
899 assert(!isDependentType() && "This doesn't make sense for dependent types");
900 // The VAT must have a size, as it is known to be complete.
901 return !isa<VariableArrayType>(CanonicalType);
904 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
905 /// - a type that can describe objects, but which lacks information needed to
906 /// determine its size.
907 bool Type::isIncompleteType(NamedDecl **Def) const {
911 switch (CanonicalType->getTypeClass()) {
912 default: return false;
914 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
918 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
922 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
923 if (EnumD->isFixed())
926 return !EnumD->isCompleteDefinition();
929 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
930 // forward declaration, but not a full definition (C99 6.2.5p22).
931 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
934 return !Rec->isCompleteDefinition();
937 // An array is incomplete if its element type is incomplete
938 // (C++ [dcl.array]p1).
939 // We don't handle variable arrays (they're not allowed in C++) or
940 // dependent-sized arrays (dependent types are never treated as incomplete).
941 return cast<ArrayType>(CanonicalType)->getElementType()
942 ->isIncompleteType(Def);
943 case IncompleteArray:
944 // An array of unknown size is an incomplete type (C99 6.2.5p22).
947 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
948 ->isIncompleteType(Def);
949 case ObjCInterface: {
950 // ObjC interfaces are incomplete if they are @class, not @interface.
951 ObjCInterfaceDecl *Interface
952 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
955 return !Interface->hasDefinition();
960 bool QualType::isPODType(ASTContext &Context) const {
961 // C++11 has a more relaxed definition of POD.
962 if (Context.getLangOpts().CPlusPlus11)
963 return isCXX11PODType(Context);
965 return isCXX98PODType(Context);
968 bool QualType::isCXX98PODType(ASTContext &Context) const {
969 // The compiler shouldn't query this for incomplete types, but the user might.
970 // We return false for that case. Except for incomplete arrays of PODs, which
971 // are PODs according to the standard.
975 if ((*this)->isIncompleteArrayType())
976 return Context.getBaseElementType(*this).isCXX98PODType(Context);
978 if ((*this)->isIncompleteType())
981 if (Context.getLangOpts().ObjCAutoRefCount) {
982 switch (getObjCLifetime()) {
983 case Qualifiers::OCL_ExplicitNone:
986 case Qualifiers::OCL_Strong:
987 case Qualifiers::OCL_Weak:
988 case Qualifiers::OCL_Autoreleasing:
991 case Qualifiers::OCL_None:
996 QualType CanonicalType = getTypePtr()->CanonicalType;
997 switch (CanonicalType->getTypeClass()) {
998 // Everything not explicitly mentioned is not POD.
999 default: return false;
1000 case Type::VariableArray:
1001 case Type::ConstantArray:
1002 // IncompleteArray is handled above.
1003 return Context.getBaseElementType(*this).isCXX98PODType(Context);
1005 case Type::ObjCObjectPointer:
1006 case Type::BlockPointer:
1010 case Type::MemberPointer:
1012 case Type::ExtVector:
1019 if (CXXRecordDecl *ClassDecl
1020 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1021 return ClassDecl->isPOD();
1023 // C struct/union is POD.
1028 bool QualType::isTrivialType(ASTContext &Context) const {
1029 // The compiler shouldn't query this for incomplete types, but the user might.
1030 // We return false for that case. Except for incomplete arrays of PODs, which
1031 // are PODs according to the standard.
1035 if ((*this)->isArrayType())
1036 return Context.getBaseElementType(*this).isTrivialType(Context);
1038 // Return false for incomplete types after skipping any incomplete array
1039 // types which are expressly allowed by the standard and thus our API.
1040 if ((*this)->isIncompleteType())
1043 if (Context.getLangOpts().ObjCAutoRefCount) {
1044 switch (getObjCLifetime()) {
1045 case Qualifiers::OCL_ExplicitNone:
1048 case Qualifiers::OCL_Strong:
1049 case Qualifiers::OCL_Weak:
1050 case Qualifiers::OCL_Autoreleasing:
1053 case Qualifiers::OCL_None:
1054 if ((*this)->isObjCLifetimeType())
1060 QualType CanonicalType = getTypePtr()->CanonicalType;
1061 if (CanonicalType->isDependentType())
1064 // C++0x [basic.types]p9:
1065 // Scalar types, trivial class types, arrays of such types, and
1066 // cv-qualified versions of these types are collectively called trivial
1069 // As an extension, Clang treats vector types as Scalar types.
1070 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1072 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1073 if (const CXXRecordDecl *ClassDecl =
1074 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1076 // A trivial class is a class that has a default constructor,
1077 // has no non-trivial default constructors, and is trivially
1079 return ClassDecl->hasDefaultConstructor() &&
1080 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1081 ClassDecl->isTriviallyCopyable();
1087 // No other types can match.
1091 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1092 if ((*this)->isArrayType())
1093 return Context.getBaseElementType(*this).isTrivialType(Context);
1095 if (Context.getLangOpts().ObjCAutoRefCount) {
1096 switch (getObjCLifetime()) {
1097 case Qualifiers::OCL_ExplicitNone:
1100 case Qualifiers::OCL_Strong:
1101 case Qualifiers::OCL_Weak:
1102 case Qualifiers::OCL_Autoreleasing:
1105 case Qualifiers::OCL_None:
1106 if ((*this)->isObjCLifetimeType())
1112 // C++0x [basic.types]p9
1113 // Scalar types, trivially copyable class types, arrays of such types, and
1114 // cv-qualified versions of these types are collectively called trivial
1117 QualType CanonicalType = getCanonicalType();
1118 if (CanonicalType->isDependentType())
1121 // Return false for incomplete types after skipping any incomplete array types
1122 // which are expressly allowed by the standard and thus our API.
1123 if (CanonicalType->isIncompleteType())
1126 // As an extension, Clang treats vector types as Scalar types.
1127 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1130 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1131 if (const CXXRecordDecl *ClassDecl =
1132 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1133 if (!ClassDecl->isTriviallyCopyable()) return false;
1139 // No other types can match.
1145 bool Type::isLiteralType(ASTContext &Ctx) const {
1146 if (isDependentType())
1149 // C++1y [basic.types]p10:
1150 // A type is a literal type if it is:
1152 if (Ctx.getLangOpts().CPlusPlus1y && isVoidType())
1155 // C++11 [basic.types]p10:
1156 // A type is a literal type if it is:
1158 // -- an array of literal type other than an array of runtime bound; or
1159 if (isVariableArrayType())
1161 const Type *BaseTy = getBaseElementTypeUnsafe();
1162 assert(BaseTy && "NULL element type");
1164 // Return false for incomplete types after skipping any incomplete array
1165 // types; those are expressly allowed by the standard and thus our API.
1166 if (BaseTy->isIncompleteType())
1169 // C++11 [basic.types]p10:
1170 // A type is a literal type if it is:
1171 // -- a scalar type; or
1172 // As an extension, Clang treats vector types and complex types as
1174 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1175 BaseTy->isAnyComplexType())
1177 // -- a reference type; or
1178 if (BaseTy->isReferenceType())
1180 // -- a class type that has all of the following properties:
1181 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1182 // -- a trivial destructor,
1183 // -- every constructor call and full-expression in the
1184 // brace-or-equal-initializers for non-static data members (if any)
1185 // is a constant expression,
1186 // -- it is an aggregate type or has at least one constexpr
1187 // constructor or constructor template that is not a copy or move
1189 // -- all non-static data members and base classes of literal types
1191 // We resolve DR1361 by ignoring the second bullet.
1192 if (const CXXRecordDecl *ClassDecl =
1193 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1194 return ClassDecl->isLiteral();
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 "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(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) {
1570 llvm_unreachable("no name for default cc");
1572 case CC_C: return "cdecl";
1573 case CC_X86StdCall: return "stdcall";
1574 case CC_X86FastCall: return "fastcall";
1575 case CC_X86ThisCall: return "thiscall";
1576 case CC_X86Pascal: return "pascal";
1577 case CC_AAPCS: return "aapcs";
1578 case CC_AAPCS_VFP: return "aapcs-vfp";
1579 case CC_PnaclCall: return "pnaclcall";
1580 case CC_IntelOclBicc: return "intel_ocl_bicc";
1583 llvm_unreachable("Invalid calling convention.");
1586 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> args,
1588 const ExtProtoInfo &epi)
1589 : FunctionType(FunctionProto, result, epi.TypeQuals,
1591 result->isDependentType(),
1592 result->isInstantiationDependentType(),
1593 result->isVariablyModifiedType(),
1594 result->containsUnexpandedParameterPack(),
1596 NumArgs(args.size()), NumExceptions(epi.NumExceptions),
1597 ExceptionSpecType(epi.ExceptionSpecType),
1598 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1599 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn),
1600 RefQualifier(epi.RefQualifier)
1602 assert(NumArgs == args.size() && "function has too many parameters");
1604 // Fill in the trailing argument array.
1605 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1606 for (unsigned i = 0; i != NumArgs; ++i) {
1607 if (args[i]->isDependentType())
1609 else if (args[i]->isInstantiationDependentType())
1610 setInstantiationDependent();
1612 if (args[i]->containsUnexpandedParameterPack())
1613 setContainsUnexpandedParameterPack();
1615 argSlot[i] = args[i];
1618 if (getExceptionSpecType() == EST_Dynamic) {
1619 // Fill in the exception array.
1620 QualType *exnSlot = argSlot + NumArgs;
1621 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1622 if (epi.Exceptions[i]->isDependentType())
1624 else if (epi.Exceptions[i]->isInstantiationDependentType())
1625 setInstantiationDependent();
1627 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1628 setContainsUnexpandedParameterPack();
1630 exnSlot[i] = epi.Exceptions[i];
1632 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1633 // Store the noexcept expression and context.
1634 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + NumArgs);
1635 *noexSlot = epi.NoexceptExpr;
1637 if (epi.NoexceptExpr) {
1638 if (epi.NoexceptExpr->isValueDependent()
1639 || epi.NoexceptExpr->isTypeDependent())
1641 else if (epi.NoexceptExpr->isInstantiationDependent())
1642 setInstantiationDependent();
1644 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1645 // Store the function decl from which we will resolve our
1646 // exception specification.
1647 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1648 slot[0] = epi.ExceptionSpecDecl;
1649 slot[1] = epi.ExceptionSpecTemplate;
1650 // This exception specification doesn't make the type dependent, because
1651 // it's not instantiated as part of instantiating the type.
1652 } else if (getExceptionSpecType() == EST_Unevaluated) {
1653 // Store the function decl from which we will resolve our
1654 // exception specification.
1655 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + NumArgs);
1656 slot[0] = epi.ExceptionSpecDecl;
1659 if (epi.ConsumedArguments) {
1660 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1661 for (unsigned i = 0; i != NumArgs; ++i)
1662 consumedArgs[i] = epi.ConsumedArguments[i];
1666 FunctionProtoType::NoexceptResult
1667 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1668 ExceptionSpecificationType est = getExceptionSpecType();
1669 if (est == EST_BasicNoexcept)
1672 if (est != EST_ComputedNoexcept)
1673 return NR_NoNoexcept;
1675 Expr *noexceptExpr = getNoexceptExpr();
1677 return NR_BadNoexcept;
1678 if (noexceptExpr->isValueDependent())
1679 return NR_Dependent;
1682 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1683 /*evaluated*/false);
1685 assert(isICE && "AST should not contain bad noexcept expressions.");
1687 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1690 bool FunctionProtoType::isTemplateVariadic() const {
1691 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1692 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1698 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1699 const QualType *ArgTys, unsigned NumArgs,
1700 const ExtProtoInfo &epi,
1701 const ASTContext &Context) {
1703 // We have to be careful not to get ambiguous profile encodings.
1704 // Note that valid type pointers are never ambiguous with anything else.
1706 // The encoding grammar begins:
1707 // type type* bool int bool
1708 // If that final bool is true, then there is a section for the EH spec:
1710 // This is followed by an optional "consumed argument" section of the
1711 // same length as the first type sequence:
1713 // Finally, we have the ext info and trailing return type flag:
1716 // There is no ambiguity between the consumed arguments and an empty EH
1717 // spec because of the leading 'bool' which unambiguously indicates
1718 // whether the following bool is the EH spec or part of the arguments.
1720 ID.AddPointer(Result.getAsOpaquePtr());
1721 for (unsigned i = 0; i != NumArgs; ++i)
1722 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1723 // This method is relatively performance sensitive, so as a performance
1724 // shortcut, use one AddInteger call instead of four for the next four
1726 assert(!(unsigned(epi.Variadic) & ~1) &&
1727 !(unsigned(epi.TypeQuals) & ~255) &&
1728 !(unsigned(epi.RefQualifier) & ~3) &&
1729 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1730 "Values larger than expected.");
1731 ID.AddInteger(unsigned(epi.Variadic) +
1732 (epi.TypeQuals << 1) +
1733 (epi.RefQualifier << 9) +
1734 (epi.ExceptionSpecType << 11));
1735 if (epi.ExceptionSpecType == EST_Dynamic) {
1736 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1737 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1738 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1739 epi.NoexceptExpr->Profile(ID, Context, false);
1740 } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1741 epi.ExceptionSpecType == EST_Unevaluated) {
1742 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1744 if (epi.ConsumedArguments) {
1745 for (unsigned i = 0; i != NumArgs; ++i)
1746 ID.AddBoolean(epi.ConsumedArguments[i]);
1748 epi.ExtInfo.Profile(ID);
1749 ID.AddBoolean(epi.HasTrailingReturn);
1752 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1753 const ASTContext &Ctx) {
1754 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1758 QualType TypedefType::desugar() const {
1759 return getDecl()->getUnderlyingType();
1762 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1763 : Type(TypeOfExpr, can, E->isTypeDependent(),
1764 E->isInstantiationDependent(),
1765 E->getType()->isVariablyModifiedType(),
1766 E->containsUnexpandedParameterPack()),
1770 bool TypeOfExprType::isSugared() const {
1771 return !TOExpr->isTypeDependent();
1774 QualType TypeOfExprType::desugar() const {
1776 return getUnderlyingExpr()->getType();
1778 return QualType(this, 0);
1781 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1782 const ASTContext &Context, Expr *E) {
1783 E->Profile(ID, Context, true);
1786 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1787 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1788 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1789 // type-dependent even if its expression is only instantiation-dependent.
1790 : Type(Decltype, can, E->isInstantiationDependent(),
1791 E->isInstantiationDependent(),
1792 E->getType()->isVariablyModifiedType(),
1793 E->containsUnexpandedParameterPack()),
1795 UnderlyingType(underlyingType) {
1798 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1800 QualType DecltypeType::desugar() const {
1802 return getUnderlyingType();
1804 return QualType(this, 0);
1807 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1808 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1810 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1811 const ASTContext &Context, Expr *E) {
1812 E->Profile(ID, Context, true);
1815 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1816 : Type(TC, can, D->isDependentType(),
1817 /*InstantiationDependent=*/D->isDependentType(),
1818 /*VariablyModified=*/false,
1819 /*ContainsUnexpandedParameterPack=*/false),
1820 decl(const_cast<TagDecl*>(D)) {}
1822 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1823 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1824 E = decl->redecls_end();
1826 if (I->isCompleteDefinition() || I->isBeingDefined())
1829 // If there's no definition (not even in progress), return what we have.
1833 UnaryTransformType::UnaryTransformType(QualType BaseType,
1834 QualType UnderlyingType,
1836 QualType CanonicalType)
1837 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1838 UnderlyingType->isInstantiationDependentType(),
1839 UnderlyingType->isVariablyModifiedType(),
1840 BaseType->containsUnexpandedParameterPack())
1841 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1844 TagDecl *TagType::getDecl() const {
1845 return getInterestingTagDecl(decl);
1848 bool TagType::isBeingDefined() const {
1849 return getDecl()->isBeingDefined();
1852 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1853 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1856 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1857 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1860 SubstTemplateTypeParmPackType::
1861 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1863 const TemplateArgument &ArgPack)
1864 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1866 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1870 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1871 return TemplateArgument(Arguments, NumArguments);
1874 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1875 Profile(ID, getReplacedParameter(), getArgumentPack());
1878 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1879 const TemplateTypeParmType *Replaced,
1880 const TemplateArgument &ArgPack) {
1881 ID.AddPointer(Replaced);
1882 ID.AddInteger(ArgPack.pack_size());
1883 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1884 PEnd = ArgPack.pack_end();
1886 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1889 bool TemplateSpecializationType::
1890 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1891 bool &InstantiationDependent) {
1892 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1893 InstantiationDependent);
1896 bool TemplateSpecializationType::
1897 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1898 bool &InstantiationDependent) {
1899 for (unsigned i = 0; i != N; ++i) {
1900 if (Args[i].getArgument().isDependent()) {
1901 InstantiationDependent = true;
1905 if (Args[i].getArgument().isInstantiationDependent())
1906 InstantiationDependent = true;
1911 bool TemplateSpecializationType::
1912 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1913 bool &InstantiationDependent) {
1914 for (unsigned i = 0; i != N; ++i) {
1915 if (Args[i].isDependent()) {
1916 InstantiationDependent = true;
1920 if (Args[i].isInstantiationDependent())
1921 InstantiationDependent = true;
1926 TemplateSpecializationType::
1927 TemplateSpecializationType(TemplateName T,
1928 const TemplateArgument *Args, unsigned NumArgs,
1929 QualType Canon, QualType AliasedType)
1930 : Type(TemplateSpecialization,
1931 Canon.isNull()? QualType(this, 0) : Canon,
1932 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1933 Canon.isNull()? T.isDependent()
1934 : Canon->isInstantiationDependentType(),
1936 T.containsUnexpandedParameterPack()),
1937 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1938 assert(!T.getAsDependentTemplateName() &&
1939 "Use DependentTemplateSpecializationType for dependent template-name");
1940 assert((T.getKind() == TemplateName::Template ||
1941 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1942 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1943 "Unexpected template name for TemplateSpecializationType");
1944 bool InstantiationDependent;
1945 (void)InstantiationDependent;
1946 assert((!Canon.isNull() ||
1948 anyDependentTemplateArguments(Args, NumArgs,
1949 InstantiationDependent)) &&
1950 "No canonical type for non-dependent class template specialization");
1952 TemplateArgument *TemplateArgs
1953 = reinterpret_cast<TemplateArgument *>(this + 1);
1954 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1955 // Update dependent and variably-modified bits.
1956 // If the canonical type exists and is non-dependent, the template
1957 // specialization type can be non-dependent even if one of the type
1958 // arguments is. Given:
1959 // template<typename T> using U = int;
1960 // U<T> is always non-dependent, irrespective of the type T.
1961 // However, U<Ts> contains an unexpanded parameter pack, even though
1962 // its expansion (and thus its desugared type) doesn't.
1963 if (Canon.isNull() && Args[Arg].isDependent())
1965 else if (Args[Arg].isInstantiationDependent())
1966 setInstantiationDependent();
1968 if (Args[Arg].getKind() == TemplateArgument::Type &&
1969 Args[Arg].getAsType()->isVariablyModifiedType())
1970 setVariablyModified();
1971 if (Args[Arg].containsUnexpandedParameterPack())
1972 setContainsUnexpandedParameterPack();
1974 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1977 // Store the aliased type if this is a type alias template specialization.
1979 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1980 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1985 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1987 const TemplateArgument *Args,
1989 const ASTContext &Context) {
1991 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1992 Args[Idx].Profile(ID, Context);
1996 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1997 if (!hasNonFastQualifiers())
1998 return QT.withFastQualifiers(getFastQualifiers());
2000 return Context.getQualifiedType(QT, *this);
2004 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2005 if (!hasNonFastQualifiers())
2006 return QualType(T, getFastQualifiers());
2008 return Context.getQualifiedType(T, *this);
2011 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2013 ObjCProtocolDecl * const *Protocols,
2014 unsigned NumProtocols) {
2015 ID.AddPointer(BaseType.getAsOpaquePtr());
2016 for (unsigned i = 0; i != NumProtocols; i++)
2017 ID.AddPointer(Protocols[i]);
2020 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2021 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2026 /// \brief The cached properties of a type.
2027 class CachedProperties {
2032 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2034 Linkage getLinkage() const { return L; }
2035 bool hasLocalOrUnnamedType() const { return local; }
2037 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2038 Linkage MergedLinkage = minLinkage(L.L, R.L);
2039 return CachedProperties(MergedLinkage,
2040 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2045 static CachedProperties computeCachedProperties(const Type *T);
2048 /// The type-property cache. This is templated so as to be
2049 /// instantiated at an internal type to prevent unnecessary symbol
2051 template <class Private> class TypePropertyCache {
2053 static CachedProperties get(QualType T) {
2054 return get(T.getTypePtr());
2057 static CachedProperties get(const Type *T) {
2059 return CachedProperties(T->TypeBits.getLinkage(),
2060 T->TypeBits.hasLocalOrUnnamedType());
2063 static void ensure(const Type *T) {
2064 // If the cache is valid, we're okay.
2065 if (T->TypeBits.isCacheValid()) return;
2067 // If this type is non-canonical, ask its canonical type for the
2068 // relevant information.
2069 if (!T->isCanonicalUnqualified()) {
2070 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2072 T->TypeBits.CacheValid = true;
2073 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2074 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2078 // Compute the cached properties and then set the cache.
2079 CachedProperties Result = computeCachedProperties(T);
2080 T->TypeBits.CacheValid = true;
2081 T->TypeBits.CachedLinkage = Result.getLinkage();
2082 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2087 // Instantiate the friend template at a private class. In a
2088 // reasonable implementation, these symbols will be internal.
2089 // It is terrible that this is the best way to accomplish this.
2090 namespace { class Private {}; }
2091 typedef TypePropertyCache<Private> Cache;
2093 static CachedProperties computeCachedProperties(const Type *T) {
2094 switch (T->getTypeClass()) {
2095 #define TYPE(Class,Base)
2096 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2097 #include "clang/AST/TypeNodes.def"
2098 llvm_unreachable("didn't expect a non-canonical type here");
2100 #define TYPE(Class,Base)
2101 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2102 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2103 #include "clang/AST/TypeNodes.def"
2104 // Treat instantiation-dependent types as external.
2105 assert(T->isInstantiationDependentType());
2106 return CachedProperties(ExternalLinkage, false);
2109 // Give non-deduced 'auto' types external linkage. We should only see them
2110 // here in error recovery.
2111 return CachedProperties(ExternalLinkage, false);
2114 // C++ [basic.link]p8:
2115 // A type is said to have linkage if and only if:
2116 // - it is a fundamental type (3.9.1); or
2117 return CachedProperties(ExternalLinkage, false);
2121 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2123 // C++ [basic.link]p8:
2124 // - it is a class or enumeration type that is named (or has a name
2125 // for linkage purposes (7.1.3)) and the name has linkage; or
2126 // - it is a specialization of a class template (14); or
2127 Linkage L = Tag->getLinkage();
2128 bool IsLocalOrUnnamed =
2129 Tag->getDeclContext()->isFunctionOrMethod() ||
2130 !Tag->hasNameForLinkage();
2131 return CachedProperties(L, IsLocalOrUnnamed);
2134 // C++ [basic.link]p8:
2135 // - it is a compound type (3.9.2) other than a class or enumeration,
2136 // compounded exclusively from types that have linkage; or
2138 return Cache::get(cast<ComplexType>(T)->getElementType());
2140 return Cache::get(cast<PointerType>(T)->getPointeeType());
2141 case Type::BlockPointer:
2142 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2143 case Type::LValueReference:
2144 case Type::RValueReference:
2145 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2146 case Type::MemberPointer: {
2147 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2148 return merge(Cache::get(MPT->getClass()),
2149 Cache::get(MPT->getPointeeType()));
2151 case Type::ConstantArray:
2152 case Type::IncompleteArray:
2153 case Type::VariableArray:
2154 return Cache::get(cast<ArrayType>(T)->getElementType());
2156 case Type::ExtVector:
2157 return Cache::get(cast<VectorType>(T)->getElementType());
2158 case Type::FunctionNoProto:
2159 return Cache::get(cast<FunctionType>(T)->getResultType());
2160 case Type::FunctionProto: {
2161 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2162 CachedProperties result = Cache::get(FPT->getResultType());
2163 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2164 ae = FPT->arg_type_end(); ai != ae; ++ai)
2165 result = merge(result, Cache::get(*ai));
2168 case Type::ObjCInterface: {
2169 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkage();
2170 return CachedProperties(L, false);
2172 case Type::ObjCObject:
2173 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2174 case Type::ObjCObjectPointer:
2175 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2177 return Cache::get(cast<AtomicType>(T)->getValueType());
2180 llvm_unreachable("unhandled type class");
2183 /// \brief Determine the linkage of this type.
2184 Linkage Type::getLinkage() const {
2185 Cache::ensure(this);
2186 return TypeBits.getLinkage();
2189 bool Type::hasUnnamedOrLocalType() const {
2190 Cache::ensure(this);
2191 return TypeBits.hasLocalOrUnnamedType();
2194 static LinkageInfo computeLinkageInfo(QualType T);
2196 static LinkageInfo computeLinkageInfo(const Type *T) {
2197 switch (T->getTypeClass()) {
2198 #define TYPE(Class,Base)
2199 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2200 #include "clang/AST/TypeNodes.def"
2201 llvm_unreachable("didn't expect a non-canonical type here");
2203 #define TYPE(Class,Base)
2204 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2205 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2206 #include "clang/AST/TypeNodes.def"
2207 // Treat instantiation-dependent types as external.
2208 assert(T->isInstantiationDependentType());
2209 return LinkageInfo::external();
2212 return LinkageInfo::external();
2215 return LinkageInfo::external();
2219 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2222 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2224 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2225 case Type::BlockPointer:
2226 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2227 case Type::LValueReference:
2228 case Type::RValueReference:
2229 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2230 case Type::MemberPointer: {
2231 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2232 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2233 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2236 case Type::ConstantArray:
2237 case Type::IncompleteArray:
2238 case Type::VariableArray:
2239 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2241 case Type::ExtVector:
2242 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2243 case Type::FunctionNoProto:
2244 return computeLinkageInfo(cast<FunctionType>(T)->getResultType());
2245 case Type::FunctionProto: {
2246 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2247 LinkageInfo LV = computeLinkageInfo(FPT->getResultType());
2248 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2249 ae = FPT->arg_type_end(); ai != ae; ++ai)
2250 LV.merge(computeLinkageInfo(*ai));
2253 case Type::ObjCInterface:
2254 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2255 case Type::ObjCObject:
2256 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2257 case Type::ObjCObjectPointer:
2258 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2260 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2263 llvm_unreachable("unhandled type class");
2266 static LinkageInfo computeLinkageInfo(QualType T) {
2267 return computeLinkageInfo(T.getTypePtr());
2270 bool Type::isLinkageValid() const {
2271 if (!TypeBits.isCacheValid())
2274 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2275 TypeBits.getLinkage();
2278 LinkageInfo Type::getLinkageAndVisibility() const {
2279 if (!isCanonicalUnqualified())
2280 return computeLinkageInfo(getCanonicalTypeInternal());
2282 LinkageInfo LV = computeLinkageInfo(this);
2283 assert(LV.getLinkage() == getLinkage());
2287 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2288 if (isObjCARCImplicitlyUnretainedType())
2289 return Qualifiers::OCL_ExplicitNone;
2290 return Qualifiers::OCL_Strong;
2293 bool Type::isObjCARCImplicitlyUnretainedType() const {
2294 assert(isObjCLifetimeType() &&
2295 "cannot query implicit lifetime for non-inferrable type");
2297 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2299 // Walk down to the base type. We don't care about qualifiers for this.
2300 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2301 canon = array->getElementType().getTypePtr();
2303 if (const ObjCObjectPointerType *opt
2304 = dyn_cast<ObjCObjectPointerType>(canon)) {
2305 // Class and Class<Protocol> don't require retension.
2306 if (opt->getObjectType()->isObjCClass())
2313 bool Type::isObjCNSObjectType() const {
2314 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2315 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2318 bool Type::isObjCRetainableType() const {
2319 return isObjCObjectPointerType() ||
2320 isBlockPointerType() ||
2321 isObjCNSObjectType();
2323 bool Type::isObjCIndirectLifetimeType() const {
2324 if (isObjCLifetimeType())
2326 if (const PointerType *OPT = getAs<PointerType>())
2327 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2328 if (const ReferenceType *Ref = getAs<ReferenceType>())
2329 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2330 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2331 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2335 /// Returns true if objects of this type have lifetime semantics under
2337 bool Type::isObjCLifetimeType() const {
2338 const Type *type = this;
2339 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2340 type = array->getElementType().getTypePtr();
2341 return type->isObjCRetainableType();
2344 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2345 /// which is either an Objective-C object pointer type or an
2346 bool Type::isObjCARCBridgableType() const {
2347 return isObjCObjectPointerType() || isBlockPointerType();
2350 /// \brief Determine whether the given type T is a "bridgeable" C type.
2351 bool Type::isCARCBridgableType() const {
2352 const PointerType *Pointer = getAs<PointerType>();
2356 QualType Pointee = Pointer->getPointeeType();
2357 return Pointee->isVoidType() || Pointee->isRecordType();
2360 bool Type::hasSizedVLAType() const {
2361 if (!isVariablyModifiedType()) return false;
2363 if (const PointerType *ptr = getAs<PointerType>())
2364 return ptr->getPointeeType()->hasSizedVLAType();
2365 if (const ReferenceType *ref = getAs<ReferenceType>())
2366 return ref->getPointeeType()->hasSizedVLAType();
2367 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2368 if (isa<VariableArrayType>(arr) &&
2369 cast<VariableArrayType>(arr)->getSizeExpr())
2372 return arr->getElementType()->hasSizedVLAType();
2378 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2379 switch (type.getObjCLifetime()) {
2380 case Qualifiers::OCL_None:
2381 case Qualifiers::OCL_ExplicitNone:
2382 case Qualifiers::OCL_Autoreleasing:
2385 case Qualifiers::OCL_Strong:
2386 return DK_objc_strong_lifetime;
2387 case Qualifiers::OCL_Weak:
2388 return DK_objc_weak_lifetime;
2391 /// Currently, the only destruction kind we recognize is C++ objects
2392 /// with non-trivial destructors.
2393 const CXXRecordDecl *record =
2394 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2395 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2396 return DK_cxx_destructor;