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();
48 NamedDecl *ND = nullptr;
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);
73 return T.getAddressSpace() == LangAS::opencl_constant;
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 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
175 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
176 QualType canonType, VectorKind vecKind)
177 : Type(tc, canonType, vecType->isDependentType(),
178 vecType->isInstantiationDependentType(),
179 vecType->isVariablyModifiedType(),
180 vecType->containsUnexpandedParameterPack()),
183 VectorTypeBits.VecKind = vecKind;
184 VectorTypeBits.NumElements = nElements;
187 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
188 /// element type of the array, potentially with type qualifiers missing.
189 /// This method should never be used when type qualifiers are meaningful.
190 const Type *Type::getArrayElementTypeNoTypeQual() const {
191 // If this is directly an array type, return it.
192 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
193 return ATy->getElementType().getTypePtr();
195 // If the canonical form of this type isn't the right kind, reject it.
196 if (!isa<ArrayType>(CanonicalType))
199 // If this is a typedef for an array type, strip the typedef off without
200 // losing all typedef information.
201 return cast<ArrayType>(getUnqualifiedDesugaredType())
202 ->getElementType().getTypePtr();
205 /// getDesugaredType - Return the specified type with any "sugar" removed from
206 /// the type. This takes off typedefs, typeof's etc. If the outer level of
207 /// the type is already concrete, it returns it unmodified. This is similar
208 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
209 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
211 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
212 SplitQualType split = getSplitDesugaredType(T);
213 return Context.getQualifiedType(split.Ty, split.Quals);
216 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
217 const ASTContext &Context) {
218 SplitQualType split = type.split();
219 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
220 return Context.getQualifiedType(desugar, split.Quals);
223 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
224 switch (getTypeClass()) {
225 #define ABSTRACT_TYPE(Class, Parent)
226 #define TYPE(Class, Parent) \
227 case Type::Class: { \
228 const Class##Type *ty = cast<Class##Type>(this); \
229 if (!ty->isSugared()) return QualType(ty, 0); \
230 return ty->desugar(); \
232 #include "clang/AST/TypeNodes.def"
234 llvm_unreachable("bad type kind!");
237 SplitQualType QualType::getSplitDesugaredType(QualType T) {
238 QualifierCollector Qs;
242 const Type *CurTy = Qs.strip(Cur);
243 switch (CurTy->getTypeClass()) {
244 #define ABSTRACT_TYPE(Class, Parent)
245 #define TYPE(Class, Parent) \
246 case Type::Class: { \
247 const Class##Type *Ty = cast<Class##Type>(CurTy); \
248 if (!Ty->isSugared()) \
249 return SplitQualType(Ty, Qs); \
250 Cur = Ty->desugar(); \
253 #include "clang/AST/TypeNodes.def"
258 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
259 SplitQualType split = type.split();
261 // All the qualifiers we've seen so far.
262 Qualifiers quals = split.Quals;
264 // The last type node we saw with any nodes inside it.
265 const Type *lastTypeWithQuals = split.Ty;
270 // Do a single-step desugar, aborting the loop if the type isn't
272 switch (split.Ty->getTypeClass()) {
273 #define ABSTRACT_TYPE(Class, Parent)
274 #define TYPE(Class, Parent) \
275 case Type::Class: { \
276 const Class##Type *ty = cast<Class##Type>(split.Ty); \
277 if (!ty->isSugared()) goto done; \
278 next = ty->desugar(); \
281 #include "clang/AST/TypeNodes.def"
284 // Otherwise, split the underlying type. If that yields qualifiers,
285 // update the information.
286 split = next.split();
287 if (!split.Quals.empty()) {
288 lastTypeWithQuals = split.Ty;
289 quals.addConsistentQualifiers(split.Quals);
294 return SplitQualType(lastTypeWithQuals, quals);
297 QualType QualType::IgnoreParens(QualType T) {
298 // FIXME: this seems inherently un-qualifiers-safe.
299 while (const ParenType *PT = T->getAs<ParenType>())
300 T = PT->getInnerType();
304 /// \brief This will check for a T (which should be a Type which can act as
305 /// sugar, such as a TypedefType) by removing any existing sugar until it
306 /// reaches a T or a non-sugared type.
307 template<typename T> static const T *getAsSugar(const Type *Cur) {
309 if (const T *Sugar = dyn_cast<T>(Cur))
311 switch (Cur->getTypeClass()) {
312 #define ABSTRACT_TYPE(Class, Parent)
313 #define TYPE(Class, Parent) \
314 case Type::Class: { \
315 const Class##Type *Ty = cast<Class##Type>(Cur); \
316 if (!Ty->isSugared()) return 0; \
317 Cur = Ty->desugar().getTypePtr(); \
320 #include "clang/AST/TypeNodes.def"
325 template <> const TypedefType *Type::getAs() const {
326 return getAsSugar<TypedefType>(this);
329 template <> const TemplateSpecializationType *Type::getAs() const {
330 return getAsSugar<TemplateSpecializationType>(this);
333 template <> const AttributedType *Type::getAs() const {
334 return getAsSugar<AttributedType>(this);
337 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
338 /// sugar off the given type. This should produce an object of the
339 /// same dynamic type as the canonical type.
340 const Type *Type::getUnqualifiedDesugaredType() const {
341 const Type *Cur = this;
344 switch (Cur->getTypeClass()) {
345 #define ABSTRACT_TYPE(Class, Parent)
346 #define TYPE(Class, Parent) \
348 const Class##Type *Ty = cast<Class##Type>(Cur); \
349 if (!Ty->isSugared()) return Cur; \
350 Cur = Ty->desugar().getTypePtr(); \
353 #include "clang/AST/TypeNodes.def"
357 bool Type::isClassType() const {
358 if (const RecordType *RT = getAs<RecordType>())
359 return RT->getDecl()->isClass();
362 bool Type::isStructureType() const {
363 if (const RecordType *RT = getAs<RecordType>())
364 return RT->getDecl()->isStruct();
367 bool Type::isObjCBoxableRecordType() const {
368 if (const RecordType *RT = getAs<RecordType>())
369 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
372 bool Type::isInterfaceType() const {
373 if (const RecordType *RT = getAs<RecordType>())
374 return RT->getDecl()->isInterface();
377 bool Type::isStructureOrClassType() const {
378 if (const RecordType *RT = getAs<RecordType>()) {
379 RecordDecl *RD = RT->getDecl();
380 return RD->isStruct() || RD->isClass() || RD->isInterface();
384 bool Type::isVoidPointerType() const {
385 if (const PointerType *PT = getAs<PointerType>())
386 return PT->getPointeeType()->isVoidType();
390 bool Type::isUnionType() const {
391 if (const RecordType *RT = getAs<RecordType>())
392 return RT->getDecl()->isUnion();
396 bool Type::isComplexType() const {
397 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
398 return CT->getElementType()->isFloatingType();
402 bool Type::isComplexIntegerType() const {
403 // Check for GCC complex integer extension.
404 return getAsComplexIntegerType();
407 const ComplexType *Type::getAsComplexIntegerType() const {
408 if (const ComplexType *Complex = getAs<ComplexType>())
409 if (Complex->getElementType()->isIntegerType())
414 QualType Type::getPointeeType() const {
415 if (const PointerType *PT = getAs<PointerType>())
416 return PT->getPointeeType();
417 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
418 return OPT->getPointeeType();
419 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
420 return BPT->getPointeeType();
421 if (const ReferenceType *RT = getAs<ReferenceType>())
422 return RT->getPointeeType();
423 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
424 return MPT->getPointeeType();
425 if (const DecayedType *DT = getAs<DecayedType>())
426 return DT->getPointeeType();
430 const RecordType *Type::getAsStructureType() const {
431 // If this is directly a structure type, return it.
432 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
433 if (RT->getDecl()->isStruct())
437 // If the canonical form of this type isn't the right kind, reject it.
438 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
439 if (!RT->getDecl()->isStruct())
442 // If this is a typedef for a structure type, strip the typedef off without
443 // losing all typedef information.
444 return cast<RecordType>(getUnqualifiedDesugaredType());
449 const RecordType *Type::getAsUnionType() const {
450 // If this is directly a union type, return it.
451 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
452 if (RT->getDecl()->isUnion())
456 // If the canonical form of this type isn't the right kind, reject it.
457 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
458 if (!RT->getDecl()->isUnion())
461 // If this is a typedef for a union type, strip the typedef off without
462 // losing all typedef information.
463 return cast<RecordType>(getUnqualifiedDesugaredType());
469 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
470 const ObjCObjectType *&bound) const {
473 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
478 if (OPT->isObjCIdType())
481 // If it's not a __kindof type, reject it now.
482 if (!OPT->isKindOfType())
485 // If it's Class or qualified Class, it's not an object type.
486 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
489 // Figure out the type bound for the __kindof type.
490 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
491 ->getAs<ObjCObjectType>();
495 bool Type::isObjCClassOrClassKindOfType() const {
496 const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>();
501 if (OPT->isObjCClassType())
504 // If it's not a __kindof type, reject it now.
505 if (!OPT->isKindOfType())
508 // If it's Class or qualified Class, it's a class __kindof type.
509 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
512 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
513 ArrayRef<QualType> typeArgs,
514 ArrayRef<ObjCProtocolDecl *> protocols,
516 : Type(ObjCObject, Canonical, Base->isDependentType(),
517 Base->isInstantiationDependentType(),
518 Base->isVariablyModifiedType(),
519 Base->containsUnexpandedParameterPack()),
522 ObjCObjectTypeBits.IsKindOf = isKindOf;
524 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
525 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
526 "bitfield overflow in type argument count");
527 ObjCObjectTypeBits.NumProtocols = protocols.size();
528 assert(getNumProtocols() == protocols.size() &&
529 "bitfield overflow in protocol count");
530 if (!typeArgs.empty())
531 memcpy(getTypeArgStorage(), typeArgs.data(),
532 typeArgs.size() * sizeof(QualType));
533 if (!protocols.empty())
534 memcpy(getProtocolStorage(), protocols.data(),
535 protocols.size() * sizeof(ObjCProtocolDecl*));
537 for (auto typeArg : typeArgs) {
538 if (typeArg->isDependentType())
540 else if (typeArg->isInstantiationDependentType())
541 setInstantiationDependent();
543 if (typeArg->containsUnexpandedParameterPack())
544 setContainsUnexpandedParameterPack();
548 bool ObjCObjectType::isSpecialized() const {
549 // If we have type arguments written here, the type is specialized.
550 if (ObjCObjectTypeBits.NumTypeArgs > 0)
553 // Otherwise, check whether the base type is specialized.
554 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
555 // Terminate when we reach an interface type.
556 if (isa<ObjCInterfaceType>(objcObject))
559 return objcObject->isSpecialized();
566 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
567 // We have type arguments written on this type.
568 if (isSpecializedAsWritten())
569 return getTypeArgsAsWritten();
571 // Look at the base type, which might have type arguments.
572 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
573 // Terminate when we reach an interface type.
574 if (isa<ObjCInterfaceType>(objcObject))
577 return objcObject->getTypeArgs();
580 // No type arguments.
584 bool ObjCObjectType::isKindOfType() const {
585 if (isKindOfTypeAsWritten())
588 // Look at the base type, which might have type arguments.
589 if (auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
590 // Terminate when we reach an interface type.
591 if (isa<ObjCInterfaceType>(objcObject))
594 return objcObject->isKindOfType();
597 // Not a "__kindof" type.
601 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
602 const ASTContext &ctx) const {
603 if (!isKindOfType() && qual_empty())
604 return QualType(this, 0);
606 // Recursively strip __kindof.
607 SplitQualType splitBaseType = getBaseType().split();
608 QualType baseType(splitBaseType.Ty, 0);
609 if (const ObjCObjectType *baseObj
610 = splitBaseType.Ty->getAs<ObjCObjectType>()) {
611 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
614 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
615 splitBaseType.Quals),
616 getTypeArgsAsWritten(),
621 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
622 const ASTContext &ctx) const {
623 if (!isKindOfType() && qual_empty())
626 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
627 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
633 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f);
635 /// Visitor used by simpleTransform() to perform the transformation.
637 struct SimpleTransformVisitor
638 : public TypeVisitor<SimpleTransformVisitor<F>, QualType> {
642 QualType recurse(QualType type) {
643 return simpleTransform(Ctx, type, std::move(TheFunc));
647 SimpleTransformVisitor(ASTContext &ctx, F &&f) : Ctx(ctx), TheFunc(std::move(f)) { }
649 // None of the clients of this transformation can occur where
650 // there are dependent types, so skip dependent types.
651 #define TYPE(Class, Base)
652 #define DEPENDENT_TYPE(Class, Base) \
653 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
654 #include "clang/AST/TypeNodes.def"
656 #define TRIVIAL_TYPE_CLASS(Class) \
657 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
659 TRIVIAL_TYPE_CLASS(Builtin)
661 QualType VisitComplexType(const ComplexType *T) {
662 QualType elementType = recurse(T->getElementType());
663 if (elementType.isNull())
666 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
667 return QualType(T, 0);
669 return Ctx.getComplexType(elementType);
672 QualType VisitPointerType(const PointerType *T) {
673 QualType pointeeType = recurse(T->getPointeeType());
674 if (pointeeType.isNull())
677 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
678 return QualType(T, 0);
680 return Ctx.getPointerType(pointeeType);
683 QualType VisitBlockPointerType(const BlockPointerType *T) {
684 QualType pointeeType = recurse(T->getPointeeType());
685 if (pointeeType.isNull())
688 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
689 return QualType(T, 0);
691 return Ctx.getBlockPointerType(pointeeType);
694 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
695 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
696 if (pointeeType.isNull())
699 if (pointeeType.getAsOpaquePtr()
700 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
701 return QualType(T, 0);
703 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
706 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
707 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
708 if (pointeeType.isNull())
711 if (pointeeType.getAsOpaquePtr()
712 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
713 return QualType(T, 0);
715 return Ctx.getRValueReferenceType(pointeeType);
718 QualType VisitMemberPointerType(const MemberPointerType *T) {
719 QualType pointeeType = recurse(T->getPointeeType());
720 if (pointeeType.isNull())
723 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
724 return QualType(T, 0);
726 return Ctx.getMemberPointerType(pointeeType, T->getClass());
729 QualType VisitConstantArrayType(const ConstantArrayType *T) {
730 QualType elementType = recurse(T->getElementType());
731 if (elementType.isNull())
734 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
735 return QualType(T, 0);
737 return Ctx.getConstantArrayType(elementType, T->getSize(),
738 T->getSizeModifier(),
739 T->getIndexTypeCVRQualifiers());
742 QualType VisitVariableArrayType(const VariableArrayType *T) {
743 QualType elementType = recurse(T->getElementType());
744 if (elementType.isNull())
747 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
748 return QualType(T, 0);
750 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
751 T->getSizeModifier(),
752 T->getIndexTypeCVRQualifiers(),
753 T->getBracketsRange());
756 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
757 QualType elementType = recurse(T->getElementType());
758 if (elementType.isNull())
761 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
762 return QualType(T, 0);
764 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
765 T->getIndexTypeCVRQualifiers());
768 QualType VisitVectorType(const VectorType *T) {
769 QualType elementType = recurse(T->getElementType());
770 if (elementType.isNull())
773 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
774 return QualType(T, 0);
776 return Ctx.getVectorType(elementType, T->getNumElements(),
780 QualType VisitExtVectorType(const ExtVectorType *T) {
781 QualType elementType = recurse(T->getElementType());
782 if (elementType.isNull())
785 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
786 return QualType(T, 0);
788 return Ctx.getExtVectorType(elementType, T->getNumElements());
791 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
792 QualType returnType = recurse(T->getReturnType());
793 if (returnType.isNull())
796 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
797 return QualType(T, 0);
799 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
802 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
803 QualType returnType = recurse(T->getReturnType());
804 if (returnType.isNull())
807 // Transform parameter types.
808 SmallVector<QualType, 4> paramTypes;
809 bool paramChanged = false;
810 for (auto paramType : T->getParamTypes()) {
811 QualType newParamType = recurse(paramType);
812 if (newParamType.isNull())
815 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
818 paramTypes.push_back(newParamType);
821 // Transform extended info.
822 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
823 bool exceptionChanged = false;
824 if (info.ExceptionSpec.Type == EST_Dynamic) {
825 SmallVector<QualType, 4> exceptionTypes;
826 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
827 QualType newExceptionType = recurse(exceptionType);
828 if (newExceptionType.isNull())
831 if (newExceptionType.getAsOpaquePtr()
832 != exceptionType.getAsOpaquePtr())
833 exceptionChanged = true;
835 exceptionTypes.push_back(newExceptionType);
838 if (exceptionChanged) {
839 unsigned size = sizeof(QualType) * exceptionTypes.size();
840 void *mem = Ctx.Allocate(size, llvm::alignOf<QualType>());
841 memcpy(mem, exceptionTypes.data(), size);
842 info.ExceptionSpec.Exceptions
843 = llvm::makeArrayRef((QualType *)mem, exceptionTypes.size());
847 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
848 !paramChanged && !exceptionChanged)
849 return QualType(T, 0);
851 return Ctx.getFunctionType(returnType, paramTypes, info);
854 QualType VisitParenType(const ParenType *T) {
855 QualType innerType = recurse(T->getInnerType());
856 if (innerType.isNull())
859 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
860 return QualType(T, 0);
862 return Ctx.getParenType(innerType);
865 TRIVIAL_TYPE_CLASS(Typedef)
867 QualType VisitAdjustedType(const AdjustedType *T) {
868 QualType originalType = recurse(T->getOriginalType());
869 if (originalType.isNull())
872 QualType adjustedType = recurse(T->getAdjustedType());
873 if (adjustedType.isNull())
876 if (originalType.getAsOpaquePtr()
877 == T->getOriginalType().getAsOpaquePtr() &&
878 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
879 return QualType(T, 0);
881 return Ctx.getAdjustedType(originalType, adjustedType);
884 QualType VisitDecayedType(const DecayedType *T) {
885 QualType originalType = recurse(T->getOriginalType());
886 if (originalType.isNull())
889 if (originalType.getAsOpaquePtr()
890 == T->getOriginalType().getAsOpaquePtr())
891 return QualType(T, 0);
893 return Ctx.getDecayedType(originalType);
896 TRIVIAL_TYPE_CLASS(TypeOfExpr)
897 TRIVIAL_TYPE_CLASS(TypeOf)
898 TRIVIAL_TYPE_CLASS(Decltype)
899 TRIVIAL_TYPE_CLASS(UnaryTransform)
900 TRIVIAL_TYPE_CLASS(Record)
901 TRIVIAL_TYPE_CLASS(Enum)
903 // FIXME: Non-trivial to implement, but important for C++
904 TRIVIAL_TYPE_CLASS(Elaborated)
906 QualType VisitAttributedType(const AttributedType *T) {
907 QualType modifiedType = recurse(T->getModifiedType());
908 if (modifiedType.isNull())
911 QualType equivalentType = recurse(T->getEquivalentType());
912 if (equivalentType.isNull())
915 if (modifiedType.getAsOpaquePtr()
916 == T->getModifiedType().getAsOpaquePtr() &&
917 equivalentType.getAsOpaquePtr()
918 == T->getEquivalentType().getAsOpaquePtr())
919 return QualType(T, 0);
921 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
925 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
926 QualType replacementType = recurse(T->getReplacementType());
927 if (replacementType.isNull())
930 if (replacementType.getAsOpaquePtr()
931 == T->getReplacementType().getAsOpaquePtr())
932 return QualType(T, 0);
934 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
938 // FIXME: Non-trivial to implement, but important for C++
939 TRIVIAL_TYPE_CLASS(TemplateSpecialization)
941 QualType VisitAutoType(const AutoType *T) {
943 return QualType(T, 0);
945 QualType deducedType = recurse(T->getDeducedType());
946 if (deducedType.isNull())
949 if (deducedType.getAsOpaquePtr()
950 == T->getDeducedType().getAsOpaquePtr())
951 return QualType(T, 0);
953 return Ctx.getAutoType(deducedType, T->isDecltypeAuto(),
954 T->isDependentType());
957 // FIXME: Non-trivial to implement, but important for C++
958 TRIVIAL_TYPE_CLASS(PackExpansion)
960 QualType VisitObjCObjectType(const ObjCObjectType *T) {
961 QualType baseType = recurse(T->getBaseType());
962 if (baseType.isNull())
965 // Transform type arguments.
966 bool typeArgChanged = false;
967 SmallVector<QualType, 4> typeArgs;
968 for (auto typeArg : T->getTypeArgsAsWritten()) {
969 QualType newTypeArg = recurse(typeArg);
970 if (newTypeArg.isNull())
973 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
974 typeArgChanged = true;
976 typeArgs.push_back(newTypeArg);
979 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
981 return QualType(T, 0);
983 return Ctx.getObjCObjectType(baseType, typeArgs,
984 llvm::makeArrayRef(T->qual_begin(),
985 T->getNumProtocols()),
986 T->isKindOfTypeAsWritten());
989 TRIVIAL_TYPE_CLASS(ObjCInterface)
991 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
992 QualType pointeeType = recurse(T->getPointeeType());
993 if (pointeeType.isNull())
996 if (pointeeType.getAsOpaquePtr()
997 == T->getPointeeType().getAsOpaquePtr())
998 return QualType(T, 0);
1000 return Ctx.getObjCObjectPointerType(pointeeType);
1003 QualType VisitAtomicType(const AtomicType *T) {
1004 QualType valueType = recurse(T->getValueType());
1005 if (valueType.isNull())
1008 if (valueType.getAsOpaquePtr()
1009 == T->getValueType().getAsOpaquePtr())
1010 return QualType(T, 0);
1012 return Ctx.getAtomicType(valueType);
1015 #undef TRIVIAL_TYPE_CLASS
1018 /// Perform a simple type transformation that does not change the
1019 /// semantics of the type.
1020 template<typename F>
1021 QualType simpleTransform(ASTContext &ctx, QualType type, F &&f) {
1022 // Transform the type. If it changed, return the transformed result.
1023 QualType transformed = f(type);
1024 if (transformed.getAsOpaquePtr() != type.getAsOpaquePtr())
1027 // Split out the qualifiers from the type.
1028 SplitQualType splitType = type.split();
1030 // Visit the type itself.
1031 SimpleTransformVisitor<F> visitor(ctx, std::move(f));
1032 QualType result = visitor.Visit(splitType.Ty);
1033 if (result.isNull())
1036 // Reconstruct the transformed type by applying the local qualifiers
1037 // from the split type.
1038 return ctx.getQualifiedType(result, splitType.Quals);
1041 } // end anonymous namespace
1043 /// Substitute the given type arguments for Objective-C type
1044 /// parameters within the given type, recursively.
1045 QualType QualType::substObjCTypeArgs(
1047 ArrayRef<QualType> typeArgs,
1048 ObjCSubstitutionContext context) const {
1049 return simpleTransform(ctx, *this,
1050 [&](QualType type) -> QualType {
1051 SplitQualType splitType = type.split();
1053 // Replace an Objective-C type parameter reference with the corresponding
1055 if (const auto *typedefTy = dyn_cast<TypedefType>(splitType.Ty)) {
1056 if (auto *typeParam = dyn_cast<ObjCTypeParamDecl>(typedefTy->getDecl())) {
1057 // If we have type arguments, use them.
1058 if (!typeArgs.empty()) {
1059 // FIXME: Introduce SubstObjCTypeParamType ?
1060 QualType argType = typeArgs[typeParam->getIndex()];
1061 return ctx.getQualifiedType(argType, splitType.Quals);
1065 case ObjCSubstitutionContext::Ordinary:
1066 case ObjCSubstitutionContext::Parameter:
1067 case ObjCSubstitutionContext::Superclass:
1068 // Substitute the bound.
1069 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1072 case ObjCSubstitutionContext::Result:
1073 case ObjCSubstitutionContext::Property: {
1074 // Substitute the __kindof form of the underlying type.
1075 const auto *objPtr = typeParam->getUnderlyingType()
1076 ->castAs<ObjCObjectPointerType>();
1078 // __kindof types, id, and Class don't need an additional
1080 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1081 return ctx.getQualifiedType(typeParam->getUnderlyingType(),
1085 const auto *obj = objPtr->getObjectType();
1086 QualType resultTy = ctx.getObjCObjectType(obj->getBaseType(),
1087 obj->getTypeArgsAsWritten(),
1088 obj->getProtocols(),
1091 // Rebuild object pointer type.
1092 resultTy = ctx.getObjCObjectPointerType(resultTy);
1093 return ctx.getQualifiedType(resultTy, splitType.Quals);
1099 // If we have a function type, update the context appropriately.
1100 if (const auto *funcType = dyn_cast<FunctionType>(splitType.Ty)) {
1101 // Substitute result type.
1102 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1105 ObjCSubstitutionContext::Result);
1106 if (returnType.isNull())
1109 // Handle non-prototyped functions, which only substitute into the result
1111 if (isa<FunctionNoProtoType>(funcType)) {
1112 // If the return type was unchanged, do nothing.
1113 if (returnType.getAsOpaquePtr()
1114 == funcType->getReturnType().getAsOpaquePtr())
1117 // Otherwise, build a new type.
1118 return ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1121 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1123 // Transform parameter types.
1124 SmallVector<QualType, 4> paramTypes;
1125 bool paramChanged = false;
1126 for (auto paramType : funcProtoType->getParamTypes()) {
1127 QualType newParamType = paramType.substObjCTypeArgs(
1130 ObjCSubstitutionContext::Parameter);
1131 if (newParamType.isNull())
1134 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1135 paramChanged = true;
1137 paramTypes.push_back(newParamType);
1140 // Transform extended info.
1141 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1142 bool exceptionChanged = false;
1143 if (info.ExceptionSpec.Type == EST_Dynamic) {
1144 SmallVector<QualType, 4> exceptionTypes;
1145 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1146 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1149 ObjCSubstitutionContext::Ordinary);
1150 if (newExceptionType.isNull())
1153 if (newExceptionType.getAsOpaquePtr()
1154 != exceptionType.getAsOpaquePtr())
1155 exceptionChanged = true;
1157 exceptionTypes.push_back(newExceptionType);
1160 if (exceptionChanged) {
1161 unsigned size = sizeof(QualType) * exceptionTypes.size();
1162 void *mem = ctx.Allocate(size, llvm::alignOf<QualType>());
1163 memcpy(mem, exceptionTypes.data(), size);
1164 info.ExceptionSpec.Exceptions
1165 = llvm::makeArrayRef((QualType *)mem, exceptionTypes.size());
1169 if (returnType.getAsOpaquePtr()
1170 == funcProtoType->getReturnType().getAsOpaquePtr() &&
1171 !paramChanged && !exceptionChanged)
1174 return ctx.getFunctionType(returnType, paramTypes, info);
1177 // Substitute into the type arguments of a specialized Objective-C object
1179 if (const auto *objcObjectType = dyn_cast<ObjCObjectType>(splitType.Ty)) {
1180 if (objcObjectType->isSpecializedAsWritten()) {
1181 SmallVector<QualType, 4> newTypeArgs;
1182 bool anyChanged = false;
1183 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1184 QualType newTypeArg = typeArg.substObjCTypeArgs(
1186 ObjCSubstitutionContext::Ordinary);
1187 if (newTypeArg.isNull())
1190 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1191 // If we're substituting based on an unspecialized context type,
1192 // produce an unspecialized type.
1193 ArrayRef<ObjCProtocolDecl *> protocols(
1194 objcObjectType->qual_begin(),
1195 objcObjectType->getNumProtocols());
1196 if (typeArgs.empty() &&
1197 context != ObjCSubstitutionContext::Superclass) {
1198 return ctx.getObjCObjectType(
1199 objcObjectType->getBaseType(), { },
1201 objcObjectType->isKindOfTypeAsWritten());
1207 newTypeArgs.push_back(newTypeArg);
1211 ArrayRef<ObjCProtocolDecl *> protocols(
1212 objcObjectType->qual_begin(),
1213 objcObjectType->getNumProtocols());
1214 return ctx.getObjCObjectType(objcObjectType->getBaseType(),
1215 newTypeArgs, protocols,
1216 objcObjectType->isKindOfTypeAsWritten());
1227 QualType QualType::substObjCMemberType(QualType objectType,
1228 const DeclContext *dc,
1229 ObjCSubstitutionContext context) const {
1230 if (auto subs = objectType->getObjCSubstitutions(dc))
1231 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1236 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1237 // FIXME: Because ASTContext::getAttributedType() is non-const.
1238 auto &ctx = const_cast<ASTContext &>(constCtx);
1239 return simpleTransform(ctx, *this,
1240 [&](QualType type) -> QualType {
1241 SplitQualType splitType = type.split();
1242 if (auto *objType = splitType.Ty->getAs<ObjCObjectType>()) {
1243 if (!objType->isKindOfType())
1247 = objType->getBaseType().stripObjCKindOfType(ctx);
1248 return ctx.getQualifiedType(
1249 ctx.getObjCObjectType(baseType,
1250 objType->getTypeArgsAsWritten(),
1251 objType->getProtocols(),
1252 /*isKindOf=*/false),
1260 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
1261 const DeclContext *dc) const {
1262 // Look through method scopes.
1263 if (auto method = dyn_cast<ObjCMethodDecl>(dc))
1264 dc = method->getDeclContext();
1266 // Find the class or category in which the type we're substituting
1268 const ObjCInterfaceDecl *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1269 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1270 ObjCTypeParamList *dcTypeParams = nullptr;
1272 // If the class does not have any type parameters, there's no
1273 // substitution to do.
1274 dcTypeParams = dcClassDecl->getTypeParamList();
1278 // If we are in neither a class mor a category, there's no
1279 // substitution to perform.
1280 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1281 if (!dcCategoryDecl)
1284 // If the category does not have any type parameters, there's no
1285 // substitution to do.
1286 dcTypeParams = dcCategoryDecl->getTypeParamList();
1290 dcClassDecl = dcCategoryDecl->getClassInterface();
1294 assert(dcTypeParams && "No substitutions to perform");
1295 assert(dcClassDecl && "No class context");
1297 // Find the underlying object type.
1298 const ObjCObjectType *objectType;
1299 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1300 objectType = objectPointerType->getObjectType();
1301 } else if (getAs<BlockPointerType>()) {
1302 ASTContext &ctx = dc->getParentASTContext();
1303 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, { })
1304 ->castAs<ObjCObjectType>();;
1306 objectType = getAs<ObjCObjectType>();
1309 /// Extract the class from the receiver object type.
1310 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1312 if (!curClassDecl) {
1313 // If we don't have a context type (e.g., this is "id" or some
1314 // variant thereof), substitute the bounds.
1315 return llvm::ArrayRef<QualType>();
1318 // Follow the superclass chain until we've mapped the receiver type
1319 // to the same class as the context.
1320 while (curClassDecl != dcClassDecl) {
1321 // Map to the superclass type.
1322 QualType superType = objectType->getSuperClassType();
1323 if (superType.isNull()) {
1324 objectType = nullptr;
1328 objectType = superType->castAs<ObjCObjectType>();
1329 curClassDecl = objectType->getInterface();
1332 // If we don't have a receiver type, or the receiver type does not
1333 // have type arguments, substitute in the defaults.
1334 if (!objectType || objectType->isUnspecialized()) {
1335 return llvm::ArrayRef<QualType>();
1338 // The receiver type has the type arguments we want.
1339 return objectType->getTypeArgs();
1342 bool Type::acceptsObjCTypeParams() const {
1343 if (auto *IfaceT = getAsObjCInterfaceType()) {
1344 if (auto *ID = IfaceT->getInterface()) {
1345 if (ID->getTypeParamList())
1353 void ObjCObjectType::computeSuperClassTypeSlow() const {
1354 // Retrieve the class declaration for this type. If there isn't one
1355 // (e.g., this is some variant of "id" or "Class"), then there is no
1357 ObjCInterfaceDecl *classDecl = getInterface();
1359 CachedSuperClassType.setInt(true);
1363 // Extract the superclass type.
1364 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1365 if (!superClassObjTy) {
1366 CachedSuperClassType.setInt(true);
1370 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1371 if (!superClassDecl) {
1372 CachedSuperClassType.setInt(true);
1376 // If the superclass doesn't have type parameters, then there is no
1377 // substitution to perform.
1378 QualType superClassType(superClassObjTy, 0);
1379 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1380 if (!superClassTypeParams) {
1381 CachedSuperClassType.setPointerAndInt(
1382 superClassType->castAs<ObjCObjectType>(), true);
1386 // If the superclass reference is unspecialized, return it.
1387 if (superClassObjTy->isUnspecialized()) {
1388 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1392 // If the subclass is not parameterized, there aren't any type
1393 // parameters in the superclass reference to substitute.
1394 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1396 CachedSuperClassType.setPointerAndInt(
1397 superClassType->castAs<ObjCObjectType>(), true);
1401 // If the subclass type isn't specialized, return the unspecialized
1403 if (isUnspecialized()) {
1404 QualType unspecializedSuper
1405 = classDecl->getASTContext().getObjCInterfaceType(
1406 superClassObjTy->getInterface());
1407 CachedSuperClassType.setPointerAndInt(
1408 unspecializedSuper->castAs<ObjCObjectType>(),
1413 // Substitute the provided type arguments into the superclass type.
1414 ArrayRef<QualType> typeArgs = getTypeArgs();
1415 assert(typeArgs.size() == typeParams->size());
1416 CachedSuperClassType.setPointerAndInt(
1417 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1418 ObjCSubstitutionContext::Superclass)
1419 ->castAs<ObjCObjectType>(),
1423 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1424 if (auto interfaceDecl = getObjectType()->getInterface()) {
1425 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1426 ->castAs<ObjCInterfaceType>();
1432 QualType ObjCObjectPointerType::getSuperClassType() const {
1433 QualType superObjectType = getObjectType()->getSuperClassType();
1434 if (superObjectType.isNull())
1435 return superObjectType;
1437 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1438 return ctx.getObjCObjectPointerType(superObjectType);
1441 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1442 // There is no sugar for ObjCObjectType's, just return the canonical
1443 // type pointer if it is the right class. There is no typedef information to
1444 // return and these cannot be Address-space qualified.
1445 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
1446 if (T->getNumProtocols() && T->getInterface())
1451 bool Type::isObjCQualifiedInterfaceType() const {
1452 return getAsObjCQualifiedInterfaceType() != nullptr;
1455 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1456 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1457 // type pointer if it is the right class.
1458 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1459 if (OPT->isObjCQualifiedIdType())
1465 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1466 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1467 // type pointer if it is the right class.
1468 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1469 if (OPT->isObjCQualifiedClassType())
1475 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1476 if (const ObjCObjectType *OT = getAs<ObjCObjectType>()) {
1477 if (OT->getInterface())
1482 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1483 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
1484 if (OPT->getInterfaceType())
1490 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1491 QualType PointeeType;
1492 if (const PointerType *PT = getAs<PointerType>())
1493 PointeeType = PT->getPointeeType();
1494 else if (const ReferenceType *RT = getAs<ReferenceType>())
1495 PointeeType = RT->getPointeeType();
1499 if (const RecordType *RT = PointeeType->getAs<RecordType>())
1500 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1505 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1506 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1509 TagDecl *Type::getAsTagDecl() const {
1510 if (const auto *TT = getAs<TagType>())
1511 return cast<TagDecl>(TT->getDecl());
1512 if (const auto *Injected = getAs<InjectedClassNameType>())
1513 return Injected->getDecl();
1519 class GetContainedAutoVisitor :
1520 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
1522 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
1523 AutoType *Visit(QualType T) {
1526 return Visit(T.getTypePtr());
1529 // The 'auto' type itself.
1530 AutoType *VisitAutoType(const AutoType *AT) {
1531 return const_cast<AutoType*>(AT);
1534 // Only these types can contain the desired 'auto' type.
1535 AutoType *VisitPointerType(const PointerType *T) {
1536 return Visit(T->getPointeeType());
1538 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
1539 return Visit(T->getPointeeType());
1541 AutoType *VisitReferenceType(const ReferenceType *T) {
1542 return Visit(T->getPointeeTypeAsWritten());
1544 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
1545 return Visit(T->getPointeeType());
1547 AutoType *VisitArrayType(const ArrayType *T) {
1548 return Visit(T->getElementType());
1550 AutoType *VisitDependentSizedExtVectorType(
1551 const DependentSizedExtVectorType *T) {
1552 return Visit(T->getElementType());
1554 AutoType *VisitVectorType(const VectorType *T) {
1555 return Visit(T->getElementType());
1557 AutoType *VisitFunctionType(const FunctionType *T) {
1558 return Visit(T->getReturnType());
1560 AutoType *VisitParenType(const ParenType *T) {
1561 return Visit(T->getInnerType());
1563 AutoType *VisitAttributedType(const AttributedType *T) {
1564 return Visit(T->getModifiedType());
1566 AutoType *VisitAdjustedType(const AdjustedType *T) {
1567 return Visit(T->getOriginalType());
1572 AutoType *Type::getContainedAutoType() const {
1573 return GetContainedAutoVisitor().Visit(this);
1576 bool Type::hasIntegerRepresentation() const {
1577 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1578 return VT->getElementType()->isIntegerType();
1580 return isIntegerType();
1583 /// \brief Determine whether this type is an integral type.
1585 /// This routine determines whether the given type is an integral type per
1586 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1587 /// term "integral type", it has a similar term "integer type", and in C++
1588 /// the two terms are equivalent. However, C's "integer type" includes
1589 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1590 /// parameter is used to determine whether we should be following the C or
1591 /// C++ rules when determining whether this type is an integral/integer type.
1593 /// For cases where C permits "an integer type" and C++ permits "an integral
1594 /// type", use this routine.
1596 /// For cases where C permits "an integer type" and C++ permits "an integral
1597 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1599 /// \param Ctx The context in which this type occurs.
1601 /// \returns true if the type is considered an integral type, false otherwise.
1602 bool Type::isIntegralType(ASTContext &Ctx) const {
1603 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1604 return BT->getKind() >= BuiltinType::Bool &&
1605 BT->getKind() <= BuiltinType::Int128;
1607 // Complete enum types are integral in C.
1608 if (!Ctx.getLangOpts().CPlusPlus)
1609 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1610 return ET->getDecl()->isComplete();
1616 bool Type::isIntegralOrUnscopedEnumerationType() const {
1617 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1618 return BT->getKind() >= BuiltinType::Bool &&
1619 BT->getKind() <= BuiltinType::Int128;
1621 // Check for a complete enum type; incomplete enum types are not properly an
1622 // enumeration type in the sense required here.
1623 // C++0x: However, if the underlying type of the enum is fixed, it is
1624 // considered complete.
1625 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1626 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1633 bool Type::isCharType() const {
1634 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1635 return BT->getKind() == BuiltinType::Char_U ||
1636 BT->getKind() == BuiltinType::UChar ||
1637 BT->getKind() == BuiltinType::Char_S ||
1638 BT->getKind() == BuiltinType::SChar;
1642 bool Type::isWideCharType() const {
1643 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1644 return BT->getKind() == BuiltinType::WChar_S ||
1645 BT->getKind() == BuiltinType::WChar_U;
1649 bool Type::isChar16Type() const {
1650 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1651 return BT->getKind() == BuiltinType::Char16;
1655 bool Type::isChar32Type() const {
1656 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1657 return BT->getKind() == BuiltinType::Char32;
1661 /// \brief Determine whether this type is any of the built-in character
1663 bool Type::isAnyCharacterType() const {
1664 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
1665 if (!BT) return false;
1666 switch (BT->getKind()) {
1667 default: return false;
1668 case BuiltinType::Char_U:
1669 case BuiltinType::UChar:
1670 case BuiltinType::WChar_U:
1671 case BuiltinType::Char16:
1672 case BuiltinType::Char32:
1673 case BuiltinType::Char_S:
1674 case BuiltinType::SChar:
1675 case BuiltinType::WChar_S:
1680 /// isSignedIntegerType - Return true if this is an integer type that is
1681 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1682 /// an enum decl which has a signed representation
1683 bool Type::isSignedIntegerType() const {
1684 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1685 return BT->getKind() >= BuiltinType::Char_S &&
1686 BT->getKind() <= BuiltinType::Int128;
1689 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1690 // Incomplete enum types are not treated as integer types.
1691 // FIXME: In C++, enum types are never integer types.
1692 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1693 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1699 bool Type::isSignedIntegerOrEnumerationType() const {
1700 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1701 return BT->getKind() >= BuiltinType::Char_S &&
1702 BT->getKind() <= BuiltinType::Int128;
1705 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1706 if (ET->getDecl()->isComplete())
1707 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1713 bool Type::hasSignedIntegerRepresentation() const {
1714 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1715 return VT->getElementType()->isSignedIntegerOrEnumerationType();
1717 return isSignedIntegerOrEnumerationType();
1720 /// isUnsignedIntegerType - Return true if this is an integer type that is
1721 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1722 /// decl which has an unsigned representation
1723 bool Type::isUnsignedIntegerType() const {
1724 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1725 return BT->getKind() >= BuiltinType::Bool &&
1726 BT->getKind() <= BuiltinType::UInt128;
1729 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1730 // Incomplete enum types are not treated as integer types.
1731 // FIXME: In C++, enum types are never integer types.
1732 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1733 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1739 bool Type::isUnsignedIntegerOrEnumerationType() const {
1740 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1741 return BT->getKind() >= BuiltinType::Bool &&
1742 BT->getKind() <= BuiltinType::UInt128;
1745 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1746 if (ET->getDecl()->isComplete())
1747 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1753 bool Type::hasUnsignedIntegerRepresentation() const {
1754 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1755 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
1757 return isUnsignedIntegerOrEnumerationType();
1760 bool Type::isFloatingType() const {
1761 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1762 return BT->getKind() >= BuiltinType::Half &&
1763 BT->getKind() <= BuiltinType::LongDouble;
1764 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
1765 return CT->getElementType()->isFloatingType();
1769 bool Type::hasFloatingRepresentation() const {
1770 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
1771 return VT->getElementType()->isFloatingType();
1773 return isFloatingType();
1776 bool Type::isRealFloatingType() const {
1777 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1778 return BT->isFloatingPoint();
1782 bool Type::isRealType() const {
1783 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1784 return BT->getKind() >= BuiltinType::Bool &&
1785 BT->getKind() <= BuiltinType::LongDouble;
1786 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1787 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1791 bool Type::isArithmeticType() const {
1792 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1793 return BT->getKind() >= BuiltinType::Bool &&
1794 BT->getKind() <= BuiltinType::LongDouble;
1795 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
1796 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
1797 // If a body isn't seen by the time we get here, return false.
1799 // C++0x: Enumerations are not arithmetic types. For now, just return
1800 // false for scoped enumerations since that will disable any
1801 // unwanted implicit conversions.
1802 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
1803 return isa<ComplexType>(CanonicalType);
1806 Type::ScalarTypeKind Type::getScalarTypeKind() const {
1807 assert(isScalarType());
1809 const Type *T = CanonicalType.getTypePtr();
1810 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
1811 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
1812 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
1813 if (BT->isInteger()) return STK_Integral;
1814 if (BT->isFloatingPoint()) return STK_Floating;
1815 llvm_unreachable("unknown scalar builtin type");
1816 } else if (isa<PointerType>(T)) {
1817 return STK_CPointer;
1818 } else if (isa<BlockPointerType>(T)) {
1819 return STK_BlockPointer;
1820 } else if (isa<ObjCObjectPointerType>(T)) {
1821 return STK_ObjCObjectPointer;
1822 } else if (isa<MemberPointerType>(T)) {
1823 return STK_MemberPointer;
1824 } else if (isa<EnumType>(T)) {
1825 assert(cast<EnumType>(T)->getDecl()->isComplete());
1826 return STK_Integral;
1827 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
1828 if (CT->getElementType()->isRealFloatingType())
1829 return STK_FloatingComplex;
1830 return STK_IntegralComplex;
1833 llvm_unreachable("unknown scalar type");
1836 /// \brief Determines whether the type is a C++ aggregate type or C
1837 /// aggregate or union type.
1839 /// An aggregate type is an array or a class type (struct, union, or
1840 /// class) that has no user-declared constructors, no private or
1841 /// protected non-static data members, no base classes, and no virtual
1842 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
1843 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
1844 /// includes union types.
1845 bool Type::isAggregateType() const {
1846 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
1847 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
1848 return ClassDecl->isAggregate();
1853 return isa<ArrayType>(CanonicalType);
1856 /// isConstantSizeType - Return true if this is not a variable sized type,
1857 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1858 /// incomplete types or dependent types.
1859 bool Type::isConstantSizeType() const {
1860 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
1861 assert(!isDependentType() && "This doesn't make sense for dependent types");
1862 // The VAT must have a size, as it is known to be complete.
1863 return !isa<VariableArrayType>(CanonicalType);
1866 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
1867 /// - a type that can describe objects, but which lacks information needed to
1868 /// determine its size.
1869 bool Type::isIncompleteType(NamedDecl **Def) const {
1873 switch (CanonicalType->getTypeClass()) {
1874 default: return false;
1876 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
1878 return isVoidType();
1880 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
1884 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
1885 if (EnumD->isFixed())
1888 return !EnumD->isCompleteDefinition();
1891 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
1892 // forward declaration, but not a full definition (C99 6.2.5p22).
1893 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
1896 return !Rec->isCompleteDefinition();
1899 // An array is incomplete if its element type is incomplete
1900 // (C++ [dcl.array]p1).
1901 // We don't handle variable arrays (they're not allowed in C++) or
1902 // dependent-sized arrays (dependent types are never treated as incomplete).
1903 return cast<ArrayType>(CanonicalType)->getElementType()
1904 ->isIncompleteType(Def);
1905 case IncompleteArray:
1906 // An array of unknown size is an incomplete type (C99 6.2.5p22).
1909 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
1910 ->isIncompleteType(Def);
1911 case ObjCInterface: {
1912 // ObjC interfaces are incomplete if they are @class, not @interface.
1913 ObjCInterfaceDecl *Interface
1914 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
1917 return !Interface->hasDefinition();
1922 bool QualType::isPODType(ASTContext &Context) const {
1923 // C++11 has a more relaxed definition of POD.
1924 if (Context.getLangOpts().CPlusPlus11)
1925 return isCXX11PODType(Context);
1927 return isCXX98PODType(Context);
1930 bool QualType::isCXX98PODType(ASTContext &Context) const {
1931 // The compiler shouldn't query this for incomplete types, but the user might.
1932 // We return false for that case. Except for incomplete arrays of PODs, which
1933 // are PODs according to the standard.
1937 if ((*this)->isIncompleteArrayType())
1938 return Context.getBaseElementType(*this).isCXX98PODType(Context);
1940 if ((*this)->isIncompleteType())
1943 if (Context.getLangOpts().ObjCAutoRefCount) {
1944 switch (getObjCLifetime()) {
1945 case Qualifiers::OCL_ExplicitNone:
1948 case Qualifiers::OCL_Strong:
1949 case Qualifiers::OCL_Weak:
1950 case Qualifiers::OCL_Autoreleasing:
1953 case Qualifiers::OCL_None:
1958 QualType CanonicalType = getTypePtr()->CanonicalType;
1959 switch (CanonicalType->getTypeClass()) {
1960 // Everything not explicitly mentioned is not POD.
1961 default: return false;
1962 case Type::VariableArray:
1963 case Type::ConstantArray:
1964 // IncompleteArray is handled above.
1965 return Context.getBaseElementType(*this).isCXX98PODType(Context);
1967 case Type::ObjCObjectPointer:
1968 case Type::BlockPointer:
1972 case Type::MemberPointer:
1974 case Type::ExtVector:
1981 if (CXXRecordDecl *ClassDecl
1982 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1983 return ClassDecl->isPOD();
1985 // C struct/union is POD.
1990 bool QualType::isTrivialType(ASTContext &Context) const {
1991 // The compiler shouldn't query this for incomplete types, but the user might.
1992 // We return false for that case. Except for incomplete arrays of PODs, which
1993 // are PODs according to the standard.
1997 if ((*this)->isArrayType())
1998 return Context.getBaseElementType(*this).isTrivialType(Context);
2000 // Return false for incomplete types after skipping any incomplete array
2001 // types which are expressly allowed by the standard and thus our API.
2002 if ((*this)->isIncompleteType())
2005 if (Context.getLangOpts().ObjCAutoRefCount) {
2006 switch (getObjCLifetime()) {
2007 case Qualifiers::OCL_ExplicitNone:
2010 case Qualifiers::OCL_Strong:
2011 case Qualifiers::OCL_Weak:
2012 case Qualifiers::OCL_Autoreleasing:
2015 case Qualifiers::OCL_None:
2016 if ((*this)->isObjCLifetimeType())
2022 QualType CanonicalType = getTypePtr()->CanonicalType;
2023 if (CanonicalType->isDependentType())
2026 // C++0x [basic.types]p9:
2027 // Scalar types, trivial class types, arrays of such types, and
2028 // cv-qualified versions of these types are collectively called trivial
2031 // As an extension, Clang treats vector types as Scalar types.
2032 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2034 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2035 if (const CXXRecordDecl *ClassDecl =
2036 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2038 // A trivial class is a class that has a default constructor,
2039 // has no non-trivial default constructors, and is trivially
2041 return ClassDecl->hasDefaultConstructor() &&
2042 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2043 ClassDecl->isTriviallyCopyable();
2049 // No other types can match.
2053 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
2054 if ((*this)->isArrayType())
2055 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2057 if (Context.getLangOpts().ObjCAutoRefCount) {
2058 switch (getObjCLifetime()) {
2059 case Qualifiers::OCL_ExplicitNone:
2062 case Qualifiers::OCL_Strong:
2063 case Qualifiers::OCL_Weak:
2064 case Qualifiers::OCL_Autoreleasing:
2067 case Qualifiers::OCL_None:
2068 if ((*this)->isObjCLifetimeType())
2074 // C++11 [basic.types]p9
2075 // Scalar types, trivially copyable class types, arrays of such types, and
2076 // non-volatile const-qualified versions of these types are collectively
2077 // called trivially copyable types.
2079 QualType CanonicalType = getCanonicalType();
2080 if (CanonicalType->isDependentType())
2083 if (CanonicalType.isVolatileQualified())
2086 // Return false for incomplete types after skipping any incomplete array types
2087 // which are expressly allowed by the standard and thus our API.
2088 if (CanonicalType->isIncompleteType())
2091 // As an extension, Clang treats vector types as Scalar types.
2092 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2095 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
2096 if (const CXXRecordDecl *ClassDecl =
2097 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2098 if (!ClassDecl->isTriviallyCopyable()) return false;
2104 // No other types can match.
2110 bool Type::isLiteralType(const ASTContext &Ctx) const {
2111 if (isDependentType())
2114 // C++1y [basic.types]p10:
2115 // A type is a literal type if it is:
2117 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2120 // C++11 [basic.types]p10:
2121 // A type is a literal type if it is:
2123 // -- an array of literal type other than an array of runtime bound; or
2124 if (isVariableArrayType())
2126 const Type *BaseTy = getBaseElementTypeUnsafe();
2127 assert(BaseTy && "NULL element type");
2129 // Return false for incomplete types after skipping any incomplete array
2130 // types; those are expressly allowed by the standard and thus our API.
2131 if (BaseTy->isIncompleteType())
2134 // C++11 [basic.types]p10:
2135 // A type is a literal type if it is:
2136 // -- a scalar type; or
2137 // As an extension, Clang treats vector types and complex types as
2139 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2140 BaseTy->isAnyComplexType())
2142 // -- a reference type; or
2143 if (BaseTy->isReferenceType())
2145 // -- a class type that has all of the following properties:
2146 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2147 // -- a trivial destructor,
2148 // -- every constructor call and full-expression in the
2149 // brace-or-equal-initializers for non-static data members (if any)
2150 // is a constant expression,
2151 // -- it is an aggregate type or has at least one constexpr
2152 // constructor or constructor template that is not a copy or move
2154 // -- all non-static data members and base classes of literal types
2156 // We resolve DR1361 by ignoring the second bullet.
2157 if (const CXXRecordDecl *ClassDecl =
2158 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2159 return ClassDecl->isLiteral();
2164 // We treat _Atomic T as a literal type if T is a literal type.
2165 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
2166 return AT->getValueType()->isLiteralType(Ctx);
2168 // If this type hasn't been deduced yet, then conservatively assume that
2169 // it'll work out to be a literal type.
2170 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2176 bool Type::isStandardLayoutType() const {
2177 if (isDependentType())
2180 // C++0x [basic.types]p9:
2181 // Scalar types, standard-layout class types, arrays of such types, and
2182 // cv-qualified versions of these types are collectively called
2183 // standard-layout types.
2184 const Type *BaseTy = getBaseElementTypeUnsafe();
2185 assert(BaseTy && "NULL element type");
2187 // Return false for incomplete types after skipping any incomplete array
2188 // types which are expressly allowed by the standard and thus our API.
2189 if (BaseTy->isIncompleteType())
2192 // As an extension, Clang treats vector types as Scalar types.
2193 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2194 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2195 if (const CXXRecordDecl *ClassDecl =
2196 dyn_cast<CXXRecordDecl>(RT->getDecl()))
2197 if (!ClassDecl->isStandardLayout())
2200 // Default to 'true' for non-C++ class types.
2201 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2202 // all the requirements of standard layout classes.
2206 // No other types can match.
2210 // This is effectively the intersection of isTrivialType and
2211 // isStandardLayoutType. We implement it directly to avoid redundant
2212 // conversions from a type to a CXXRecordDecl.
2213 bool QualType::isCXX11PODType(ASTContext &Context) const {
2214 const Type *ty = getTypePtr();
2215 if (ty->isDependentType())
2218 if (Context.getLangOpts().ObjCAutoRefCount) {
2219 switch (getObjCLifetime()) {
2220 case Qualifiers::OCL_ExplicitNone:
2223 case Qualifiers::OCL_Strong:
2224 case Qualifiers::OCL_Weak:
2225 case Qualifiers::OCL_Autoreleasing:
2228 case Qualifiers::OCL_None:
2233 // C++11 [basic.types]p9:
2234 // Scalar types, POD classes, arrays of such types, and cv-qualified
2235 // versions of these types are collectively called trivial types.
2236 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2237 assert(BaseTy && "NULL element type");
2239 // Return false for incomplete types after skipping any incomplete array
2240 // types which are expressly allowed by the standard and thus our API.
2241 if (BaseTy->isIncompleteType())
2244 // As an extension, Clang treats vector types as Scalar types.
2245 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2246 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
2247 if (const CXXRecordDecl *ClassDecl =
2248 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2249 // C++11 [class]p10:
2250 // A POD struct is a non-union class that is both a trivial class [...]
2251 if (!ClassDecl->isTrivial()) return false;
2253 // C++11 [class]p10:
2254 // A POD struct is a non-union class that is both a trivial class and
2255 // a standard-layout class [...]
2256 if (!ClassDecl->isStandardLayout()) return false;
2258 // C++11 [class]p10:
2259 // A POD struct is a non-union class that is both a trivial class and
2260 // a standard-layout class, and has no non-static data members of type
2261 // non-POD struct, non-POD union (or array of such types). [...]
2263 // We don't directly query the recursive aspect as the requiremets for
2264 // both standard-layout classes and trivial classes apply recursively
2271 // No other types can match.
2275 bool Type::isPromotableIntegerType() const {
2276 if (const BuiltinType *BT = getAs<BuiltinType>())
2277 switch (BT->getKind()) {
2278 case BuiltinType::Bool:
2279 case BuiltinType::Char_S:
2280 case BuiltinType::Char_U:
2281 case BuiltinType::SChar:
2282 case BuiltinType::UChar:
2283 case BuiltinType::Short:
2284 case BuiltinType::UShort:
2285 case BuiltinType::WChar_S:
2286 case BuiltinType::WChar_U:
2287 case BuiltinType::Char16:
2288 case BuiltinType::Char32:
2294 // Enumerated types are promotable to their compatible integer types
2295 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2296 if (const EnumType *ET = getAs<EnumType>()){
2297 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2298 || ET->getDecl()->isScoped())
2307 bool Type::isSpecifierType() const {
2308 // Note that this intentionally does not use the canonical type.
2309 switch (getTypeClass()) {
2317 case TemplateTypeParm:
2318 case SubstTemplateTypeParm:
2319 case TemplateSpecialization:
2322 case DependentTemplateSpecialization:
2325 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2332 ElaboratedTypeKeyword
2333 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2335 default: return ETK_None;
2336 case TST_typename: return ETK_Typename;
2337 case TST_class: return ETK_Class;
2338 case TST_struct: return ETK_Struct;
2339 case TST_interface: return ETK_Interface;
2340 case TST_union: return ETK_Union;
2341 case TST_enum: return ETK_Enum;
2346 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2348 case TST_class: return TTK_Class;
2349 case TST_struct: return TTK_Struct;
2350 case TST_interface: return TTK_Interface;
2351 case TST_union: return TTK_Union;
2352 case TST_enum: return TTK_Enum;
2355 llvm_unreachable("Type specifier is not a tag type kind.");
2358 ElaboratedTypeKeyword
2359 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2361 case TTK_Class: return ETK_Class;
2362 case TTK_Struct: return ETK_Struct;
2363 case TTK_Interface: return ETK_Interface;
2364 case TTK_Union: return ETK_Union;
2365 case TTK_Enum: return ETK_Enum;
2367 llvm_unreachable("Unknown tag type kind.");
2371 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2373 case ETK_Class: return TTK_Class;
2374 case ETK_Struct: return TTK_Struct;
2375 case ETK_Interface: return TTK_Interface;
2376 case ETK_Union: return TTK_Union;
2377 case ETK_Enum: return TTK_Enum;
2378 case ETK_None: // Fall through.
2380 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2382 llvm_unreachable("Unknown elaborated type keyword.");
2386 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2398 llvm_unreachable("Unknown elaborated type keyword.");
2401 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2403 case ETK_None: return "";
2404 case ETK_Typename: return "typename";
2405 case ETK_Class: return "class";
2406 case ETK_Struct: return "struct";
2407 case ETK_Interface: return "__interface";
2408 case ETK_Union: return "union";
2409 case ETK_Enum: return "enum";
2412 llvm_unreachable("Unknown elaborated type keyword.");
2415 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2416 ElaboratedTypeKeyword Keyword,
2417 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2418 unsigned NumArgs, const TemplateArgument *Args,
2420 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
2421 /*VariablyModified=*/false,
2422 NNS && NNS->containsUnexpandedParameterPack()),
2423 NNS(NNS), Name(Name), NumArgs(NumArgs) {
2424 assert((!NNS || NNS->isDependent()) &&
2425 "DependentTemplateSpecializatonType requires dependent qualifier");
2426 for (unsigned I = 0; I != NumArgs; ++I) {
2427 if (Args[I].containsUnexpandedParameterPack())
2428 setContainsUnexpandedParameterPack();
2430 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
2435 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2436 const ASTContext &Context,
2437 ElaboratedTypeKeyword Keyword,
2438 NestedNameSpecifier *Qualifier,
2439 const IdentifierInfo *Name,
2441 const TemplateArgument *Args) {
2442 ID.AddInteger(Keyword);
2443 ID.AddPointer(Qualifier);
2444 ID.AddPointer(Name);
2445 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2446 Args[Idx].Profile(ID, Context);
2449 bool Type::isElaboratedTypeSpecifier() const {
2450 ElaboratedTypeKeyword Keyword;
2451 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
2452 Keyword = Elab->getKeyword();
2453 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
2454 Keyword = DepName->getKeyword();
2455 else if (const DependentTemplateSpecializationType *DepTST =
2456 dyn_cast<DependentTemplateSpecializationType>(this))
2457 Keyword = DepTST->getKeyword();
2461 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2464 const char *Type::getTypeClassName() const {
2465 switch (TypeBits.TC) {
2466 #define ABSTRACT_TYPE(Derived, Base)
2467 #define TYPE(Derived, Base) case Derived: return #Derived;
2468 #include "clang/AST/TypeNodes.def"
2471 llvm_unreachable("Invalid type class.");
2474 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2475 switch (getKind()) {
2476 case Void: return "void";
2477 case Bool: return Policy.Bool ? "bool" : "_Bool";
2478 case Char_S: return "char";
2479 case Char_U: return "char";
2480 case SChar: return "signed char";
2481 case Short: return "short";
2482 case Int: return "int";
2483 case Long: return "long";
2484 case LongLong: return "long long";
2485 case Int128: return "__int128";
2486 case UChar: return "unsigned char";
2487 case UShort: return "unsigned short";
2488 case UInt: return "unsigned int";
2489 case ULong: return "unsigned long";
2490 case ULongLong: return "unsigned long long";
2491 case UInt128: return "unsigned __int128";
2492 case Half: return Policy.Half ? "half" : "__fp16";
2493 case Float: return "float";
2494 case Double: return "double";
2495 case LongDouble: return "long double";
2497 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2498 case Char16: return "char16_t";
2499 case Char32: return "char32_t";
2500 case NullPtr: return "nullptr_t";
2501 case Overload: return "<overloaded function type>";
2502 case BoundMember: return "<bound member function type>";
2503 case PseudoObject: return "<pseudo-object type>";
2504 case Dependent: return "<dependent type>";
2505 case UnknownAny: return "<unknown type>";
2506 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
2507 case BuiltinFn: return "<builtin fn type>";
2508 case ObjCId: return "id";
2509 case ObjCClass: return "Class";
2510 case ObjCSel: return "SEL";
2511 case OCLImage1d: return "image1d_t";
2512 case OCLImage1dArray: return "image1d_array_t";
2513 case OCLImage1dBuffer: return "image1d_buffer_t";
2514 case OCLImage2d: return "image2d_t";
2515 case OCLImage2dArray: return "image2d_array_t";
2516 case OCLImage3d: return "image3d_t";
2517 case OCLSampler: return "sampler_t";
2518 case OCLEvent: return "event_t";
2521 llvm_unreachable("Invalid builtin type.");
2524 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
2525 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
2526 return RefType->getPointeeType();
2528 // C++0x [basic.lval]:
2529 // Class prvalues can have cv-qualified types; non-class prvalues always
2530 // have cv-unqualified types.
2532 // See also C99 6.3.2.1p2.
2533 if (!Context.getLangOpts().CPlusPlus ||
2534 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
2535 return getUnqualifiedType();
2540 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
2542 case CC_C: return "cdecl";
2543 case CC_X86StdCall: return "stdcall";
2544 case CC_X86FastCall: return "fastcall";
2545 case CC_X86ThisCall: return "thiscall";
2546 case CC_X86Pascal: return "pascal";
2547 case CC_X86VectorCall: return "vectorcall";
2548 case CC_X86_64Win64: return "ms_abi";
2549 case CC_X86_64SysV: return "sysv_abi";
2550 case CC_AAPCS: return "aapcs";
2551 case CC_AAPCS_VFP: return "aapcs-vfp";
2552 case CC_IntelOclBicc: return "intel_ocl_bicc";
2553 case CC_SpirFunction: return "spir_function";
2554 case CC_SpirKernel: return "spir_kernel";
2557 llvm_unreachable("Invalid calling convention.");
2560 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
2562 const ExtProtoInfo &epi)
2563 : FunctionType(FunctionProto, result, canonical,
2564 result->isDependentType(),
2565 result->isInstantiationDependentType(),
2566 result->isVariablyModifiedType(),
2567 result->containsUnexpandedParameterPack(), epi.ExtInfo),
2568 NumParams(params.size()),
2569 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
2570 ExceptionSpecType(epi.ExceptionSpec.Type),
2571 HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
2572 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
2573 assert(NumParams == params.size() && "function has too many parameters");
2575 FunctionTypeBits.TypeQuals = epi.TypeQuals;
2576 FunctionTypeBits.RefQualifier = epi.RefQualifier;
2578 // Fill in the trailing argument array.
2579 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
2580 for (unsigned i = 0; i != NumParams; ++i) {
2581 if (params[i]->isDependentType())
2583 else if (params[i]->isInstantiationDependentType())
2584 setInstantiationDependent();
2586 if (params[i]->containsUnexpandedParameterPack())
2587 setContainsUnexpandedParameterPack();
2589 argSlot[i] = params[i];
2592 if (getExceptionSpecType() == EST_Dynamic) {
2593 // Fill in the exception array.
2594 QualType *exnSlot = argSlot + NumParams;
2596 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
2597 // Note that a dependent exception specification does *not* make
2598 // a type dependent; it's not even part of the C++ type system.
2599 if (ExceptionType->isInstantiationDependentType())
2600 setInstantiationDependent();
2602 if (ExceptionType->containsUnexpandedParameterPack())
2603 setContainsUnexpandedParameterPack();
2605 exnSlot[I++] = ExceptionType;
2607 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
2608 // Store the noexcept expression and context.
2609 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
2610 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
2612 if (epi.ExceptionSpec.NoexceptExpr) {
2613 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
2614 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
2615 setInstantiationDependent();
2617 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
2618 setContainsUnexpandedParameterPack();
2620 } else if (getExceptionSpecType() == EST_Uninstantiated) {
2621 // Store the function decl from which we will resolve our
2622 // exception specification.
2623 FunctionDecl **slot =
2624 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2625 slot[0] = epi.ExceptionSpec.SourceDecl;
2626 slot[1] = epi.ExceptionSpec.SourceTemplate;
2627 // This exception specification doesn't make the type dependent, because
2628 // it's not instantiated as part of instantiating the type.
2629 } else if (getExceptionSpecType() == EST_Unevaluated) {
2630 // Store the function decl from which we will resolve our
2631 // exception specification.
2632 FunctionDecl **slot =
2633 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
2634 slot[0] = epi.ExceptionSpec.SourceDecl;
2637 if (epi.ConsumedParameters) {
2638 bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
2639 for (unsigned i = 0; i != NumParams; ++i)
2640 consumedParams[i] = epi.ConsumedParameters[i];
2644 bool FunctionProtoType::hasDependentExceptionSpec() const {
2645 if (Expr *NE = getNoexceptExpr())
2646 return NE->isValueDependent();
2647 for (QualType ET : exceptions())
2648 // A pack expansion with a non-dependent pattern is still dependent,
2649 // because we don't know whether the pattern is in the exception spec
2650 // or not (that depends on whether the pack has 0 expansions).
2651 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
2656 FunctionProtoType::NoexceptResult
2657 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
2658 ExceptionSpecificationType est = getExceptionSpecType();
2659 if (est == EST_BasicNoexcept)
2662 if (est != EST_ComputedNoexcept)
2663 return NR_NoNoexcept;
2665 Expr *noexceptExpr = getNoexceptExpr();
2667 return NR_BadNoexcept;
2668 if (noexceptExpr->isValueDependent())
2669 return NR_Dependent;
2672 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
2673 /*evaluated*/false);
2675 assert(isICE && "AST should not contain bad noexcept expressions.");
2677 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
2680 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
2681 bool ResultIfDependent) const {
2682 ExceptionSpecificationType EST = getExceptionSpecType();
2683 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
2684 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2687 if (EST == EST_Dynamic && ResultIfDependent) {
2688 // A dynamic exception specification is throwing unless every exception
2689 // type is an (unexpanded) pack expansion type.
2690 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
2691 if (!getExceptionType(I)->getAs<PackExpansionType>())
2693 return ResultIfDependent;
2696 if (EST != EST_ComputedNoexcept)
2699 NoexceptResult NR = getNoexceptSpec(Ctx);
2700 if (NR == NR_Dependent)
2701 return ResultIfDependent;
2702 return NR == NR_Nothrow;
2705 bool FunctionProtoType::isTemplateVariadic() const {
2706 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
2707 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
2713 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2714 const QualType *ArgTys, unsigned NumParams,
2715 const ExtProtoInfo &epi,
2716 const ASTContext &Context) {
2718 // We have to be careful not to get ambiguous profile encodings.
2719 // Note that valid type pointers are never ambiguous with anything else.
2721 // The encoding grammar begins:
2722 // type type* bool int bool
2723 // If that final bool is true, then there is a section for the EH spec:
2725 // This is followed by an optional "consumed argument" section of the
2726 // same length as the first type sequence:
2728 // Finally, we have the ext info and trailing return type flag:
2731 // There is no ambiguity between the consumed arguments and an empty EH
2732 // spec because of the leading 'bool' which unambiguously indicates
2733 // whether the following bool is the EH spec or part of the arguments.
2735 ID.AddPointer(Result.getAsOpaquePtr());
2736 for (unsigned i = 0; i != NumParams; ++i)
2737 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
2738 // This method is relatively performance sensitive, so as a performance
2739 // shortcut, use one AddInteger call instead of four for the next four
2741 assert(!(unsigned(epi.Variadic) & ~1) &&
2742 !(unsigned(epi.TypeQuals) & ~255) &&
2743 !(unsigned(epi.RefQualifier) & ~3) &&
2744 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
2745 "Values larger than expected.");
2746 ID.AddInteger(unsigned(epi.Variadic) +
2747 (epi.TypeQuals << 1) +
2748 (epi.RefQualifier << 9) +
2749 (epi.ExceptionSpec.Type << 11));
2750 if (epi.ExceptionSpec.Type == EST_Dynamic) {
2751 for (QualType Ex : epi.ExceptionSpec.Exceptions)
2752 ID.AddPointer(Ex.getAsOpaquePtr());
2753 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
2754 epi.ExceptionSpec.NoexceptExpr) {
2755 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
2756 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
2757 epi.ExceptionSpec.Type == EST_Unevaluated) {
2758 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
2760 if (epi.ConsumedParameters) {
2761 for (unsigned i = 0; i != NumParams; ++i)
2762 ID.AddBoolean(epi.ConsumedParameters[i]);
2764 epi.ExtInfo.Profile(ID);
2765 ID.AddBoolean(epi.HasTrailingReturn);
2768 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
2769 const ASTContext &Ctx) {
2770 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
2774 QualType TypedefType::desugar() const {
2775 return getDecl()->getUnderlyingType();
2778 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
2779 : Type(TypeOfExpr, can, E->isTypeDependent(),
2780 E->isInstantiationDependent(),
2781 E->getType()->isVariablyModifiedType(),
2782 E->containsUnexpandedParameterPack()),
2786 bool TypeOfExprType::isSugared() const {
2787 return !TOExpr->isTypeDependent();
2790 QualType TypeOfExprType::desugar() const {
2792 return getUnderlyingExpr()->getType();
2794 return QualType(this, 0);
2797 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
2798 const ASTContext &Context, Expr *E) {
2799 E->Profile(ID, Context, true);
2802 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
2803 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
2804 // decltype(e) denotes a unique dependent type." Hence a decltype type is
2805 // type-dependent even if its expression is only instantiation-dependent.
2806 : Type(Decltype, can, E->isInstantiationDependent(),
2807 E->isInstantiationDependent(),
2808 E->getType()->isVariablyModifiedType(),
2809 E->containsUnexpandedParameterPack()),
2811 UnderlyingType(underlyingType) {
2814 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
2816 QualType DecltypeType::desugar() const {
2818 return getUnderlyingType();
2820 return QualType(this, 0);
2823 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
2824 : DecltypeType(E, Context.DependentTy), Context(Context) { }
2826 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
2827 const ASTContext &Context, Expr *E) {
2828 E->Profile(ID, Context, true);
2831 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
2832 : Type(TC, can, D->isDependentType(),
2833 /*InstantiationDependent=*/D->isDependentType(),
2834 /*VariablyModified=*/false,
2835 /*ContainsUnexpandedParameterPack=*/false),
2836 decl(const_cast<TagDecl*>(D)) {}
2838 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
2839 for (auto I : decl->redecls()) {
2840 if (I->isCompleteDefinition() || I->isBeingDefined())
2843 // If there's no definition (not even in progress), return what we have.
2847 UnaryTransformType::UnaryTransformType(QualType BaseType,
2848 QualType UnderlyingType,
2850 QualType CanonicalType)
2851 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
2852 UnderlyingType->isInstantiationDependentType(),
2853 UnderlyingType->isVariablyModifiedType(),
2854 BaseType->containsUnexpandedParameterPack())
2855 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
2858 TagDecl *TagType::getDecl() const {
2859 return getInterestingTagDecl(decl);
2862 bool TagType::isBeingDefined() const {
2863 return getDecl()->isBeingDefined();
2866 bool AttributedType::isMSTypeSpec() const {
2867 switch (getAttrKind()) {
2868 default: return false;
2875 llvm_unreachable("invalid attr kind");
2878 bool AttributedType::isCallingConv() const {
2879 switch (getAttrKind()) {
2884 case attr_address_space:
2886 case attr_vector_size:
2887 case attr_neon_vector_type:
2888 case attr_neon_polyvector_type:
2890 case attr_objc_ownership:
2894 case attr_null_unspecified:
2895 case attr_objc_kindof:
2904 case attr_vectorcall:
2908 case attr_inteloclbicc:
2911 llvm_unreachable("invalid attr kind");
2914 CXXRecordDecl *InjectedClassNameType::getDecl() const {
2915 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
2918 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
2919 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
2922 SubstTemplateTypeParmPackType::
2923 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
2925 const TemplateArgument &ArgPack)
2926 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
2928 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
2932 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
2933 return TemplateArgument(Arguments, NumArguments);
2936 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
2937 Profile(ID, getReplacedParameter(), getArgumentPack());
2940 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
2941 const TemplateTypeParmType *Replaced,
2942 const TemplateArgument &ArgPack) {
2943 ID.AddPointer(Replaced);
2944 ID.AddInteger(ArgPack.pack_size());
2945 for (const auto &P : ArgPack.pack_elements())
2946 ID.AddPointer(P.getAsType().getAsOpaquePtr());
2949 bool TemplateSpecializationType::
2950 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
2951 bool &InstantiationDependent) {
2952 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
2953 InstantiationDependent);
2956 bool TemplateSpecializationType::
2957 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
2958 bool &InstantiationDependent) {
2959 for (unsigned i = 0; i != N; ++i) {
2960 if (Args[i].getArgument().isDependent()) {
2961 InstantiationDependent = true;
2965 if (Args[i].getArgument().isInstantiationDependent())
2966 InstantiationDependent = true;
2971 TemplateSpecializationType::
2972 TemplateSpecializationType(TemplateName T,
2973 const TemplateArgument *Args, unsigned NumArgs,
2974 QualType Canon, QualType AliasedType)
2975 : Type(TemplateSpecialization,
2976 Canon.isNull()? QualType(this, 0) : Canon,
2977 Canon.isNull()? true : Canon->isDependentType(),
2978 Canon.isNull()? true : Canon->isInstantiationDependentType(),
2980 T.containsUnexpandedParameterPack()),
2981 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2982 assert(!T.getAsDependentTemplateName() &&
2983 "Use DependentTemplateSpecializationType for dependent template-name");
2984 assert((T.getKind() == TemplateName::Template ||
2985 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2986 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2987 "Unexpected template name for TemplateSpecializationType");
2989 TemplateArgument *TemplateArgs
2990 = reinterpret_cast<TemplateArgument *>(this + 1);
2991 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2992 // Update instantiation-dependent and variably-modified bits.
2993 // If the canonical type exists and is non-dependent, the template
2994 // specialization type can be non-dependent even if one of the type
2995 // arguments is. Given:
2996 // template<typename T> using U = int;
2997 // U<T> is always non-dependent, irrespective of the type T.
2998 // However, U<Ts> contains an unexpanded parameter pack, even though
2999 // its expansion (and thus its desugared type) doesn't.
3000 if (Args[Arg].isInstantiationDependent())
3001 setInstantiationDependent();
3002 if (Args[Arg].getKind() == TemplateArgument::Type &&
3003 Args[Arg].getAsType()->isVariablyModifiedType())
3004 setVariablyModified();
3005 if (Args[Arg].containsUnexpandedParameterPack())
3006 setContainsUnexpandedParameterPack();
3007 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
3010 // Store the aliased type if this is a type alias template specialization.
3012 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3013 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3018 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3020 const TemplateArgument *Args,
3022 const ASTContext &Context) {
3024 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
3025 Args[Idx].Profile(ID, Context);
3029 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3030 if (!hasNonFastQualifiers())
3031 return QT.withFastQualifiers(getFastQualifiers());
3033 return Context.getQualifiedType(QT, *this);
3037 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3038 if (!hasNonFastQualifiers())
3039 return QualType(T, getFastQualifiers());
3041 return Context.getQualifiedType(T, *this);
3044 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3046 ArrayRef<QualType> typeArgs,
3047 ArrayRef<ObjCProtocolDecl *> protocols,
3049 ID.AddPointer(BaseType.getAsOpaquePtr());
3050 ID.AddInteger(typeArgs.size());
3051 for (auto typeArg : typeArgs)
3052 ID.AddPointer(typeArg.getAsOpaquePtr());
3053 ID.AddInteger(protocols.size());
3054 for (auto proto : protocols)
3055 ID.AddPointer(proto);
3056 ID.AddBoolean(isKindOf);
3059 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3060 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3061 llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3062 isKindOfTypeAsWritten());
3067 /// \brief The cached properties of a type.
3068 class CachedProperties {
3073 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3075 Linkage getLinkage() const { return L; }
3076 bool hasLocalOrUnnamedType() const { return local; }
3078 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3079 Linkage MergedLinkage = minLinkage(L.L, R.L);
3080 return CachedProperties(MergedLinkage,
3081 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3086 static CachedProperties computeCachedProperties(const Type *T);
3089 /// The type-property cache. This is templated so as to be
3090 /// instantiated at an internal type to prevent unnecessary symbol
3092 template <class Private> class TypePropertyCache {
3094 static CachedProperties get(QualType T) {
3095 return get(T.getTypePtr());
3098 static CachedProperties get(const Type *T) {
3100 return CachedProperties(T->TypeBits.getLinkage(),
3101 T->TypeBits.hasLocalOrUnnamedType());
3104 static void ensure(const Type *T) {
3105 // If the cache is valid, we're okay.
3106 if (T->TypeBits.isCacheValid()) return;
3108 // If this type is non-canonical, ask its canonical type for the
3109 // relevant information.
3110 if (!T->isCanonicalUnqualified()) {
3111 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3113 T->TypeBits.CacheValid = true;
3114 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3115 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3119 // Compute the cached properties and then set the cache.
3120 CachedProperties Result = computeCachedProperties(T);
3121 T->TypeBits.CacheValid = true;
3122 T->TypeBits.CachedLinkage = Result.getLinkage();
3123 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3128 // Instantiate the friend template at a private class. In a
3129 // reasonable implementation, these symbols will be internal.
3130 // It is terrible that this is the best way to accomplish this.
3131 namespace { class Private {}; }
3132 typedef TypePropertyCache<Private> Cache;
3134 static CachedProperties computeCachedProperties(const Type *T) {
3135 switch (T->getTypeClass()) {
3136 #define TYPE(Class,Base)
3137 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3138 #include "clang/AST/TypeNodes.def"
3139 llvm_unreachable("didn't expect a non-canonical type here");
3141 #define TYPE(Class,Base)
3142 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3143 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3144 #include "clang/AST/TypeNodes.def"
3145 // Treat instantiation-dependent types as external.
3146 assert(T->isInstantiationDependentType());
3147 return CachedProperties(ExternalLinkage, false);
3150 // Give non-deduced 'auto' types external linkage. We should only see them
3151 // here in error recovery.
3152 return CachedProperties(ExternalLinkage, false);
3155 // C++ [basic.link]p8:
3156 // A type is said to have linkage if and only if:
3157 // - it is a fundamental type (3.9.1); or
3158 return CachedProperties(ExternalLinkage, false);
3162 const TagDecl *Tag = cast<TagType>(T)->getDecl();
3164 // C++ [basic.link]p8:
3165 // - it is a class or enumeration type that is named (or has a name
3166 // for linkage purposes (7.1.3)) and the name has linkage; or
3167 // - it is a specialization of a class template (14); or
3168 Linkage L = Tag->getLinkageInternal();
3169 bool IsLocalOrUnnamed =
3170 Tag->getDeclContext()->isFunctionOrMethod() ||
3171 !Tag->hasNameForLinkage();
3172 return CachedProperties(L, IsLocalOrUnnamed);
3175 // C++ [basic.link]p8:
3176 // - it is a compound type (3.9.2) other than a class or enumeration,
3177 // compounded exclusively from types that have linkage; or
3179 return Cache::get(cast<ComplexType>(T)->getElementType());
3181 return Cache::get(cast<PointerType>(T)->getPointeeType());
3182 case Type::BlockPointer:
3183 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3184 case Type::LValueReference:
3185 case Type::RValueReference:
3186 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3187 case Type::MemberPointer: {
3188 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3189 return merge(Cache::get(MPT->getClass()),
3190 Cache::get(MPT->getPointeeType()));
3192 case Type::ConstantArray:
3193 case Type::IncompleteArray:
3194 case Type::VariableArray:
3195 return Cache::get(cast<ArrayType>(T)->getElementType());
3197 case Type::ExtVector:
3198 return Cache::get(cast<VectorType>(T)->getElementType());
3199 case Type::FunctionNoProto:
3200 return Cache::get(cast<FunctionType>(T)->getReturnType());
3201 case Type::FunctionProto: {
3202 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3203 CachedProperties result = Cache::get(FPT->getReturnType());
3204 for (const auto &ai : FPT->param_types())
3205 result = merge(result, Cache::get(ai));
3208 case Type::ObjCInterface: {
3209 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3210 return CachedProperties(L, false);
3212 case Type::ObjCObject:
3213 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3214 case Type::ObjCObjectPointer:
3215 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3217 return Cache::get(cast<AtomicType>(T)->getValueType());
3220 llvm_unreachable("unhandled type class");
3223 /// \brief Determine the linkage of this type.
3224 Linkage Type::getLinkage() const {
3225 Cache::ensure(this);
3226 return TypeBits.getLinkage();
3229 bool Type::hasUnnamedOrLocalType() const {
3230 Cache::ensure(this);
3231 return TypeBits.hasLocalOrUnnamedType();
3234 static LinkageInfo computeLinkageInfo(QualType T);
3236 static LinkageInfo computeLinkageInfo(const Type *T) {
3237 switch (T->getTypeClass()) {
3238 #define TYPE(Class,Base)
3239 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3240 #include "clang/AST/TypeNodes.def"
3241 llvm_unreachable("didn't expect a non-canonical type here");
3243 #define TYPE(Class,Base)
3244 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3245 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3246 #include "clang/AST/TypeNodes.def"
3247 // Treat instantiation-dependent types as external.
3248 assert(T->isInstantiationDependentType());
3249 return LinkageInfo::external();
3252 return LinkageInfo::external();
3255 return LinkageInfo::external();
3259 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
3262 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
3264 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3265 case Type::BlockPointer:
3266 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3267 case Type::LValueReference:
3268 case Type::RValueReference:
3269 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3270 case Type::MemberPointer: {
3271 const MemberPointerType *MPT = cast<MemberPointerType>(T);
3272 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
3273 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
3276 case Type::ConstantArray:
3277 case Type::IncompleteArray:
3278 case Type::VariableArray:
3279 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
3281 case Type::ExtVector:
3282 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
3283 case Type::FunctionNoProto:
3284 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3285 case Type::FunctionProto: {
3286 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
3287 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
3288 for (const auto &ai : FPT->param_types())
3289 LV.merge(computeLinkageInfo(ai));
3292 case Type::ObjCInterface:
3293 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
3294 case Type::ObjCObject:
3295 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3296 case Type::ObjCObjectPointer:
3297 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
3299 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
3302 llvm_unreachable("unhandled type class");
3305 static LinkageInfo computeLinkageInfo(QualType T) {
3306 return computeLinkageInfo(T.getTypePtr());
3309 bool Type::isLinkageValid() const {
3310 if (!TypeBits.isCacheValid())
3313 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
3314 TypeBits.getLinkage();
3317 LinkageInfo Type::getLinkageAndVisibility() const {
3318 if (!isCanonicalUnqualified())
3319 return computeLinkageInfo(getCanonicalTypeInternal());
3321 LinkageInfo LV = computeLinkageInfo(this);
3322 assert(LV.getLinkage() == getLinkage());
3326 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
3327 QualType type(this, 0);
3329 // Check whether this is an attributed type with nullability
3331 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
3332 if (auto nullability = attributed->getImmediateNullability())
3336 // Desugar the type. If desugaring does nothing, we're done.
3337 QualType desugared = type.getSingleStepDesugaredType(context);
3338 if (desugared.getTypePtr() == type.getTypePtr())
3345 bool Type::canHaveNullability() const {
3346 QualType type = getCanonicalTypeInternal();
3348 switch (type->getTypeClass()) {
3349 // We'll only see canonical types here.
3350 #define NON_CANONICAL_TYPE(Class, Parent) \
3352 llvm_unreachable("non-canonical type");
3353 #define TYPE(Class, Parent)
3354 #include "clang/AST/TypeNodes.def"
3358 case Type::BlockPointer:
3359 case Type::MemberPointer:
3360 case Type::ObjCObjectPointer:
3363 // Dependent types that could instantiate to pointer types.
3364 case Type::UnresolvedUsing:
3365 case Type::TypeOfExpr:
3367 case Type::Decltype:
3368 case Type::UnaryTransform:
3369 case Type::TemplateTypeParm:
3370 case Type::SubstTemplateTypeParmPack:
3371 case Type::DependentName:
3372 case Type::DependentTemplateSpecialization:
3375 // Dependent template specializations can instantiate to pointer
3376 // types unless they're known to be specializations of a class
3378 case Type::TemplateSpecialization:
3379 if (TemplateDecl *templateDecl
3380 = cast<TemplateSpecializationType>(type.getTypePtr())
3381 ->getTemplateName().getAsTemplateDecl()) {
3382 if (isa<ClassTemplateDecl>(templateDecl))
3387 // auto is considered dependent when it isn't deduced.
3389 return !cast<AutoType>(type.getTypePtr())->isDeduced();
3392 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
3393 // Signed, unsigned, and floating-point types cannot have nullability.
3394 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3395 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3396 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
3397 #define BUILTIN_TYPE(Id, SingletonId)
3398 #include "clang/AST/BuiltinTypes.def"
3401 // Dependent types that could instantiate to a pointer type.
3402 case BuiltinType::Dependent:
3403 case BuiltinType::Overload:
3404 case BuiltinType::BoundMember:
3405 case BuiltinType::PseudoObject:
3406 case BuiltinType::UnknownAny:
3407 case BuiltinType::ARCUnbridgedCast:
3410 case BuiltinType::Void:
3411 case BuiltinType::ObjCId:
3412 case BuiltinType::ObjCClass:
3413 case BuiltinType::ObjCSel:
3414 case BuiltinType::OCLImage1d:
3415 case BuiltinType::OCLImage1dArray:
3416 case BuiltinType::OCLImage1dBuffer:
3417 case BuiltinType::OCLImage2d:
3418 case BuiltinType::OCLImage2dArray:
3419 case BuiltinType::OCLImage3d:
3420 case BuiltinType::OCLSampler:
3421 case BuiltinType::OCLEvent:
3422 case BuiltinType::BuiltinFn:
3423 case BuiltinType::NullPtr:
3427 // Non-pointer types.
3429 case Type::LValueReference:
3430 case Type::RValueReference:
3431 case Type::ConstantArray:
3432 case Type::IncompleteArray:
3433 case Type::VariableArray:
3434 case Type::DependentSizedArray:
3435 case Type::DependentSizedExtVector:
3437 case Type::ExtVector:
3438 case Type::FunctionProto:
3439 case Type::FunctionNoProto:
3442 case Type::InjectedClassName:
3443 case Type::PackExpansion:
3444 case Type::ObjCObject:
3445 case Type::ObjCInterface:
3449 llvm_unreachable("bad type kind!");
3452 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
3453 if (getAttrKind() == AttributedType::attr_nonnull)
3454 return NullabilityKind::NonNull;
3455 if (getAttrKind() == AttributedType::attr_nullable)
3456 return NullabilityKind::Nullable;
3457 if (getAttrKind() == AttributedType::attr_null_unspecified)
3458 return NullabilityKind::Unspecified;
3462 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
3463 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
3464 if (auto nullability = attributed->getImmediateNullability()) {
3465 T = attributed->getModifiedType();
3473 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
3474 const ObjCObjectPointerType *objcPtr = getAs<ObjCObjectPointerType>();
3478 if (objcPtr->isObjCIdType()) {
3479 // id is always okay.
3483 // Blocks are NSObjects.
3484 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
3485 if (iface->getIdentifier() != ctx.getNSObjectName())
3488 // Continue to check qualifiers, below.
3489 } else if (objcPtr->isObjCQualifiedIdType()) {
3490 // Continue to check qualifiers, below.
3495 // Check protocol qualifiers.
3496 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
3497 // Blocks conform to NSObject and NSCopying.
3498 if (proto->getIdentifier() != ctx.getNSObjectName() &&
3499 proto->getIdentifier() != ctx.getNSCopyingName())
3506 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
3507 if (isObjCARCImplicitlyUnretainedType())
3508 return Qualifiers::OCL_ExplicitNone;
3509 return Qualifiers::OCL_Strong;
3512 bool Type::isObjCARCImplicitlyUnretainedType() const {
3513 assert(isObjCLifetimeType() &&
3514 "cannot query implicit lifetime for non-inferrable type");
3516 const Type *canon = getCanonicalTypeInternal().getTypePtr();
3518 // Walk down to the base type. We don't care about qualifiers for this.
3519 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
3520 canon = array->getElementType().getTypePtr();
3522 if (const ObjCObjectPointerType *opt
3523 = dyn_cast<ObjCObjectPointerType>(canon)) {
3524 // Class and Class<Protocol> don't require retension.
3525 if (opt->getObjectType()->isObjCClass())
3532 bool Type::isObjCNSObjectType() const {
3533 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
3534 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
3537 bool Type::isObjCIndependentClassType() const {
3538 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
3539 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
3542 bool Type::isObjCRetainableType() const {
3543 return isObjCObjectPointerType() ||
3544 isBlockPointerType() ||
3545 isObjCNSObjectType();
3547 bool Type::isObjCIndirectLifetimeType() const {
3548 if (isObjCLifetimeType())
3550 if (const PointerType *OPT = getAs<PointerType>())
3551 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
3552 if (const ReferenceType *Ref = getAs<ReferenceType>())
3553 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
3554 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
3555 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
3559 /// Returns true if objects of this type have lifetime semantics under
3561 bool Type::isObjCLifetimeType() const {
3562 const Type *type = this;
3563 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
3564 type = array->getElementType().getTypePtr();
3565 return type->isObjCRetainableType();
3568 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
3569 /// which is either an Objective-C object pointer type or an
3570 bool Type::isObjCARCBridgableType() const {
3571 return isObjCObjectPointerType() || isBlockPointerType();
3574 /// \brief Determine whether the given type T is a "bridgeable" C type.
3575 bool Type::isCARCBridgableType() const {
3576 const PointerType *Pointer = getAs<PointerType>();
3580 QualType Pointee = Pointer->getPointeeType();
3581 return Pointee->isVoidType() || Pointee->isRecordType();
3584 bool Type::hasSizedVLAType() const {
3585 if (!isVariablyModifiedType()) return false;
3587 if (const PointerType *ptr = getAs<PointerType>())
3588 return ptr->getPointeeType()->hasSizedVLAType();
3589 if (const ReferenceType *ref = getAs<ReferenceType>())
3590 return ref->getPointeeType()->hasSizedVLAType();
3591 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
3592 if (isa<VariableArrayType>(arr) &&
3593 cast<VariableArrayType>(arr)->getSizeExpr())
3596 return arr->getElementType()->hasSizedVLAType();
3602 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
3603 switch (type.getObjCLifetime()) {
3604 case Qualifiers::OCL_None:
3605 case Qualifiers::OCL_ExplicitNone:
3606 case Qualifiers::OCL_Autoreleasing:
3609 case Qualifiers::OCL_Strong:
3610 return DK_objc_strong_lifetime;
3611 case Qualifiers::OCL_Weak:
3612 return DK_objc_weak_lifetime;
3615 /// Currently, the only destruction kind we recognize is C++ objects
3616 /// with non-trivial destructors.
3617 const CXXRecordDecl *record =
3618 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3619 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
3620 return DK_cxx_destructor;
3625 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
3626 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();