1 //===- Type.cpp - Type representation and manipulation --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements type-related functionality.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Type.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/NestedNameSpecifier.h"
25 #include "clang/AST/NonTrivialTypeVisitor.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/TemplateBase.h"
28 #include "clang/AST/TemplateName.h"
29 #include "clang/AST/TypeVisitor.h"
30 #include "clang/Basic/AddressSpaces.h"
31 #include "clang/Basic/ExceptionSpecificationType.h"
32 #include "clang/Basic/IdentifierTable.h"
33 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "clang/Basic/Linkage.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetCXXABI.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Visibility.h"
40 #include "llvm/ADT/APInt.h"
41 #include "llvm/ADT/APSInt.h"
42 #include "llvm/ADT/ArrayRef.h"
43 #include "llvm/ADT/FoldingSet.h"
44 #include "llvm/ADT/None.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
53 #include <type_traits>
55 using namespace clang;
57 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
58 return (*this != Other) &&
59 // CVR qualifiers superset
60 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
61 // ObjC GC qualifiers superset
62 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
63 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
64 // Address space superset.
65 ((getAddressSpace() == Other.getAddressSpace()) ||
66 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
67 // Lifetime qualifier superset.
68 ((getObjCLifetime() == Other.getObjCLifetime()) ||
69 (hasObjCLifetime() && !Other.hasObjCLifetime()));
72 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
73 const Type* ty = getTypePtr();
74 NamedDecl *ND = nullptr;
75 if (ty->isPointerType() || ty->isReferenceType())
76 return ty->getPointeeType().getBaseTypeIdentifier();
77 else if (ty->isRecordType())
78 ND = ty->castAs<RecordType>()->getDecl();
79 else if (ty->isEnumeralType())
80 ND = ty->castAs<EnumType>()->getDecl();
81 else if (ty->getTypeClass() == Type::Typedef)
82 ND = ty->castAs<TypedefType>()->getDecl();
83 else if (ty->isArrayType())
84 return ty->castAsArrayTypeUnsafe()->
85 getElementType().getBaseTypeIdentifier();
88 return ND->getIdentifier();
92 bool QualType::mayBeDynamicClass() const {
93 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
94 return ClassDecl && ClassDecl->mayBeDynamicClass();
97 bool QualType::mayBeNotDynamicClass() const {
98 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
99 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
102 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
103 if (T.isConstQualified())
106 if (const ArrayType *AT = Ctx.getAsArrayType(T))
107 return AT->getElementType().isConstant(Ctx);
109 return T.getAddressSpace() == LangAS::opencl_constant;
112 // C++ [temp.dep.type]p1:
113 // A type is dependent if it is...
114 // - an array type constructed from any dependent type or whose
115 // size is specified by a constant expression that is
117 ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
118 ArraySizeModifier sm, unsigned tq, const Expr *sz)
119 // Note, we need to check for DependentSizedArrayType explicitly here
120 // because we use a DependentSizedArrayType with no size expression as the
121 // type of a dependent array of unknown bound with a dependent braced
124 // template<int ...N> int arr[] = {N...};
126 et->isDependentType() || (sz && sz->isValueDependent()) ||
127 tc == DependentSizedArray,
128 et->isInstantiationDependentType() ||
129 (sz && sz->isInstantiationDependent()) ||
130 tc == DependentSizedArray,
131 (tc == VariableArray || et->isVariablyModifiedType()),
132 et->containsUnexpandedParameterPack() ||
133 (sz && sz->containsUnexpandedParameterPack())),
135 ArrayTypeBits.IndexTypeQuals = tq;
136 ArrayTypeBits.SizeModifier = sm;
139 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
140 QualType ElementType,
141 const llvm::APInt &NumElements) {
142 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
144 // Fast path the common cases so we can avoid the conservative computation
145 // below, which in common cases allocates "large" APSInt values, which are
148 // If the element size is a power of 2, we can directly compute the additional
149 // number of addressing bits beyond those required for the element count.
150 if (llvm::isPowerOf2_64(ElementSize)) {
151 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
154 // If both the element count and element size fit in 32-bits, we can do the
155 // computation directly in 64-bits.
156 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
157 (NumElements.getZExtValue() >> 32) == 0) {
158 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
159 return 64 - llvm::countLeadingZeros(TotalSize);
162 // Otherwise, use APSInt to handle arbitrary sized values.
163 llvm::APSInt SizeExtended(NumElements, true);
164 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
165 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
166 SizeExtended.getBitWidth()) * 2);
168 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
169 TotalSize *= SizeExtended;
171 return TotalSize.getActiveBits();
174 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
175 unsigned Bits = Context.getTypeSize(Context.getSizeType());
177 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
178 // integer (see PR8256). We can do this as currently there is no hardware
179 // that supports full 64-bit virtual space.
186 void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
187 const ASTContext &Context, QualType ET,
188 const llvm::APInt &ArraySize,
189 const Expr *SizeExpr, ArraySizeModifier SizeMod,
190 unsigned TypeQuals) {
191 ID.AddPointer(ET.getAsOpaquePtr());
192 ID.AddInteger(ArraySize.getZExtValue());
193 ID.AddInteger(SizeMod);
194 ID.AddInteger(TypeQuals);
195 ID.AddBoolean(SizeExpr != 0);
197 SizeExpr->Profile(ID, Context, true);
200 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
201 QualType et, QualType can,
202 Expr *e, ArraySizeModifier sm,
204 SourceRange brackets)
205 : ArrayType(DependentSizedArray, et, can, sm, tq, e),
206 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
208 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
209 const ASTContext &Context,
211 ArraySizeModifier SizeMod,
214 ID.AddPointer(ET.getAsOpaquePtr());
215 ID.AddInteger(SizeMod);
216 ID.AddInteger(TypeQuals);
217 E->Profile(ID, Context, true);
220 DependentVectorType::DependentVectorType(
221 const ASTContext &Context, QualType ElementType, QualType CanonType,
222 Expr *SizeExpr, SourceLocation Loc, VectorType::VectorKind VecKind)
223 : Type(DependentVector, CanonType, /*Dependent=*/true,
224 /*InstantiationDependent=*/true,
225 ElementType->isVariablyModifiedType(),
226 ElementType->containsUnexpandedParameterPack() ||
227 (SizeExpr && SizeExpr->containsUnexpandedParameterPack())),
228 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
229 VectorTypeBits.VecKind = VecKind;
232 void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
233 const ASTContext &Context,
234 QualType ElementType, const Expr *SizeExpr,
235 VectorType::VectorKind VecKind) {
236 ID.AddPointer(ElementType.getAsOpaquePtr());
237 ID.AddInteger(VecKind);
238 SizeExpr->Profile(ID, Context, true);
241 DependentSizedExtVectorType::DependentSizedExtVectorType(const
243 QualType ElementType,
247 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
248 /*InstantiationDependent=*/true,
249 ElementType->isVariablyModifiedType(),
250 (ElementType->containsUnexpandedParameterPack() ||
251 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
252 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
256 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
257 const ASTContext &Context,
258 QualType ElementType, Expr *SizeExpr) {
259 ID.AddPointer(ElementType.getAsOpaquePtr());
260 SizeExpr->Profile(ID, Context, true);
263 DependentAddressSpaceType::DependentAddressSpaceType(
264 const ASTContext &Context, QualType PointeeType, QualType can,
265 Expr *AddrSpaceExpr, SourceLocation loc)
266 : Type(DependentAddressSpace, can, /*Dependent=*/true,
267 /*InstantiationDependent=*/true,
268 PointeeType->isVariablyModifiedType(),
269 (PointeeType->containsUnexpandedParameterPack() ||
271 AddrSpaceExpr->containsUnexpandedParameterPack()))),
272 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
275 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
276 const ASTContext &Context,
277 QualType PointeeType,
278 Expr *AddrSpaceExpr) {
279 ID.AddPointer(PointeeType.getAsOpaquePtr());
280 AddrSpaceExpr->Profile(ID, Context, true);
283 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
285 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
287 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
288 QualType canonType, VectorKind vecKind)
289 : Type(tc, canonType, vecType->isDependentType(),
290 vecType->isInstantiationDependentType(),
291 vecType->isVariablyModifiedType(),
292 vecType->containsUnexpandedParameterPack()),
293 ElementType(vecType) {
294 VectorTypeBits.VecKind = vecKind;
295 VectorTypeBits.NumElements = nElements;
298 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
299 /// element type of the array, potentially with type qualifiers missing.
300 /// This method should never be used when type qualifiers are meaningful.
301 const Type *Type::getArrayElementTypeNoTypeQual() const {
302 // If this is directly an array type, return it.
303 if (const auto *ATy = dyn_cast<ArrayType>(this))
304 return ATy->getElementType().getTypePtr();
306 // If the canonical form of this type isn't the right kind, reject it.
307 if (!isa<ArrayType>(CanonicalType))
310 // If this is a typedef for an array type, strip the typedef off without
311 // losing all typedef information.
312 return cast<ArrayType>(getUnqualifiedDesugaredType())
313 ->getElementType().getTypePtr();
316 /// getDesugaredType - Return the specified type with any "sugar" removed from
317 /// the type. This takes off typedefs, typeof's etc. If the outer level of
318 /// the type is already concrete, it returns it unmodified. This is similar
319 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
320 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
322 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
323 SplitQualType split = getSplitDesugaredType(T);
324 return Context.getQualifiedType(split.Ty, split.Quals);
327 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
328 const ASTContext &Context) {
329 SplitQualType split = type.split();
330 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
331 return Context.getQualifiedType(desugar, split.Quals);
334 // Check that no type class is polymorphic. LLVM style RTTI should be used
335 // instead. If absolutely needed an exception can still be added here by
336 // defining the appropriate macro (but please don't do this).
337 #define TYPE(CLASS, BASE) \
338 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
339 #CLASS "Type should not be polymorphic!");
340 #include "clang/AST/TypeNodes.inc"
342 // Check that no type class has a non-trival destructor. Types are
343 // allocated with the BumpPtrAllocator from ASTContext and therefore
344 // their destructor is not executed.
346 // FIXME: ConstantArrayType is not trivially destructible because of its
347 // APInt member. It should be replaced in favor of ASTContext allocation.
348 #define TYPE(CLASS, BASE) \
349 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
350 std::is_same<CLASS##Type, ConstantArrayType>::value, \
351 #CLASS "Type should be trivially destructible!");
352 #include "clang/AST/TypeNodes.inc"
354 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
355 switch (getTypeClass()) {
356 #define ABSTRACT_TYPE(Class, Parent)
357 #define TYPE(Class, Parent) \
358 case Type::Class: { \
359 const auto *ty = cast<Class##Type>(this); \
360 if (!ty->isSugared()) return QualType(ty, 0); \
361 return ty->desugar(); \
363 #include "clang/AST/TypeNodes.inc"
365 llvm_unreachable("bad type kind!");
368 SplitQualType QualType::getSplitDesugaredType(QualType T) {
369 QualifierCollector Qs;
373 const Type *CurTy = Qs.strip(Cur);
374 switch (CurTy->getTypeClass()) {
375 #define ABSTRACT_TYPE(Class, Parent)
376 #define TYPE(Class, Parent) \
377 case Type::Class: { \
378 const auto *Ty = cast<Class##Type>(CurTy); \
379 if (!Ty->isSugared()) \
380 return SplitQualType(Ty, Qs); \
381 Cur = Ty->desugar(); \
384 #include "clang/AST/TypeNodes.inc"
389 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
390 SplitQualType split = type.split();
392 // All the qualifiers we've seen so far.
393 Qualifiers quals = split.Quals;
395 // The last type node we saw with any nodes inside it.
396 const Type *lastTypeWithQuals = split.Ty;
401 // Do a single-step desugar, aborting the loop if the type isn't
403 switch (split.Ty->getTypeClass()) {
404 #define ABSTRACT_TYPE(Class, Parent)
405 #define TYPE(Class, Parent) \
406 case Type::Class: { \
407 const auto *ty = cast<Class##Type>(split.Ty); \
408 if (!ty->isSugared()) goto done; \
409 next = ty->desugar(); \
412 #include "clang/AST/TypeNodes.inc"
415 // Otherwise, split the underlying type. If that yields qualifiers,
416 // update the information.
417 split = next.split();
418 if (!split.Quals.empty()) {
419 lastTypeWithQuals = split.Ty;
420 quals.addConsistentQualifiers(split.Quals);
425 return SplitQualType(lastTypeWithQuals, quals);
428 QualType QualType::IgnoreParens(QualType T) {
429 // FIXME: this seems inherently un-qualifiers-safe.
430 while (const auto *PT = T->getAs<ParenType>())
431 T = PT->getInnerType();
435 /// This will check for a T (which should be a Type which can act as
436 /// sugar, such as a TypedefType) by removing any existing sugar until it
437 /// reaches a T or a non-sugared type.
438 template<typename T> static const T *getAsSugar(const Type *Cur) {
440 if (const auto *Sugar = dyn_cast<T>(Cur))
442 switch (Cur->getTypeClass()) {
443 #define ABSTRACT_TYPE(Class, Parent)
444 #define TYPE(Class, Parent) \
445 case Type::Class: { \
446 const auto *Ty = cast<Class##Type>(Cur); \
447 if (!Ty->isSugared()) return 0; \
448 Cur = Ty->desugar().getTypePtr(); \
451 #include "clang/AST/TypeNodes.inc"
456 template <> const TypedefType *Type::getAs() const {
457 return getAsSugar<TypedefType>(this);
460 template <> const TemplateSpecializationType *Type::getAs() const {
461 return getAsSugar<TemplateSpecializationType>(this);
464 template <> const AttributedType *Type::getAs() const {
465 return getAsSugar<AttributedType>(this);
468 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
469 /// sugar off the given type. This should produce an object of the
470 /// same dynamic type as the canonical type.
471 const Type *Type::getUnqualifiedDesugaredType() const {
472 const Type *Cur = this;
475 switch (Cur->getTypeClass()) {
476 #define ABSTRACT_TYPE(Class, Parent)
477 #define TYPE(Class, Parent) \
479 const auto *Ty = cast<Class##Type>(Cur); \
480 if (!Ty->isSugared()) return Cur; \
481 Cur = Ty->desugar().getTypePtr(); \
484 #include "clang/AST/TypeNodes.inc"
489 bool Type::isClassType() const {
490 if (const auto *RT = getAs<RecordType>())
491 return RT->getDecl()->isClass();
495 bool Type::isStructureType() const {
496 if (const auto *RT = getAs<RecordType>())
497 return RT->getDecl()->isStruct();
501 bool Type::isObjCBoxableRecordType() const {
502 if (const auto *RT = getAs<RecordType>())
503 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
507 bool Type::isInterfaceType() const {
508 if (const auto *RT = getAs<RecordType>())
509 return RT->getDecl()->isInterface();
513 bool Type::isStructureOrClassType() const {
514 if (const auto *RT = getAs<RecordType>()) {
515 RecordDecl *RD = RT->getDecl();
516 return RD->isStruct() || RD->isClass() || RD->isInterface();
521 bool Type::isVoidPointerType() const {
522 if (const auto *PT = getAs<PointerType>())
523 return PT->getPointeeType()->isVoidType();
527 bool Type::isUnionType() const {
528 if (const auto *RT = getAs<RecordType>())
529 return RT->getDecl()->isUnion();
533 bool Type::isComplexType() const {
534 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
535 return CT->getElementType()->isFloatingType();
539 bool Type::isComplexIntegerType() const {
540 // Check for GCC complex integer extension.
541 return getAsComplexIntegerType();
544 bool Type::isScopedEnumeralType() const {
545 if (const auto *ET = getAs<EnumType>())
546 return ET->getDecl()->isScoped();
550 const ComplexType *Type::getAsComplexIntegerType() const {
551 if (const auto *Complex = getAs<ComplexType>())
552 if (Complex->getElementType()->isIntegerType())
557 QualType Type::getPointeeType() const {
558 if (const auto *PT = getAs<PointerType>())
559 return PT->getPointeeType();
560 if (const auto *OPT = getAs<ObjCObjectPointerType>())
561 return OPT->getPointeeType();
562 if (const auto *BPT = getAs<BlockPointerType>())
563 return BPT->getPointeeType();
564 if (const auto *RT = getAs<ReferenceType>())
565 return RT->getPointeeType();
566 if (const auto *MPT = getAs<MemberPointerType>())
567 return MPT->getPointeeType();
568 if (const auto *DT = getAs<DecayedType>())
569 return DT->getPointeeType();
573 const RecordType *Type::getAsStructureType() const {
574 // If this is directly a structure type, return it.
575 if (const auto *RT = dyn_cast<RecordType>(this)) {
576 if (RT->getDecl()->isStruct())
580 // If the canonical form of this type isn't the right kind, reject it.
581 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
582 if (!RT->getDecl()->isStruct())
585 // If this is a typedef for a structure type, strip the typedef off without
586 // losing all typedef information.
587 return cast<RecordType>(getUnqualifiedDesugaredType());
592 const RecordType *Type::getAsUnionType() const {
593 // If this is directly a union type, return it.
594 if (const auto *RT = dyn_cast<RecordType>(this)) {
595 if (RT->getDecl()->isUnion())
599 // If the canonical form of this type isn't the right kind, reject it.
600 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
601 if (!RT->getDecl()->isUnion())
604 // If this is a typedef for a union type, strip the typedef off without
605 // losing all typedef information.
606 return cast<RecordType>(getUnqualifiedDesugaredType());
612 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
613 const ObjCObjectType *&bound) const {
616 const auto *OPT = getAs<ObjCObjectPointerType>();
621 if (OPT->isObjCIdType())
624 // If it's not a __kindof type, reject it now.
625 if (!OPT->isKindOfType())
628 // If it's Class or qualified Class, it's not an object type.
629 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
632 // Figure out the type bound for the __kindof type.
633 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
634 ->getAs<ObjCObjectType>();
638 bool Type::isObjCClassOrClassKindOfType() const {
639 const auto *OPT = getAs<ObjCObjectPointerType>();
644 if (OPT->isObjCClassType())
647 // If it's not a __kindof type, reject it now.
648 if (!OPT->isKindOfType())
651 // If it's Class or qualified Class, it's a class __kindof type.
652 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
655 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D,
657 ArrayRef<ObjCProtocolDecl *> protocols)
658 : Type(ObjCTypeParam, can, can->isDependentType(),
659 can->isInstantiationDependentType(),
660 can->isVariablyModifiedType(),
661 /*ContainsUnexpandedParameterPack=*/false),
662 OTPDecl(const_cast<ObjCTypeParamDecl*>(D)) {
663 initialize(protocols);
666 QualType ObjCTypeParamType::desugar() const {
667 return getDecl()->getUnderlyingType();
670 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
671 ArrayRef<QualType> typeArgs,
672 ArrayRef<ObjCProtocolDecl *> protocols,
674 : Type(ObjCObject, Canonical, Base->isDependentType(),
675 Base->isInstantiationDependentType(),
676 Base->isVariablyModifiedType(),
677 Base->containsUnexpandedParameterPack()),
679 ObjCObjectTypeBits.IsKindOf = isKindOf;
681 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
682 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
683 "bitfield overflow in type argument count");
684 if (!typeArgs.empty())
685 memcpy(getTypeArgStorage(), typeArgs.data(),
686 typeArgs.size() * sizeof(QualType));
688 for (auto typeArg : typeArgs) {
689 if (typeArg->isDependentType())
691 else if (typeArg->isInstantiationDependentType())
692 setInstantiationDependent();
694 if (typeArg->containsUnexpandedParameterPack())
695 setContainsUnexpandedParameterPack();
697 // Initialize the protocol qualifiers. The protocol storage is known
698 // after we set number of type arguments.
699 initialize(protocols);
702 bool ObjCObjectType::isSpecialized() const {
703 // If we have type arguments written here, the type is specialized.
704 if (ObjCObjectTypeBits.NumTypeArgs > 0)
707 // Otherwise, check whether the base type is specialized.
708 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
709 // Terminate when we reach an interface type.
710 if (isa<ObjCInterfaceType>(objcObject))
713 return objcObject->isSpecialized();
720 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
721 // We have type arguments written on this type.
722 if (isSpecializedAsWritten())
723 return getTypeArgsAsWritten();
725 // Look at the base type, which might have type arguments.
726 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
727 // Terminate when we reach an interface type.
728 if (isa<ObjCInterfaceType>(objcObject))
731 return objcObject->getTypeArgs();
734 // No type arguments.
738 bool ObjCObjectType::isKindOfType() const {
739 if (isKindOfTypeAsWritten())
742 // Look at the base type, which might have type arguments.
743 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
744 // Terminate when we reach an interface type.
745 if (isa<ObjCInterfaceType>(objcObject))
748 return objcObject->isKindOfType();
751 // Not a "__kindof" type.
755 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
756 const ASTContext &ctx) const {
757 if (!isKindOfType() && qual_empty())
758 return QualType(this, 0);
760 // Recursively strip __kindof.
761 SplitQualType splitBaseType = getBaseType().split();
762 QualType baseType(splitBaseType.Ty, 0);
763 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
764 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
766 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
767 splitBaseType.Quals),
768 getTypeArgsAsWritten(),
773 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
774 const ASTContext &ctx) const {
775 if (!isKindOfType() && qual_empty())
778 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
779 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
784 /// Visitor used to perform a simple type transformation that does not change
785 /// the semantics of the type.
786 template <typename Derived>
787 struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
790 QualType recurse(QualType type) {
791 // Split out the qualifiers from the type.
792 SplitQualType splitType = type.split();
794 // Visit the type itself.
795 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
799 // Reconstruct the transformed type by applying the local qualifiers
800 // from the split type.
801 return Ctx.getQualifiedType(result, splitType.Quals);
805 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
807 // None of the clients of this transformation can occur where
808 // there are dependent types, so skip dependent types.
809 #define TYPE(Class, Base)
810 #define DEPENDENT_TYPE(Class, Base) \
811 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
812 #include "clang/AST/TypeNodes.inc"
814 #define TRIVIAL_TYPE_CLASS(Class) \
815 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
816 #define SUGARED_TYPE_CLASS(Class) \
817 QualType Visit##Class##Type(const Class##Type *T) { \
818 if (!T->isSugared()) \
819 return QualType(T, 0); \
820 QualType desugaredType = recurse(T->desugar()); \
821 if (desugaredType.isNull()) \
823 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
824 return QualType(T, 0); \
825 return desugaredType; \
828 TRIVIAL_TYPE_CLASS(Builtin)
830 QualType VisitComplexType(const ComplexType *T) {
831 QualType elementType = recurse(T->getElementType());
832 if (elementType.isNull())
835 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
836 return QualType(T, 0);
838 return Ctx.getComplexType(elementType);
841 QualType VisitPointerType(const PointerType *T) {
842 QualType pointeeType = recurse(T->getPointeeType());
843 if (pointeeType.isNull())
846 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
847 return QualType(T, 0);
849 return Ctx.getPointerType(pointeeType);
852 QualType VisitBlockPointerType(const BlockPointerType *T) {
853 QualType pointeeType = recurse(T->getPointeeType());
854 if (pointeeType.isNull())
857 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
858 return QualType(T, 0);
860 return Ctx.getBlockPointerType(pointeeType);
863 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
864 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
865 if (pointeeType.isNull())
868 if (pointeeType.getAsOpaquePtr()
869 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
870 return QualType(T, 0);
872 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
875 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
876 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
877 if (pointeeType.isNull())
880 if (pointeeType.getAsOpaquePtr()
881 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
882 return QualType(T, 0);
884 return Ctx.getRValueReferenceType(pointeeType);
887 QualType VisitMemberPointerType(const MemberPointerType *T) {
888 QualType pointeeType = recurse(T->getPointeeType());
889 if (pointeeType.isNull())
892 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
893 return QualType(T, 0);
895 return Ctx.getMemberPointerType(pointeeType, T->getClass());
898 QualType VisitConstantArrayType(const ConstantArrayType *T) {
899 QualType elementType = recurse(T->getElementType());
900 if (elementType.isNull())
903 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
904 return QualType(T, 0);
906 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
907 T->getSizeModifier(),
908 T->getIndexTypeCVRQualifiers());
911 QualType VisitVariableArrayType(const VariableArrayType *T) {
912 QualType elementType = recurse(T->getElementType());
913 if (elementType.isNull())
916 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
917 return QualType(T, 0);
919 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
920 T->getSizeModifier(),
921 T->getIndexTypeCVRQualifiers(),
922 T->getBracketsRange());
925 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
926 QualType elementType = recurse(T->getElementType());
927 if (elementType.isNull())
930 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
931 return QualType(T, 0);
933 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
934 T->getIndexTypeCVRQualifiers());
937 QualType VisitVectorType(const VectorType *T) {
938 QualType elementType = recurse(T->getElementType());
939 if (elementType.isNull())
942 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
943 return QualType(T, 0);
945 return Ctx.getVectorType(elementType, T->getNumElements(),
949 QualType VisitExtVectorType(const ExtVectorType *T) {
950 QualType elementType = recurse(T->getElementType());
951 if (elementType.isNull())
954 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
955 return QualType(T, 0);
957 return Ctx.getExtVectorType(elementType, T->getNumElements());
960 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
961 QualType returnType = recurse(T->getReturnType());
962 if (returnType.isNull())
965 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
966 return QualType(T, 0);
968 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
971 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
972 QualType returnType = recurse(T->getReturnType());
973 if (returnType.isNull())
976 // Transform parameter types.
977 SmallVector<QualType, 4> paramTypes;
978 bool paramChanged = false;
979 for (auto paramType : T->getParamTypes()) {
980 QualType newParamType = recurse(paramType);
981 if (newParamType.isNull())
984 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
987 paramTypes.push_back(newParamType);
990 // Transform extended info.
991 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
992 bool exceptionChanged = false;
993 if (info.ExceptionSpec.Type == EST_Dynamic) {
994 SmallVector<QualType, 4> exceptionTypes;
995 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
996 QualType newExceptionType = recurse(exceptionType);
997 if (newExceptionType.isNull())
1000 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1001 exceptionChanged = true;
1003 exceptionTypes.push_back(newExceptionType);
1006 if (exceptionChanged) {
1007 info.ExceptionSpec.Exceptions =
1008 llvm::makeArrayRef(exceptionTypes).copy(Ctx);
1012 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1013 !paramChanged && !exceptionChanged)
1014 return QualType(T, 0);
1016 return Ctx.getFunctionType(returnType, paramTypes, info);
1019 QualType VisitParenType(const ParenType *T) {
1020 QualType innerType = recurse(T->getInnerType());
1021 if (innerType.isNull())
1024 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1025 return QualType(T, 0);
1027 return Ctx.getParenType(innerType);
1030 SUGARED_TYPE_CLASS(Typedef)
1031 SUGARED_TYPE_CLASS(ObjCTypeParam)
1032 SUGARED_TYPE_CLASS(MacroQualified)
1034 QualType VisitAdjustedType(const AdjustedType *T) {
1035 QualType originalType = recurse(T->getOriginalType());
1036 if (originalType.isNull())
1039 QualType adjustedType = recurse(T->getAdjustedType());
1040 if (adjustedType.isNull())
1043 if (originalType.getAsOpaquePtr()
1044 == T->getOriginalType().getAsOpaquePtr() &&
1045 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1046 return QualType(T, 0);
1048 return Ctx.getAdjustedType(originalType, adjustedType);
1051 QualType VisitDecayedType(const DecayedType *T) {
1052 QualType originalType = recurse(T->getOriginalType());
1053 if (originalType.isNull())
1056 if (originalType.getAsOpaquePtr()
1057 == T->getOriginalType().getAsOpaquePtr())
1058 return QualType(T, 0);
1060 return Ctx.getDecayedType(originalType);
1063 SUGARED_TYPE_CLASS(TypeOfExpr)
1064 SUGARED_TYPE_CLASS(TypeOf)
1065 SUGARED_TYPE_CLASS(Decltype)
1066 SUGARED_TYPE_CLASS(UnaryTransform)
1067 TRIVIAL_TYPE_CLASS(Record)
1068 TRIVIAL_TYPE_CLASS(Enum)
1070 // FIXME: Non-trivial to implement, but important for C++
1071 SUGARED_TYPE_CLASS(Elaborated)
1073 QualType VisitAttributedType(const AttributedType *T) {
1074 QualType modifiedType = recurse(T->getModifiedType());
1075 if (modifiedType.isNull())
1078 QualType equivalentType = recurse(T->getEquivalentType());
1079 if (equivalentType.isNull())
1082 if (modifiedType.getAsOpaquePtr()
1083 == T->getModifiedType().getAsOpaquePtr() &&
1084 equivalentType.getAsOpaquePtr()
1085 == T->getEquivalentType().getAsOpaquePtr())
1086 return QualType(T, 0);
1088 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
1092 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1093 QualType replacementType = recurse(T->getReplacementType());
1094 if (replacementType.isNull())
1097 if (replacementType.getAsOpaquePtr()
1098 == T->getReplacementType().getAsOpaquePtr())
1099 return QualType(T, 0);
1101 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(),
1105 // FIXME: Non-trivial to implement, but important for C++
1106 SUGARED_TYPE_CLASS(TemplateSpecialization)
1108 QualType VisitAutoType(const AutoType *T) {
1109 if (!T->isDeduced())
1110 return QualType(T, 0);
1112 QualType deducedType = recurse(T->getDeducedType());
1113 if (deducedType.isNull())
1116 if (deducedType.getAsOpaquePtr()
1117 == T->getDeducedType().getAsOpaquePtr())
1118 return QualType(T, 0);
1120 return Ctx.getAutoType(deducedType, T->getKeyword(),
1121 T->isDependentType());
1124 // FIXME: Non-trivial to implement, but important for C++
1125 SUGARED_TYPE_CLASS(PackExpansion)
1127 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1128 QualType baseType = recurse(T->getBaseType());
1129 if (baseType.isNull())
1132 // Transform type arguments.
1133 bool typeArgChanged = false;
1134 SmallVector<QualType, 4> typeArgs;
1135 for (auto typeArg : T->getTypeArgsAsWritten()) {
1136 QualType newTypeArg = recurse(typeArg);
1137 if (newTypeArg.isNull())
1140 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1141 typeArgChanged = true;
1143 typeArgs.push_back(newTypeArg);
1146 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1148 return QualType(T, 0);
1150 return Ctx.getObjCObjectType(baseType, typeArgs,
1151 llvm::makeArrayRef(T->qual_begin(),
1152 T->getNumProtocols()),
1153 T->isKindOfTypeAsWritten());
1156 TRIVIAL_TYPE_CLASS(ObjCInterface)
1158 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1159 QualType pointeeType = recurse(T->getPointeeType());
1160 if (pointeeType.isNull())
1163 if (pointeeType.getAsOpaquePtr()
1164 == T->getPointeeType().getAsOpaquePtr())
1165 return QualType(T, 0);
1167 return Ctx.getObjCObjectPointerType(pointeeType);
1170 QualType VisitAtomicType(const AtomicType *T) {
1171 QualType valueType = recurse(T->getValueType());
1172 if (valueType.isNull())
1175 if (valueType.getAsOpaquePtr()
1176 == T->getValueType().getAsOpaquePtr())
1177 return QualType(T, 0);
1179 return Ctx.getAtomicType(valueType);
1182 #undef TRIVIAL_TYPE_CLASS
1183 #undef SUGARED_TYPE_CLASS
1186 struct SubstObjCTypeArgsVisitor
1187 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1188 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1190 ArrayRef<QualType> TypeArgs;
1191 ObjCSubstitutionContext SubstContext;
1193 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1194 ObjCSubstitutionContext context)
1195 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1197 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1198 // Replace an Objective-C type parameter reference with the corresponding
1200 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1201 // If we have type arguments, use them.
1202 if (!TypeArgs.empty()) {
1203 QualType argType = TypeArgs[typeParam->getIndex()];
1204 if (OTPTy->qual_empty())
1207 // Apply protocol lists if exists.
1209 SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
1210 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end());
1211 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1212 return Ctx.applyObjCProtocolQualifiers(
1213 argType, protocolsToApply, hasError, true/*allowOnPointerType*/);
1216 switch (SubstContext) {
1217 case ObjCSubstitutionContext::Ordinary:
1218 case ObjCSubstitutionContext::Parameter:
1219 case ObjCSubstitutionContext::Superclass:
1220 // Substitute the bound.
1221 return typeParam->getUnderlyingType();
1223 case ObjCSubstitutionContext::Result:
1224 case ObjCSubstitutionContext::Property: {
1225 // Substitute the __kindof form of the underlying type.
1226 const auto *objPtr =
1227 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
1229 // __kindof types, id, and Class don't need an additional
1231 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1232 return typeParam->getUnderlyingType();
1235 const auto *obj = objPtr->getObjectType();
1236 QualType resultTy = Ctx.getObjCObjectType(
1237 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
1240 // Rebuild object pointer type.
1241 return Ctx.getObjCObjectPointerType(resultTy);
1244 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1247 QualType VisitFunctionType(const FunctionType *funcType) {
1248 // If we have a function type, update the substitution context
1251 //Substitute result type.
1252 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1253 Ctx, TypeArgs, ObjCSubstitutionContext::Result);
1254 if (returnType.isNull())
1257 // Handle non-prototyped functions, which only substitute into the result
1259 if (isa<FunctionNoProtoType>(funcType)) {
1260 // If the return type was unchanged, do nothing.
1261 if (returnType.getAsOpaquePtr() ==
1262 funcType->getReturnType().getAsOpaquePtr())
1263 return BaseType::VisitFunctionType(funcType);
1265 // Otherwise, build a new type.
1266 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1269 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1271 // Transform parameter types.
1272 SmallVector<QualType, 4> paramTypes;
1273 bool paramChanged = false;
1274 for (auto paramType : funcProtoType->getParamTypes()) {
1275 QualType newParamType = paramType.substObjCTypeArgs(
1276 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter);
1277 if (newParamType.isNull())
1280 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1281 paramChanged = true;
1283 paramTypes.push_back(newParamType);
1286 // Transform extended info.
1287 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1288 bool exceptionChanged = false;
1289 if (info.ExceptionSpec.Type == EST_Dynamic) {
1290 SmallVector<QualType, 4> exceptionTypes;
1291 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1292 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1293 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1294 if (newExceptionType.isNull())
1297 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1298 exceptionChanged = true;
1300 exceptionTypes.push_back(newExceptionType);
1303 if (exceptionChanged) {
1304 info.ExceptionSpec.Exceptions =
1305 llvm::makeArrayRef(exceptionTypes).copy(Ctx);
1309 if (returnType.getAsOpaquePtr() ==
1310 funcProtoType->getReturnType().getAsOpaquePtr() &&
1311 !paramChanged && !exceptionChanged)
1312 return BaseType::VisitFunctionType(funcType);
1314 return Ctx.getFunctionType(returnType, paramTypes, info);
1317 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1318 // Substitute into the type arguments of a specialized Objective-C object
1320 if (objcObjectType->isSpecializedAsWritten()) {
1321 SmallVector<QualType, 4> newTypeArgs;
1322 bool anyChanged = false;
1323 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1324 QualType newTypeArg = typeArg.substObjCTypeArgs(
1325 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1326 if (newTypeArg.isNull())
1329 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1330 // If we're substituting based on an unspecialized context type,
1331 // produce an unspecialized type.
1332 ArrayRef<ObjCProtocolDecl *> protocols(
1333 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1334 if (TypeArgs.empty() &&
1335 SubstContext != ObjCSubstitutionContext::Superclass) {
1336 return Ctx.getObjCObjectType(
1337 objcObjectType->getBaseType(), {}, protocols,
1338 objcObjectType->isKindOfTypeAsWritten());
1344 newTypeArgs.push_back(newTypeArg);
1348 ArrayRef<ObjCProtocolDecl *> protocols(
1349 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1350 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs,
1352 objcObjectType->isKindOfTypeAsWritten());
1356 return BaseType::VisitObjCObjectType(objcObjectType);
1359 QualType VisitAttributedType(const AttributedType *attrType) {
1360 QualType newType = BaseType::VisitAttributedType(attrType);
1361 if (newType.isNull())
1364 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
1365 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1368 // Find out if it's an Objective-C object or object pointer type;
1369 QualType newEquivType = newAttrType->getEquivalentType();
1370 const ObjCObjectPointerType *ptrType =
1371 newEquivType->getAs<ObjCObjectPointerType>();
1372 const ObjCObjectType *objType = ptrType
1373 ? ptrType->getObjectType()
1374 : newEquivType->getAs<ObjCObjectType>();
1378 // Rebuild the "equivalent" type, which pushes __kindof down into
1380 newEquivType = Ctx.getObjCObjectType(
1381 objType->getBaseType(), objType->getTypeArgsAsWritten(),
1382 objType->getProtocols(),
1383 // There is no need to apply kindof on an unqualified id type.
1384 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1386 // If we started with an object pointer type, rebuild it.
1388 newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
1390 // Rebuild the attributed type.
1391 return Ctx.getAttributedType(newAttrType->getAttrKind(),
1392 newAttrType->getModifiedType(), newEquivType);
1396 struct StripObjCKindOfTypeVisitor
1397 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1398 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1400 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1402 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1403 if (!objType->isKindOfType())
1404 return BaseType::VisitObjCObjectType(objType);
1406 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
1407 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
1408 objType->getProtocols(),
1409 /*isKindOf=*/false);
1415 /// Substitute the given type arguments for Objective-C type
1416 /// parameters within the given type, recursively.
1417 QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1418 ArrayRef<QualType> typeArgs,
1419 ObjCSubstitutionContext context) const {
1420 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1421 return visitor.recurse(*this);
1424 QualType QualType::substObjCMemberType(QualType objectType,
1425 const DeclContext *dc,
1426 ObjCSubstitutionContext context) const {
1427 if (auto subs = objectType->getObjCSubstitutions(dc))
1428 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1433 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1434 // FIXME: Because ASTContext::getAttributedType() is non-const.
1435 auto &ctx = const_cast<ASTContext &>(constCtx);
1436 StripObjCKindOfTypeVisitor visitor(ctx);
1437 return visitor.recurse(*this);
1440 QualType QualType::getAtomicUnqualifiedType() const {
1441 if (const auto AT = getTypePtr()->getAs<AtomicType>())
1442 return AT->getValueType().getUnqualifiedType();
1443 return getUnqualifiedType();
1446 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions(
1447 const DeclContext *dc) const {
1448 // Look through method scopes.
1449 if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1450 dc = method->getDeclContext();
1452 // Find the class or category in which the type we're substituting
1454 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1455 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1456 ObjCTypeParamList *dcTypeParams = nullptr;
1458 // If the class does not have any type parameters, there's no
1459 // substitution to do.
1460 dcTypeParams = dcClassDecl->getTypeParamList();
1464 // If we are in neither a class nor a category, there's no
1465 // substitution to perform.
1466 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1467 if (!dcCategoryDecl)
1470 // If the category does not have any type parameters, there's no
1471 // substitution to do.
1472 dcTypeParams = dcCategoryDecl->getTypeParamList();
1476 dcClassDecl = dcCategoryDecl->getClassInterface();
1480 assert(dcTypeParams && "No substitutions to perform");
1481 assert(dcClassDecl && "No class context");
1483 // Find the underlying object type.
1484 const ObjCObjectType *objectType;
1485 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1486 objectType = objectPointerType->getObjectType();
1487 } else if (getAs<BlockPointerType>()) {
1488 ASTContext &ctx = dc->getParentASTContext();
1489 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1490 ->castAs<ObjCObjectType>();
1492 objectType = getAs<ObjCObjectType>();
1495 /// Extract the class from the receiver object type.
1496 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1498 if (!curClassDecl) {
1499 // If we don't have a context type (e.g., this is "id" or some
1500 // variant thereof), substitute the bounds.
1501 return llvm::ArrayRef<QualType>();
1504 // Follow the superclass chain until we've mapped the receiver type
1505 // to the same class as the context.
1506 while (curClassDecl != dcClassDecl) {
1507 // Map to the superclass type.
1508 QualType superType = objectType->getSuperClassType();
1509 if (superType.isNull()) {
1510 objectType = nullptr;
1514 objectType = superType->castAs<ObjCObjectType>();
1515 curClassDecl = objectType->getInterface();
1518 // If we don't have a receiver type, or the receiver type does not
1519 // have type arguments, substitute in the defaults.
1520 if (!objectType || objectType->isUnspecialized()) {
1521 return llvm::ArrayRef<QualType>();
1524 // The receiver type has the type arguments we want.
1525 return objectType->getTypeArgs();
1528 bool Type::acceptsObjCTypeParams() const {
1529 if (auto *IfaceT = getAsObjCInterfaceType()) {
1530 if (auto *ID = IfaceT->getInterface()) {
1531 if (ID->getTypeParamList())
1539 void ObjCObjectType::computeSuperClassTypeSlow() const {
1540 // Retrieve the class declaration for this type. If there isn't one
1541 // (e.g., this is some variant of "id" or "Class"), then there is no
1543 ObjCInterfaceDecl *classDecl = getInterface();
1545 CachedSuperClassType.setInt(true);
1549 // Extract the superclass type.
1550 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1551 if (!superClassObjTy) {
1552 CachedSuperClassType.setInt(true);
1556 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1557 if (!superClassDecl) {
1558 CachedSuperClassType.setInt(true);
1562 // If the superclass doesn't have type parameters, then there is no
1563 // substitution to perform.
1564 QualType superClassType(superClassObjTy, 0);
1565 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1566 if (!superClassTypeParams) {
1567 CachedSuperClassType.setPointerAndInt(
1568 superClassType->castAs<ObjCObjectType>(), true);
1572 // If the superclass reference is unspecialized, return it.
1573 if (superClassObjTy->isUnspecialized()) {
1574 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1578 // If the subclass is not parameterized, there aren't any type
1579 // parameters in the superclass reference to substitute.
1580 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1582 CachedSuperClassType.setPointerAndInt(
1583 superClassType->castAs<ObjCObjectType>(), true);
1587 // If the subclass type isn't specialized, return the unspecialized
1589 if (isUnspecialized()) {
1590 QualType unspecializedSuper
1591 = classDecl->getASTContext().getObjCInterfaceType(
1592 superClassObjTy->getInterface());
1593 CachedSuperClassType.setPointerAndInt(
1594 unspecializedSuper->castAs<ObjCObjectType>(),
1599 // Substitute the provided type arguments into the superclass type.
1600 ArrayRef<QualType> typeArgs = getTypeArgs();
1601 assert(typeArgs.size() == typeParams->size());
1602 CachedSuperClassType.setPointerAndInt(
1603 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1604 ObjCSubstitutionContext::Superclass)
1605 ->castAs<ObjCObjectType>(),
1609 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1610 if (auto interfaceDecl = getObjectType()->getInterface()) {
1611 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1612 ->castAs<ObjCInterfaceType>();
1618 QualType ObjCObjectPointerType::getSuperClassType() const {
1619 QualType superObjectType = getObjectType()->getSuperClassType();
1620 if (superObjectType.isNull())
1621 return superObjectType;
1623 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1624 return ctx.getObjCObjectPointerType(superObjectType);
1627 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1628 // There is no sugar for ObjCObjectType's, just return the canonical
1629 // type pointer if it is the right class. There is no typedef information to
1630 // return and these cannot be Address-space qualified.
1631 if (const auto *T = getAs<ObjCObjectType>())
1632 if (T->getNumProtocols() && T->getInterface())
1637 bool Type::isObjCQualifiedInterfaceType() const {
1638 return getAsObjCQualifiedInterfaceType() != nullptr;
1641 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1642 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1643 // type pointer if it is the right class.
1644 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1645 if (OPT->isObjCQualifiedIdType())
1651 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1652 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1653 // type pointer if it is the right class.
1654 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1655 if (OPT->isObjCQualifiedClassType())
1661 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1662 if (const auto *OT = getAs<ObjCObjectType>()) {
1663 if (OT->getInterface())
1669 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1670 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1671 if (OPT->getInterfaceType())
1677 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1678 QualType PointeeType;
1679 if (const auto *PT = getAs<PointerType>())
1680 PointeeType = PT->getPointeeType();
1681 else if (const auto *RT = getAs<ReferenceType>())
1682 PointeeType = RT->getPointeeType();
1686 if (const auto *RT = PointeeType->getAs<RecordType>())
1687 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1692 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1693 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1696 RecordDecl *Type::getAsRecordDecl() const {
1697 return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1700 TagDecl *Type::getAsTagDecl() const {
1701 if (const auto *TT = getAs<TagType>())
1702 return TT->getDecl();
1703 if (const auto *Injected = getAs<InjectedClassNameType>())
1704 return Injected->getDecl();
1709 bool Type::hasAttr(attr::Kind AK) const {
1710 const Type *Cur = this;
1711 while (const auto *AT = Cur->getAs<AttributedType>()) {
1712 if (AT->getAttrKind() == AK)
1714 Cur = AT->getEquivalentType().getTypePtr();
1721 class GetContainedDeducedTypeVisitor :
1722 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1726 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1727 : Syntactic(Syntactic) {}
1729 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1731 Type *Visit(QualType T) {
1734 return Visit(T.getTypePtr());
1737 // The deduced type itself.
1738 Type *VisitDeducedType(const DeducedType *AT) {
1739 return const_cast<DeducedType*>(AT);
1742 // Only these types can contain the desired 'auto' type.
1744 Type *VisitElaboratedType(const ElaboratedType *T) {
1745 return Visit(T->getNamedType());
1748 Type *VisitPointerType(const PointerType *T) {
1749 return Visit(T->getPointeeType());
1752 Type *VisitBlockPointerType(const BlockPointerType *T) {
1753 return Visit(T->getPointeeType());
1756 Type *VisitReferenceType(const ReferenceType *T) {
1757 return Visit(T->getPointeeTypeAsWritten());
1760 Type *VisitMemberPointerType(const MemberPointerType *T) {
1761 return Visit(T->getPointeeType());
1764 Type *VisitArrayType(const ArrayType *T) {
1765 return Visit(T->getElementType());
1768 Type *VisitDependentSizedExtVectorType(
1769 const DependentSizedExtVectorType *T) {
1770 return Visit(T->getElementType());
1773 Type *VisitVectorType(const VectorType *T) {
1774 return Visit(T->getElementType());
1777 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1778 if (Syntactic && T->hasTrailingReturn())
1779 return const_cast<FunctionProtoType*>(T);
1780 return VisitFunctionType(T);
1783 Type *VisitFunctionType(const FunctionType *T) {
1784 return Visit(T->getReturnType());
1787 Type *VisitParenType(const ParenType *T) {
1788 return Visit(T->getInnerType());
1791 Type *VisitAttributedType(const AttributedType *T) {
1792 return Visit(T->getModifiedType());
1795 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
1796 return Visit(T->getUnderlyingType());
1799 Type *VisitAdjustedType(const AdjustedType *T) {
1800 return Visit(T->getOriginalType());
1803 Type *VisitPackExpansionType(const PackExpansionType *T) {
1804 return Visit(T->getPattern());
1810 DeducedType *Type::getContainedDeducedType() const {
1811 return cast_or_null<DeducedType>(
1812 GetContainedDeducedTypeVisitor().Visit(this));
1815 bool Type::hasAutoForTrailingReturnType() const {
1816 return dyn_cast_or_null<FunctionType>(
1817 GetContainedDeducedTypeVisitor(true).Visit(this));
1820 bool Type::hasIntegerRepresentation() const {
1821 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1822 return VT->getElementType()->isIntegerType();
1824 return isIntegerType();
1827 /// Determine whether this type is an integral type.
1829 /// This routine determines whether the given type is an integral type per
1830 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1831 /// term "integral type", it has a similar term "integer type", and in C++
1832 /// the two terms are equivalent. However, C's "integer type" includes
1833 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1834 /// parameter is used to determine whether we should be following the C or
1835 /// C++ rules when determining whether this type is an integral/integer type.
1837 /// For cases where C permits "an integer type" and C++ permits "an integral
1838 /// type", use this routine.
1840 /// For cases where C permits "an integer type" and C++ permits "an integral
1841 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1843 /// \param Ctx The context in which this type occurs.
1845 /// \returns true if the type is considered an integral type, false otherwise.
1846 bool Type::isIntegralType(const ASTContext &Ctx) const {
1847 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1848 return BT->getKind() >= BuiltinType::Bool &&
1849 BT->getKind() <= BuiltinType::Int128;
1851 // Complete enum types are integral in C.
1852 if (!Ctx.getLangOpts().CPlusPlus)
1853 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1854 return ET->getDecl()->isComplete();
1859 bool Type::isIntegralOrUnscopedEnumerationType() const {
1860 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1861 return BT->getKind() >= BuiltinType::Bool &&
1862 BT->getKind() <= BuiltinType::Int128;
1864 // Check for a complete enum type; incomplete enum types are not properly an
1865 // enumeration type in the sense required here.
1866 // C++0x: However, if the underlying type of the enum is fixed, it is
1867 // considered complete.
1868 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1869 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
1874 bool Type::isCharType() const {
1875 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1876 return BT->getKind() == BuiltinType::Char_U ||
1877 BT->getKind() == BuiltinType::UChar ||
1878 BT->getKind() == BuiltinType::Char_S ||
1879 BT->getKind() == BuiltinType::SChar;
1883 bool Type::isWideCharType() const {
1884 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1885 return BT->getKind() == BuiltinType::WChar_S ||
1886 BT->getKind() == BuiltinType::WChar_U;
1890 bool Type::isChar8Type() const {
1891 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
1892 return BT->getKind() == BuiltinType::Char8;
1896 bool Type::isChar16Type() const {
1897 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1898 return BT->getKind() == BuiltinType::Char16;
1902 bool Type::isChar32Type() const {
1903 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1904 return BT->getKind() == BuiltinType::Char32;
1908 /// Determine whether this type is any of the built-in character
1910 bool Type::isAnyCharacterType() const {
1911 const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
1912 if (!BT) return false;
1913 switch (BT->getKind()) {
1914 default: return false;
1915 case BuiltinType::Char_U:
1916 case BuiltinType::UChar:
1917 case BuiltinType::WChar_U:
1918 case BuiltinType::Char8:
1919 case BuiltinType::Char16:
1920 case BuiltinType::Char32:
1921 case BuiltinType::Char_S:
1922 case BuiltinType::SChar:
1923 case BuiltinType::WChar_S:
1928 /// isSignedIntegerType - Return true if this is an integer type that is
1929 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1930 /// an enum decl which has a signed representation
1931 bool Type::isSignedIntegerType() const {
1932 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1933 return BT->getKind() >= BuiltinType::Char_S &&
1934 BT->getKind() <= BuiltinType::Int128;
1937 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
1938 // Incomplete enum types are not treated as integer types.
1939 // FIXME: In C++, enum types are never integer types.
1940 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1941 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1947 bool Type::isSignedIntegerOrEnumerationType() const {
1948 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1949 return BT->getKind() >= BuiltinType::Char_S &&
1950 BT->getKind() <= BuiltinType::Int128;
1953 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1954 if (ET->getDecl()->isComplete())
1955 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
1961 bool Type::hasSignedIntegerRepresentation() const {
1962 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1963 return VT->getElementType()->isSignedIntegerOrEnumerationType();
1965 return isSignedIntegerOrEnumerationType();
1968 /// isUnsignedIntegerType - Return true if this is an integer type that is
1969 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1970 /// decl which has an unsigned representation
1971 bool Type::isUnsignedIntegerType() const {
1972 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1973 return BT->getKind() >= BuiltinType::Bool &&
1974 BT->getKind() <= BuiltinType::UInt128;
1977 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1978 // Incomplete enum types are not treated as integer types.
1979 // FIXME: In C++, enum types are never integer types.
1980 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
1981 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
1987 bool Type::isUnsignedIntegerOrEnumerationType() const {
1988 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
1989 return BT->getKind() >= BuiltinType::Bool &&
1990 BT->getKind() <= BuiltinType::UInt128;
1993 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
1994 if (ET->getDecl()->isComplete())
1995 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2001 bool Type::hasUnsignedIntegerRepresentation() const {
2002 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2003 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2005 return isUnsignedIntegerOrEnumerationType();
2008 bool Type::isFloatingType() const {
2009 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2010 return BT->getKind() >= BuiltinType::Half &&
2011 BT->getKind() <= BuiltinType::Float128;
2012 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
2013 return CT->getElementType()->isFloatingType();
2017 bool Type::hasFloatingRepresentation() const {
2018 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2019 return VT->getElementType()->isFloatingType();
2021 return isFloatingType();
2024 bool Type::isRealFloatingType() const {
2025 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2026 return BT->isFloatingPoint();
2030 bool Type::isRealType() const {
2031 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2032 return BT->getKind() >= BuiltinType::Bool &&
2033 BT->getKind() <= BuiltinType::Float128;
2034 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2035 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
2039 bool Type::isArithmeticType() const {
2040 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2041 return BT->getKind() >= BuiltinType::Bool &&
2042 BT->getKind() <= BuiltinType::Float128;
2043 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2044 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2045 // If a body isn't seen by the time we get here, return false.
2047 // C++0x: Enumerations are not arithmetic types. For now, just return
2048 // false for scoped enumerations since that will disable any
2049 // unwanted implicit conversions.
2050 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
2051 return isa<ComplexType>(CanonicalType);
2054 Type::ScalarTypeKind Type::getScalarTypeKind() const {
2055 assert(isScalarType());
2057 const Type *T = CanonicalType.getTypePtr();
2058 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
2059 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
2060 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
2061 if (BT->isInteger()) return STK_Integral;
2062 if (BT->isFloatingPoint()) return STK_Floating;
2063 if (BT->isFixedPointType()) return STK_FixedPoint;
2064 llvm_unreachable("unknown scalar builtin type");
2065 } else if (isa<PointerType>(T)) {
2066 return STK_CPointer;
2067 } else if (isa<BlockPointerType>(T)) {
2068 return STK_BlockPointer;
2069 } else if (isa<ObjCObjectPointerType>(T)) {
2070 return STK_ObjCObjectPointer;
2071 } else if (isa<MemberPointerType>(T)) {
2072 return STK_MemberPointer;
2073 } else if (isa<EnumType>(T)) {
2074 assert(cast<EnumType>(T)->getDecl()->isComplete());
2075 return STK_Integral;
2076 } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
2077 if (CT->getElementType()->isRealFloatingType())
2078 return STK_FloatingComplex;
2079 return STK_IntegralComplex;
2082 llvm_unreachable("unknown scalar type");
2085 /// Determines whether the type is a C++ aggregate type or C
2086 /// aggregate or union type.
2088 /// An aggregate type is an array or a class type (struct, union, or
2089 /// class) that has no user-declared constructors, no private or
2090 /// protected non-static data members, no base classes, and no virtual
2091 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2092 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2093 /// includes union types.
2094 bool Type::isAggregateType() const {
2095 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
2096 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
2097 return ClassDecl->isAggregate();
2102 return isa<ArrayType>(CanonicalType);
2105 /// isConstantSizeType - Return true if this is not a variable sized type,
2106 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2107 /// incomplete types or dependent types.
2108 bool Type::isConstantSizeType() const {
2109 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2110 assert(!isDependentType() && "This doesn't make sense for dependent types");
2111 // The VAT must have a size, as it is known to be complete.
2112 return !isa<VariableArrayType>(CanonicalType);
2115 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2116 /// - a type that can describe objects, but which lacks information needed to
2117 /// determine its size.
2118 bool Type::isIncompleteType(NamedDecl **Def) const {
2122 switch (CanonicalType->getTypeClass()) {
2123 default: return false;
2125 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2127 return isVoidType();
2129 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2132 return !EnumD->isComplete();
2135 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2136 // forward declaration, but not a full definition (C99 6.2.5p22).
2137 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2140 return !Rec->isCompleteDefinition();
2143 // An array is incomplete if its element type is incomplete
2144 // (C++ [dcl.array]p1).
2145 // We don't handle variable arrays (they're not allowed in C++) or
2146 // dependent-sized arrays (dependent types are never treated as incomplete).
2147 return cast<ArrayType>(CanonicalType)->getElementType()
2148 ->isIncompleteType(Def);
2149 case IncompleteArray:
2150 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2152 case MemberPointer: {
2153 // Member pointers in the MS ABI have special behavior in
2154 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2155 // to indicate which inheritance model to use.
2156 auto *MPTy = cast<MemberPointerType>(CanonicalType);
2157 const Type *ClassTy = MPTy->getClass();
2158 // Member pointers with dependent class types don't get special treatment.
2159 if (ClassTy->isDependentType())
2161 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2162 ASTContext &Context = RD->getASTContext();
2163 // Member pointers not in the MS ABI don't get special treatment.
2164 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2166 // The inheritance attribute might only be present on the most recent
2167 // CXXRecordDecl, use that one.
2168 RD = RD->getMostRecentNonInjectedDecl();
2169 // Nothing interesting to do if the inheritance attribute is already set.
2170 if (RD->hasAttr<MSInheritanceAttr>())
2175 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2176 ->isIncompleteType(Def);
2177 case ObjCInterface: {
2178 // ObjC interfaces are incomplete if they are @class, not @interface.
2179 ObjCInterfaceDecl *Interface
2180 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2183 return !Interface->hasDefinition();
2188 bool QualType::isPODType(const ASTContext &Context) const {
2189 // C++11 has a more relaxed definition of POD.
2190 if (Context.getLangOpts().CPlusPlus11)
2191 return isCXX11PODType(Context);
2193 return isCXX98PODType(Context);
2196 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2197 // The compiler shouldn't query this for incomplete types, but the user might.
2198 // We return false for that case. Except for incomplete arrays of PODs, which
2199 // are PODs according to the standard.
2203 if ((*this)->isIncompleteArrayType())
2204 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2206 if ((*this)->isIncompleteType())
2209 if (hasNonTrivialObjCLifetime())
2212 QualType CanonicalType = getTypePtr()->CanonicalType;
2213 switch (CanonicalType->getTypeClass()) {
2214 // Everything not explicitly mentioned is not POD.
2215 default: return false;
2216 case Type::VariableArray:
2217 case Type::ConstantArray:
2218 // IncompleteArray is handled above.
2219 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2221 case Type::ObjCObjectPointer:
2222 case Type::BlockPointer:
2226 case Type::MemberPointer:
2228 case Type::ExtVector:
2235 if (const auto *ClassDecl =
2236 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2237 return ClassDecl->isPOD();
2239 // C struct/union is POD.
2244 bool QualType::isTrivialType(const ASTContext &Context) const {
2245 // The compiler shouldn't query this for incomplete types, but the user might.
2246 // We return false for that case. Except for incomplete arrays of PODs, which
2247 // are PODs according to the standard.
2251 if ((*this)->isArrayType())
2252 return Context.getBaseElementType(*this).isTrivialType(Context);
2254 // Return false for incomplete types after skipping any incomplete array
2255 // types which are expressly allowed by the standard and thus our API.
2256 if ((*this)->isIncompleteType())
2259 if (hasNonTrivialObjCLifetime())
2262 QualType CanonicalType = getTypePtr()->CanonicalType;
2263 if (CanonicalType->isDependentType())
2266 // C++0x [basic.types]p9:
2267 // Scalar types, trivial class types, arrays of such types, and
2268 // cv-qualified versions of these types are collectively called trivial
2271 // As an extension, Clang treats vector types as Scalar types.
2272 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2274 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2275 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2277 // A trivial class is a class that has a default constructor,
2278 // has no non-trivial default constructors, and is trivially
2280 return ClassDecl->hasDefaultConstructor() &&
2281 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2282 ClassDecl->isTriviallyCopyable();
2288 // No other types can match.
2292 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2293 if ((*this)->isArrayType())
2294 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2296 if (hasNonTrivialObjCLifetime())
2299 // C++11 [basic.types]p9 - See Core 2094
2300 // Scalar types, trivially copyable class types, arrays of such types, and
2301 // cv-qualified versions of these types are collectively
2302 // called trivially copyable types.
2304 QualType CanonicalType = getCanonicalType();
2305 if (CanonicalType->isDependentType())
2308 // Return false for incomplete types after skipping any incomplete array types
2309 // which are expressly allowed by the standard and thus our API.
2310 if (CanonicalType->isIncompleteType())
2313 // As an extension, Clang treats vector types as Scalar types.
2314 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2317 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2318 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2319 if (!ClassDecl->isTriviallyCopyable()) return false;
2325 // No other types can match.
2329 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2330 return !Context.getLangOpts().ObjCAutoRefCount &&
2331 Context.getLangOpts().ObjCWeak &&
2332 getObjCLifetime() != Qualifiers::OCL_Weak;
2335 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
2336 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2339 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2340 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2343 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2344 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2347 QualType::PrimitiveDefaultInitializeKind
2348 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2349 if (const auto *RT =
2350 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2351 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2354 switch (getQualifiers().getObjCLifetime()) {
2355 case Qualifiers::OCL_Strong:
2356 return PDIK_ARCStrong;
2357 case Qualifiers::OCL_Weak:
2358 return PDIK_ARCWeak;
2360 return PDIK_Trivial;
2364 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2365 if (const auto *RT =
2366 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2367 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2370 Qualifiers Qs = getQualifiers();
2371 switch (Qs.getObjCLifetime()) {
2372 case Qualifiers::OCL_Strong:
2373 return PCK_ARCStrong;
2374 case Qualifiers::OCL_Weak:
2377 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2381 QualType::PrimitiveCopyKind
2382 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2383 return isNonTrivialToPrimitiveCopy();
2386 bool Type::isLiteralType(const ASTContext &Ctx) const {
2387 if (isDependentType())
2390 // C++1y [basic.types]p10:
2391 // A type is a literal type if it is:
2393 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2396 // C++11 [basic.types]p10:
2397 // A type is a literal type if it is:
2399 // -- an array of literal type other than an array of runtime bound; or
2400 if (isVariableArrayType())
2402 const Type *BaseTy = getBaseElementTypeUnsafe();
2403 assert(BaseTy && "NULL element type");
2405 // Return false for incomplete types after skipping any incomplete array
2406 // types; those are expressly allowed by the standard and thus our API.
2407 if (BaseTy->isIncompleteType())
2410 // C++11 [basic.types]p10:
2411 // A type is a literal type if it is:
2412 // -- a scalar type; or
2413 // As an extension, Clang treats vector types and complex types as
2415 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2416 BaseTy->isAnyComplexType())
2418 // -- a reference type; or
2419 if (BaseTy->isReferenceType())
2421 // -- a class type that has all of the following properties:
2422 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2423 // -- a trivial destructor,
2424 // -- every constructor call and full-expression in the
2425 // brace-or-equal-initializers for non-static data members (if any)
2426 // is a constant expression,
2427 // -- it is an aggregate type or has at least one constexpr
2428 // constructor or constructor template that is not a copy or move
2430 // -- all non-static data members and base classes of literal types
2432 // We resolve DR1361 by ignoring the second bullet.
2433 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2434 return ClassDecl->isLiteral();
2439 // We treat _Atomic T as a literal type if T is a literal type.
2440 if (const auto *AT = BaseTy->getAs<AtomicType>())
2441 return AT->getValueType()->isLiteralType(Ctx);
2443 // If this type hasn't been deduced yet, then conservatively assume that
2444 // it'll work out to be a literal type.
2445 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2451 bool Type::isStandardLayoutType() const {
2452 if (isDependentType())
2455 // C++0x [basic.types]p9:
2456 // Scalar types, standard-layout class types, arrays of such types, and
2457 // cv-qualified versions of these types are collectively called
2458 // standard-layout types.
2459 const Type *BaseTy = getBaseElementTypeUnsafe();
2460 assert(BaseTy && "NULL element type");
2462 // Return false for incomplete types after skipping any incomplete array
2463 // types which are expressly allowed by the standard and thus our API.
2464 if (BaseTy->isIncompleteType())
2467 // As an extension, Clang treats vector types as Scalar types.
2468 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2469 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2470 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2471 if (!ClassDecl->isStandardLayout())
2474 // Default to 'true' for non-C++ class types.
2475 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2476 // all the requirements of standard layout classes.
2480 // No other types can match.
2484 // This is effectively the intersection of isTrivialType and
2485 // isStandardLayoutType. We implement it directly to avoid redundant
2486 // conversions from a type to a CXXRecordDecl.
2487 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2488 const Type *ty = getTypePtr();
2489 if (ty->isDependentType())
2492 if (hasNonTrivialObjCLifetime())
2495 // C++11 [basic.types]p9:
2496 // Scalar types, POD classes, arrays of such types, and cv-qualified
2497 // versions of these types are collectively called trivial types.
2498 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2499 assert(BaseTy && "NULL element type");
2501 // Return false for incomplete types after skipping any incomplete array
2502 // types which are expressly allowed by the standard and thus our API.
2503 if (BaseTy->isIncompleteType())
2506 // As an extension, Clang treats vector types as Scalar types.
2507 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2508 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2509 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2510 // C++11 [class]p10:
2511 // A POD struct is a non-union class that is both a trivial class [...]
2512 if (!ClassDecl->isTrivial()) return false;
2514 // C++11 [class]p10:
2515 // A POD struct is a non-union class that is both a trivial class and
2516 // a standard-layout class [...]
2517 if (!ClassDecl->isStandardLayout()) return false;
2519 // C++11 [class]p10:
2520 // A POD struct is a non-union class that is both a trivial class and
2521 // a standard-layout class, and has no non-static data members of type
2522 // non-POD struct, non-POD union (or array of such types). [...]
2524 // We don't directly query the recursive aspect as the requirements for
2525 // both standard-layout classes and trivial classes apply recursively
2532 // No other types can match.
2536 bool Type::isNothrowT() const {
2537 if (const auto *RD = getAsCXXRecordDecl()) {
2538 IdentifierInfo *II = RD->getIdentifier();
2539 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2545 bool Type::isAlignValT() const {
2546 if (const auto *ET = getAs<EnumType>()) {
2547 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2548 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2554 bool Type::isStdByteType() const {
2555 if (const auto *ET = getAs<EnumType>()) {
2556 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2557 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2563 bool Type::isPromotableIntegerType() const {
2564 if (const auto *BT = getAs<BuiltinType>())
2565 switch (BT->getKind()) {
2566 case BuiltinType::Bool:
2567 case BuiltinType::Char_S:
2568 case BuiltinType::Char_U:
2569 case BuiltinType::SChar:
2570 case BuiltinType::UChar:
2571 case BuiltinType::Short:
2572 case BuiltinType::UShort:
2573 case BuiltinType::WChar_S:
2574 case BuiltinType::WChar_U:
2575 case BuiltinType::Char8:
2576 case BuiltinType::Char16:
2577 case BuiltinType::Char32:
2583 // Enumerated types are promotable to their compatible integer types
2584 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2585 if (const auto *ET = getAs<EnumType>()){
2586 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2587 || ET->getDecl()->isScoped())
2596 bool Type::isSpecifierType() const {
2597 // Note that this intentionally does not use the canonical type.
2598 switch (getTypeClass()) {
2606 case TemplateTypeParm:
2607 case SubstTemplateTypeParm:
2608 case TemplateSpecialization:
2611 case DependentTemplateSpecialization:
2614 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2621 ElaboratedTypeKeyword
2622 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2624 default: return ETK_None;
2625 case TST_typename: return ETK_Typename;
2626 case TST_class: return ETK_Class;
2627 case TST_struct: return ETK_Struct;
2628 case TST_interface: return ETK_Interface;
2629 case TST_union: return ETK_Union;
2630 case TST_enum: return ETK_Enum;
2635 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2637 case TST_class: return TTK_Class;
2638 case TST_struct: return TTK_Struct;
2639 case TST_interface: return TTK_Interface;
2640 case TST_union: return TTK_Union;
2641 case TST_enum: return TTK_Enum;
2644 llvm_unreachable("Type specifier is not a tag type kind.");
2647 ElaboratedTypeKeyword
2648 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2650 case TTK_Class: return ETK_Class;
2651 case TTK_Struct: return ETK_Struct;
2652 case TTK_Interface: return ETK_Interface;
2653 case TTK_Union: return ETK_Union;
2654 case TTK_Enum: return ETK_Enum;
2656 llvm_unreachable("Unknown tag type kind.");
2660 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2662 case ETK_Class: return TTK_Class;
2663 case ETK_Struct: return TTK_Struct;
2664 case ETK_Interface: return TTK_Interface;
2665 case ETK_Union: return TTK_Union;
2666 case ETK_Enum: return TTK_Enum;
2667 case ETK_None: // Fall through.
2669 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2671 llvm_unreachable("Unknown elaborated type keyword.");
2675 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2687 llvm_unreachable("Unknown elaborated type keyword.");
2690 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2692 case ETK_None: return {};
2693 case ETK_Typename: return "typename";
2694 case ETK_Class: return "class";
2695 case ETK_Struct: return "struct";
2696 case ETK_Interface: return "__interface";
2697 case ETK_Union: return "union";
2698 case ETK_Enum: return "enum";
2701 llvm_unreachable("Unknown elaborated type keyword.");
2704 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2705 ElaboratedTypeKeyword Keyword,
2706 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
2707 ArrayRef<TemplateArgument> Args,
2709 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
2710 /*VariablyModified=*/false,
2711 NNS && NNS->containsUnexpandedParameterPack()),
2712 NNS(NNS), Name(Name) {
2713 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
2714 assert((!NNS || NNS->isDependent()) &&
2715 "DependentTemplateSpecializatonType requires dependent qualifier");
2716 TemplateArgument *ArgBuffer = getArgBuffer();
2717 for (const TemplateArgument &Arg : Args) {
2718 if (Arg.containsUnexpandedParameterPack())
2719 setContainsUnexpandedParameterPack();
2721 new (ArgBuffer++) TemplateArgument(Arg);
2726 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2727 const ASTContext &Context,
2728 ElaboratedTypeKeyword Keyword,
2729 NestedNameSpecifier *Qualifier,
2730 const IdentifierInfo *Name,
2731 ArrayRef<TemplateArgument> Args) {
2732 ID.AddInteger(Keyword);
2733 ID.AddPointer(Qualifier);
2734 ID.AddPointer(Name);
2735 for (const TemplateArgument &Arg : Args)
2736 Arg.Profile(ID, Context);
2739 bool Type::isElaboratedTypeSpecifier() const {
2740 ElaboratedTypeKeyword Keyword;
2741 if (const auto *Elab = dyn_cast<ElaboratedType>(this))
2742 Keyword = Elab->getKeyword();
2743 else if (const auto *DepName = dyn_cast<DependentNameType>(this))
2744 Keyword = DepName->getKeyword();
2745 else if (const auto *DepTST =
2746 dyn_cast<DependentTemplateSpecializationType>(this))
2747 Keyword = DepTST->getKeyword();
2751 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2754 const char *Type::getTypeClassName() const {
2755 switch (TypeBits.TC) {
2756 #define ABSTRACT_TYPE(Derived, Base)
2757 #define TYPE(Derived, Base) case Derived: return #Derived;
2758 #include "clang/AST/TypeNodes.inc"
2761 llvm_unreachable("Invalid type class.");
2764 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2765 switch (getKind()) {
2769 return Policy.Bool ? "bool" : "_Bool";
2775 return "signed char";
2787 return "unsigned char";
2789 return "unsigned short";
2791 return "unsigned int";
2793 return "unsigned long";
2795 return "unsigned long long";
2797 return "unsigned __int128";
2799 return Policy.Half ? "half" : "__fp16";
2805 return "long double";
2807 return "short _Accum";
2811 return "long _Accum";
2813 return "unsigned short _Accum";
2815 return "unsigned _Accum";
2817 return "unsigned long _Accum";
2818 case BuiltinType::ShortFract:
2819 return "short _Fract";
2820 case BuiltinType::Fract:
2822 case BuiltinType::LongFract:
2823 return "long _Fract";
2824 case BuiltinType::UShortFract:
2825 return "unsigned short _Fract";
2826 case BuiltinType::UFract:
2827 return "unsigned _Fract";
2828 case BuiltinType::ULongFract:
2829 return "unsigned long _Fract";
2830 case BuiltinType::SatShortAccum:
2831 return "_Sat short _Accum";
2832 case BuiltinType::SatAccum:
2833 return "_Sat _Accum";
2834 case BuiltinType::SatLongAccum:
2835 return "_Sat long _Accum";
2836 case BuiltinType::SatUShortAccum:
2837 return "_Sat unsigned short _Accum";
2838 case BuiltinType::SatUAccum:
2839 return "_Sat unsigned _Accum";
2840 case BuiltinType::SatULongAccum:
2841 return "_Sat unsigned long _Accum";
2842 case BuiltinType::SatShortFract:
2843 return "_Sat short _Fract";
2844 case BuiltinType::SatFract:
2845 return "_Sat _Fract";
2846 case BuiltinType::SatLongFract:
2847 return "_Sat long _Fract";
2848 case BuiltinType::SatUShortFract:
2849 return "_Sat unsigned short _Fract";
2850 case BuiltinType::SatUFract:
2851 return "_Sat unsigned _Fract";
2852 case BuiltinType::SatULongFract:
2853 return "_Sat unsigned long _Fract";
2857 return "__float128";
2860 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2870 return "<overloaded function type>";
2872 return "<bound member function type>";
2874 return "<pseudo-object type>";
2876 return "<dependent type>";
2878 return "<unknown type>";
2879 case ARCUnbridgedCast:
2880 return "<ARC unbridged cast type>";
2882 return "<builtin fn type>";
2889 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2891 return "__" #Access " " #ImgType "_t";
2892 #include "clang/Basic/OpenCLImageTypes.def"
2898 return "clk_event_t";
2902 return "reserve_id_t";
2903 case OMPArraySection:
2904 return "<OpenMP array section type>";
2905 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2908 #include "clang/Basic/OpenCLExtensionTypes.def"
2909 #define SVE_TYPE(Name, Id, SingletonId) \
2912 #include "clang/Basic/AArch64SVEACLETypes.def"
2915 llvm_unreachable("Invalid builtin type.");
2918 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
2919 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
2920 return RefType->getPointeeType();
2922 // C++0x [basic.lval]:
2923 // Class prvalues can have cv-qualified types; non-class prvalues always
2924 // have cv-unqualified types.
2926 // See also C99 6.3.2.1p2.
2927 if (!Context.getLangOpts().CPlusPlus ||
2928 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
2929 return getUnqualifiedType();
2934 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
2936 case CC_C: return "cdecl";
2937 case CC_X86StdCall: return "stdcall";
2938 case CC_X86FastCall: return "fastcall";
2939 case CC_X86ThisCall: return "thiscall";
2940 case CC_X86Pascal: return "pascal";
2941 case CC_X86VectorCall: return "vectorcall";
2942 case CC_Win64: return "ms_abi";
2943 case CC_X86_64SysV: return "sysv_abi";
2944 case CC_X86RegCall : return "regcall";
2945 case CC_AAPCS: return "aapcs";
2946 case CC_AAPCS_VFP: return "aapcs-vfp";
2947 case CC_AArch64VectorCall: return "aarch64_vector_pcs";
2948 case CC_IntelOclBicc: return "intel_ocl_bicc";
2949 case CC_SpirFunction: return "spir_function";
2950 case CC_OpenCLKernel: return "opencl_kernel";
2951 case CC_Swift: return "swiftcall";
2952 case CC_PreserveMost: return "preserve_most";
2953 case CC_PreserveAll: return "preserve_all";
2956 llvm_unreachable("Invalid calling convention.");
2959 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
2961 const ExtProtoInfo &epi)
2962 : FunctionType(FunctionProto, result, canonical, result->isDependentType(),
2963 result->isInstantiationDependentType(),
2964 result->isVariablyModifiedType(),
2965 result->containsUnexpandedParameterPack(), epi.ExtInfo) {
2966 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
2967 FunctionTypeBits.RefQualifier = epi.RefQualifier;
2968 FunctionTypeBits.NumParams = params.size();
2969 assert(getNumParams() == params.size() && "NumParams overflow!");
2970 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
2971 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
2972 FunctionTypeBits.Variadic = epi.Variadic;
2973 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
2975 // Fill in the extra trailing bitfields if present.
2976 if (hasExtraBitfields(epi.ExceptionSpec.Type)) {
2977 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
2978 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
2981 // Fill in the trailing argument array.
2982 auto *argSlot = getTrailingObjects<QualType>();
2983 for (unsigned i = 0; i != getNumParams(); ++i) {
2984 if (params[i]->isDependentType())
2986 else if (params[i]->isInstantiationDependentType())
2987 setInstantiationDependent();
2989 if (params[i]->containsUnexpandedParameterPack())
2990 setContainsUnexpandedParameterPack();
2992 argSlot[i] = params[i];
2995 // Fill in the exception type array if present.
2996 if (getExceptionSpecType() == EST_Dynamic) {
2997 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
2999 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3001 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3002 // Note that, before C++17, a dependent exception specification does
3003 // *not* make a type dependent; it's not even part of the C++ type
3005 if (ExceptionType->isInstantiationDependentType())
3006 setInstantiationDependent();
3008 if (ExceptionType->containsUnexpandedParameterPack())
3009 setContainsUnexpandedParameterPack();
3011 exnSlot[I++] = ExceptionType;
3014 // Fill in the Expr * in the exception specification if present.
3015 else if (isComputedNoexcept(getExceptionSpecType())) {
3016 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3017 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3018 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3020 // Store the noexcept expression and context.
3021 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3023 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
3024 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
3025 setInstantiationDependent();
3027 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
3028 setContainsUnexpandedParameterPack();
3030 // Fill in the FunctionDecl * in the exception specification if present.
3031 else if (getExceptionSpecType() == EST_Uninstantiated) {
3032 // Store the function decl from which we will resolve our
3033 // exception specification.
3034 auto **slot = getTrailingObjects<FunctionDecl *>();
3035 slot[0] = epi.ExceptionSpec.SourceDecl;
3036 slot[1] = epi.ExceptionSpec.SourceTemplate;
3037 // This exception specification doesn't make the type dependent, because
3038 // it's not instantiated as part of instantiating the type.
3039 } else if (getExceptionSpecType() == EST_Unevaluated) {
3040 // Store the function decl from which we will resolve our
3041 // exception specification.
3042 auto **slot = getTrailingObjects<FunctionDecl *>();
3043 slot[0] = epi.ExceptionSpec.SourceDecl;
3046 // If this is a canonical type, and its exception specification is dependent,
3047 // then it's a dependent type. This only happens in C++17 onwards.
3048 if (isCanonicalUnqualified()) {
3049 if (getExceptionSpecType() == EST_Dynamic ||
3050 getExceptionSpecType() == EST_DependentNoexcept) {
3051 assert(hasDependentExceptionSpec() && "type should not be canonical");
3054 } else if (getCanonicalTypeInternal()->isDependentType()) {
3055 // Ask our canonical type whether our exception specification was dependent.
3059 // Fill in the extra parameter info if present.
3060 if (epi.ExtParameterInfos) {
3061 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3062 for (unsigned i = 0; i != getNumParams(); ++i)
3063 extParamInfos[i] = epi.ExtParameterInfos[i];
3066 if (epi.TypeQuals.hasNonFastQualifiers()) {
3067 FunctionTypeBits.HasExtQuals = 1;
3068 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3070 FunctionTypeBits.HasExtQuals = 0;
3074 bool FunctionProtoType::hasDependentExceptionSpec() const {
3075 if (Expr *NE = getNoexceptExpr())
3076 return NE->isValueDependent();
3077 for (QualType ET : exceptions())
3078 // A pack expansion with a non-dependent pattern is still dependent,
3079 // because we don't know whether the pattern is in the exception spec
3080 // or not (that depends on whether the pack has 0 expansions).
3081 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3086 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3087 if (Expr *NE = getNoexceptExpr())
3088 return NE->isInstantiationDependent();
3089 for (QualType ET : exceptions())
3090 if (ET->isInstantiationDependentType())
3095 CanThrowResult FunctionProtoType::canThrow() const {
3096 switch (getExceptionSpecType()) {
3098 case EST_Unevaluated:
3099 case EST_Uninstantiated:
3100 llvm_unreachable("should not call this with unresolved exception specs");
3102 case EST_DynamicNone:
3103 case EST_BasicNoexcept:
3104 case EST_NoexceptTrue:
3110 case EST_NoexceptFalse:
3114 // A dynamic exception specification is throwing unless every exception
3115 // type is an (unexpanded) pack expansion type.
3116 for (unsigned I = 0; I != getNumExceptions(); ++I)
3117 if (!getExceptionType(I)->getAs<PackExpansionType>())
3119 return CT_Dependent;
3121 case EST_DependentNoexcept:
3122 return CT_Dependent;
3125 llvm_unreachable("unexpected exception specification kind");
3128 bool FunctionProtoType::isTemplateVariadic() const {
3129 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3130 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3136 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3137 const QualType *ArgTys, unsigned NumParams,
3138 const ExtProtoInfo &epi,
3139 const ASTContext &Context, bool Canonical) {
3140 // We have to be careful not to get ambiguous profile encodings.
3141 // Note that valid type pointers are never ambiguous with anything else.
3143 // The encoding grammar begins:
3144 // type type* bool int bool
3145 // If that final bool is true, then there is a section for the EH spec:
3147 // This is followed by an optional "consumed argument" section of the
3148 // same length as the first type sequence:
3150 // Finally, we have the ext info and trailing return type flag:
3153 // There is no ambiguity between the consumed arguments and an empty EH
3154 // spec because of the leading 'bool' which unambiguously indicates
3155 // whether the following bool is the EH spec or part of the arguments.
3157 ID.AddPointer(Result.getAsOpaquePtr());
3158 for (unsigned i = 0; i != NumParams; ++i)
3159 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3160 // This method is relatively performance sensitive, so as a performance
3161 // shortcut, use one AddInteger call instead of four for the next four
3163 assert(!(unsigned(epi.Variadic) & ~1) &&
3164 !(unsigned(epi.RefQualifier) & ~3) &&
3165 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3166 "Values larger than expected.");
3167 ID.AddInteger(unsigned(epi.Variadic) +
3168 (epi.RefQualifier << 1) +
3169 (epi.ExceptionSpec.Type << 3));
3170 ID.Add(epi.TypeQuals);
3171 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3172 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3173 ID.AddPointer(Ex.getAsOpaquePtr());
3174 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3175 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3176 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3177 epi.ExceptionSpec.Type == EST_Unevaluated) {
3178 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3180 if (epi.ExtParameterInfos) {
3181 for (unsigned i = 0; i != NumParams; ++i)
3182 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3184 epi.ExtInfo.Profile(ID);
3185 ID.AddBoolean(epi.HasTrailingReturn);
3188 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3189 const ASTContext &Ctx) {
3190 Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3191 getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3194 QualType TypedefType::desugar() const {
3195 return getDecl()->getUnderlyingType();
3198 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3200 QualType MacroQualifiedType::getModifiedType() const {
3201 // Step over MacroQualifiedTypes from the same macro to find the type
3202 // ultimately qualified by the macro qualifier.
3203 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3204 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3205 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3207 Inner = InnerMQT->getModifiedType();
3212 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
3213 : Type(TypeOfExpr, can, E->isTypeDependent(),
3214 E->isInstantiationDependent(),
3215 E->getType()->isVariablyModifiedType(),
3216 E->containsUnexpandedParameterPack()),
3219 bool TypeOfExprType::isSugared() const {
3220 return !TOExpr->isTypeDependent();
3223 QualType TypeOfExprType::desugar() const {
3225 return getUnderlyingExpr()->getType();
3227 return QualType(this, 0);
3230 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3231 const ASTContext &Context, Expr *E) {
3232 E->Profile(ID, Context, true);
3235 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3236 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3237 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3238 // type-dependent even if its expression is only instantiation-dependent.
3239 : Type(Decltype, can, E->isInstantiationDependent(),
3240 E->isInstantiationDependent(),
3241 E->getType()->isVariablyModifiedType(),
3242 E->containsUnexpandedParameterPack()),
3243 E(E), UnderlyingType(underlyingType) {}
3245 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3247 QualType DecltypeType::desugar() const {
3249 return getUnderlyingType();
3251 return QualType(this, 0);
3254 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
3255 : DecltypeType(E, Context.DependentTy), Context(Context) {}
3257 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3258 const ASTContext &Context, Expr *E) {
3259 E->Profile(ID, Context, true);
3262 UnaryTransformType::UnaryTransformType(QualType BaseType,
3263 QualType UnderlyingType,
3265 QualType CanonicalType)
3266 : Type(UnaryTransform, CanonicalType, BaseType->isDependentType(),
3267 BaseType->isInstantiationDependentType(),
3268 BaseType->isVariablyModifiedType(),
3269 BaseType->containsUnexpandedParameterPack()),
3270 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3272 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3275 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3277 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3278 : Type(TC, can, D->isDependentType(),
3279 /*InstantiationDependent=*/D->isDependentType(),
3280 /*VariablyModified=*/false,
3281 /*ContainsUnexpandedParameterPack=*/false),
3282 decl(const_cast<TagDecl*>(D)) {}
3284 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3285 for (auto I : decl->redecls()) {
3286 if (I->isCompleteDefinition() || I->isBeingDefined())
3289 // If there's no definition (not even in progress), return what we have.
3293 TagDecl *TagType::getDecl() const {
3294 return getInterestingTagDecl(decl);
3297 bool TagType::isBeingDefined() const {
3298 return getDecl()->isBeingDefined();
3301 bool RecordType::hasConstFields() const {
3302 std::vector<const RecordType*> RecordTypeList;
3303 RecordTypeList.push_back(this);
3304 unsigned NextToCheckIndex = 0;
3306 while (RecordTypeList.size() > NextToCheckIndex) {
3307 for (FieldDecl *FD :
3308 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3309 QualType FieldTy = FD->getType();
3310 if (FieldTy.isConstQualified())
3312 FieldTy = FieldTy.getCanonicalType();
3313 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3314 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
3315 RecordTypeList.push_back(FieldRecTy);
3323 bool AttributedType::isQualifier() const {
3324 // FIXME: Generate this with TableGen.
3325 switch (getAttrKind()) {
3326 // These are type qualifiers in the traditional C sense: they annotate
3327 // something about a specific value/variable of a type. (They aren't
3328 // always part of the canonical type, though.)
3330 case attr::ObjCOwnership:
3331 case attr::ObjCInertUnsafeUnretained:
3332 case attr::TypeNonNull:
3333 case attr::TypeNullable:
3334 case attr::TypeNullUnspecified:
3335 case attr::LifetimeBound:
3336 case attr::AddressSpace:
3339 // All other type attributes aren't qualifiers; they rewrite the modified
3340 // type to be a semantically different type.
3346 bool AttributedType::isMSTypeSpec() const {
3347 // FIXME: Generate this with TableGen?
3348 switch (getAttrKind()) {
3349 default: return false;
3356 llvm_unreachable("invalid attr kind");
3359 bool AttributedType::isCallingConv() const {
3360 // FIXME: Generate this with TableGen.
3361 switch (getAttrKind()) {
3362 default: return false;
3365 case attr::FastCall:
3367 case attr::ThisCall:
3369 case attr::SwiftCall:
3370 case attr::VectorCall:
3371 case attr::AArch64VectorPcs:
3375 case attr::IntelOclBicc:
3376 case attr::PreserveMost:
3377 case attr::PreserveAll:
3380 llvm_unreachable("invalid attr kind");
3383 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3384 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3387 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3388 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3391 SubstTemplateTypeParmPackType::
3392 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3394 const TemplateArgument &ArgPack)
3395 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
3396 Replaced(Param), Arguments(ArgPack.pack_begin()) {
3397 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3400 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3401 return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs()));
3404 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3405 Profile(ID, getReplacedParameter(), getArgumentPack());
3408 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3409 const TemplateTypeParmType *Replaced,
3410 const TemplateArgument &ArgPack) {
3411 ID.AddPointer(Replaced);
3412 ID.AddInteger(ArgPack.pack_size());
3413 for (const auto &P : ArgPack.pack_elements())
3414 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3417 bool TemplateSpecializationType::
3418 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
3419 bool &InstantiationDependent) {
3420 return anyDependentTemplateArguments(Args.arguments(),
3421 InstantiationDependent);
3424 bool TemplateSpecializationType::
3425 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3426 bool &InstantiationDependent) {
3427 for (const TemplateArgumentLoc &ArgLoc : Args) {
3428 if (ArgLoc.getArgument().isDependent()) {
3429 InstantiationDependent = true;
3433 if (ArgLoc.getArgument().isInstantiationDependent())
3434 InstantiationDependent = true;
3439 TemplateSpecializationType::
3440 TemplateSpecializationType(TemplateName T,
3441 ArrayRef<TemplateArgument> Args,
3442 QualType Canon, QualType AliasedType)
3443 : Type(TemplateSpecialization,
3444 Canon.isNull()? QualType(this, 0) : Canon,
3445 Canon.isNull()? true : Canon->isDependentType(),
3446 Canon.isNull()? true : Canon->isInstantiationDependentType(),
3448 T.containsUnexpandedParameterPack()), Template(T) {
3449 TemplateSpecializationTypeBits.NumArgs = Args.size();
3450 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3452 assert(!T.getAsDependentTemplateName() &&
3453 "Use DependentTemplateSpecializationType for dependent template-name");
3454 assert((T.getKind() == TemplateName::Template ||
3455 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3456 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
3457 "Unexpected template name for TemplateSpecializationType");
3459 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3460 for (const TemplateArgument &Arg : Args) {
3461 // Update instantiation-dependent and variably-modified bits.
3462 // If the canonical type exists and is non-dependent, the template
3463 // specialization type can be non-dependent even if one of the type
3464 // arguments is. Given:
3465 // template<typename T> using U = int;
3466 // U<T> is always non-dependent, irrespective of the type T.
3467 // However, U<Ts> contains an unexpanded parameter pack, even though
3468 // its expansion (and thus its desugared type) doesn't.
3469 if (Arg.isInstantiationDependent())
3470 setInstantiationDependent();
3471 if (Arg.getKind() == TemplateArgument::Type &&
3472 Arg.getAsType()->isVariablyModifiedType())
3473 setVariablyModified();
3474 if (Arg.containsUnexpandedParameterPack())
3475 setContainsUnexpandedParameterPack();
3476 new (TemplateArgs++) TemplateArgument(Arg);
3479 // Store the aliased type if this is a type alias template specialization.
3480 if (isTypeAlias()) {
3481 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3482 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3487 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3489 ArrayRef<TemplateArgument> Args,
3490 const ASTContext &Context) {
3492 for (const TemplateArgument &Arg : Args)
3493 Arg.Profile(ID, Context);
3497 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3498 if (!hasNonFastQualifiers())
3499 return QT.withFastQualifiers(getFastQualifiers());
3501 return Context.getQualifiedType(QT, *this);
3505 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3506 if (!hasNonFastQualifiers())
3507 return QualType(T, getFastQualifiers());
3509 return Context.getQualifiedType(T, *this);
3512 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3514 ArrayRef<QualType> typeArgs,
3515 ArrayRef<ObjCProtocolDecl *> protocols,
3517 ID.AddPointer(BaseType.getAsOpaquePtr());
3518 ID.AddInteger(typeArgs.size());
3519 for (auto typeArg : typeArgs)
3520 ID.AddPointer(typeArg.getAsOpaquePtr());
3521 ID.AddInteger(protocols.size());
3522 for (auto proto : protocols)
3523 ID.AddPointer(proto);
3524 ID.AddBoolean(isKindOf);
3527 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3528 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3529 llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3530 isKindOfTypeAsWritten());
3533 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3534 const ObjCTypeParamDecl *OTPDecl,
3535 ArrayRef<ObjCProtocolDecl *> protocols) {
3536 ID.AddPointer(OTPDecl);
3537 ID.AddInteger(protocols.size());
3538 for (auto proto : protocols)
3539 ID.AddPointer(proto);
3542 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3543 Profile(ID, getDecl(),
3544 llvm::makeArrayRef(qual_begin(), getNumProtocols()));
3549 /// The cached properties of a type.
3550 class CachedProperties {
3555 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3557 Linkage getLinkage() const { return L; }
3558 bool hasLocalOrUnnamedType() const { return local; }
3560 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3561 Linkage MergedLinkage = minLinkage(L.L, R.L);
3562 return CachedProperties(MergedLinkage,
3563 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3569 static CachedProperties computeCachedProperties(const Type *T);
3573 /// The type-property cache. This is templated so as to be
3574 /// instantiated at an internal type to prevent unnecessary symbol
3576 template <class Private> class TypePropertyCache {
3578 static CachedProperties get(QualType T) {
3579 return get(T.getTypePtr());
3582 static CachedProperties get(const Type *T) {
3584 return CachedProperties(T->TypeBits.getLinkage(),
3585 T->TypeBits.hasLocalOrUnnamedType());
3588 static void ensure(const Type *T) {
3589 // If the cache is valid, we're okay.
3590 if (T->TypeBits.isCacheValid()) return;
3592 // If this type is non-canonical, ask its canonical type for the
3593 // relevant information.
3594 if (!T->isCanonicalUnqualified()) {
3595 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3597 T->TypeBits.CacheValid = true;
3598 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3599 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3603 // Compute the cached properties and then set the cache.
3604 CachedProperties Result = computeCachedProperties(T);
3605 T->TypeBits.CacheValid = true;
3606 T->TypeBits.CachedLinkage = Result.getLinkage();
3607 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3611 } // namespace clang
3613 // Instantiate the friend template at a private class. In a
3614 // reasonable implementation, these symbols will be internal.
3615 // It is terrible that this is the best way to accomplish this.
3622 using Cache = TypePropertyCache<Private>;
3624 static CachedProperties computeCachedProperties(const Type *T) {
3625 switch (T->getTypeClass()) {
3626 #define TYPE(Class,Base)
3627 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3628 #include "clang/AST/TypeNodes.inc"
3629 llvm_unreachable("didn't expect a non-canonical type here");
3631 #define TYPE(Class,Base)
3632 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3633 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3634 #include "clang/AST/TypeNodes.inc"
3635 // Treat instantiation-dependent types as external.
3636 if (!T->isInstantiationDependentType()) T->dump();
3637 assert(T->isInstantiationDependentType());
3638 return CachedProperties(ExternalLinkage, false);
3641 case Type::DeducedTemplateSpecialization:
3642 // Give non-deduced 'auto' types external linkage. We should only see them
3643 // here in error recovery.
3644 return CachedProperties(ExternalLinkage, false);
3647 // C++ [basic.link]p8:
3648 // A type is said to have linkage if and only if:
3649 // - it is a fundamental type (3.9.1); or
3650 return CachedProperties(ExternalLinkage, false);
3654 const TagDecl *Tag = cast<TagType>(T)->getDecl();
3656 // C++ [basic.link]p8:
3657 // - it is a class or enumeration type that is named (or has a name
3658 // for linkage purposes (7.1.3)) and the name has linkage; or
3659 // - it is a specialization of a class template (14); or
3660 Linkage L = Tag->getLinkageInternal();
3661 bool IsLocalOrUnnamed =
3662 Tag->getDeclContext()->isFunctionOrMethod() ||
3663 !Tag->hasNameForLinkage();
3664 return CachedProperties(L, IsLocalOrUnnamed);
3667 // C++ [basic.link]p8:
3668 // - it is a compound type (3.9.2) other than a class or enumeration,
3669 // compounded exclusively from types that have linkage; or
3671 return Cache::get(cast<ComplexType>(T)->getElementType());
3673 return Cache::get(cast<PointerType>(T)->getPointeeType());
3674 case Type::BlockPointer:
3675 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3676 case Type::LValueReference:
3677 case Type::RValueReference:
3678 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3679 case Type::MemberPointer: {
3680 const auto *MPT = cast<MemberPointerType>(T);
3681 return merge(Cache::get(MPT->getClass()),
3682 Cache::get(MPT->getPointeeType()));
3684 case Type::ConstantArray:
3685 case Type::IncompleteArray:
3686 case Type::VariableArray:
3687 return Cache::get(cast<ArrayType>(T)->getElementType());
3689 case Type::ExtVector:
3690 return Cache::get(cast<VectorType>(T)->getElementType());
3691 case Type::FunctionNoProto:
3692 return Cache::get(cast<FunctionType>(T)->getReturnType());
3693 case Type::FunctionProto: {
3694 const auto *FPT = cast<FunctionProtoType>(T);
3695 CachedProperties result = Cache::get(FPT->getReturnType());
3696 for (const auto &ai : FPT->param_types())
3697 result = merge(result, Cache::get(ai));
3700 case Type::ObjCInterface: {
3701 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3702 return CachedProperties(L, false);
3704 case Type::ObjCObject:
3705 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3706 case Type::ObjCObjectPointer:
3707 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3709 return Cache::get(cast<AtomicType>(T)->getValueType());
3711 return Cache::get(cast<PipeType>(T)->getElementType());
3714 llvm_unreachable("unhandled type class");
3717 /// Determine the linkage of this type.
3718 Linkage Type::getLinkage() const {
3719 Cache::ensure(this);
3720 return TypeBits.getLinkage();
3723 bool Type::hasUnnamedOrLocalType() const {
3724 Cache::ensure(this);
3725 return TypeBits.hasLocalOrUnnamedType();
3728 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
3729 switch (T->getTypeClass()) {
3730 #define TYPE(Class,Base)
3731 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3732 #include "clang/AST/TypeNodes.inc"
3733 llvm_unreachable("didn't expect a non-canonical type here");
3735 #define TYPE(Class,Base)
3736 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3737 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3738 #include "clang/AST/TypeNodes.inc"
3739 // Treat instantiation-dependent types as external.
3740 assert(T->isInstantiationDependentType());
3741 return LinkageInfo::external();
3744 return LinkageInfo::external();
3747 case Type::DeducedTemplateSpecialization:
3748 return LinkageInfo::external();
3752 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
3755 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
3757 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3758 case Type::BlockPointer:
3759 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3760 case Type::LValueReference:
3761 case Type::RValueReference:
3762 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3763 case Type::MemberPointer: {
3764 const auto *MPT = cast<MemberPointerType>(T);
3765 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
3766 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
3769 case Type::ConstantArray:
3770 case Type::IncompleteArray:
3771 case Type::VariableArray:
3772 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
3774 case Type::ExtVector:
3775 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
3776 case Type::FunctionNoProto:
3777 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3778 case Type::FunctionProto: {
3779 const auto *FPT = cast<FunctionProtoType>(T);
3780 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
3781 for (const auto &ai : FPT->param_types())
3782 LV.merge(computeTypeLinkageInfo(ai));
3785 case Type::ObjCInterface:
3786 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
3787 case Type::ObjCObject:
3788 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3789 case Type::ObjCObjectPointer:
3790 return computeTypeLinkageInfo(
3791 cast<ObjCObjectPointerType>(T)->getPointeeType());
3793 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
3795 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
3798 llvm_unreachable("unhandled type class");
3801 bool Type::isLinkageValid() const {
3802 if (!TypeBits.isCacheValid())
3805 Linkage L = LinkageComputer{}
3806 .computeTypeLinkageInfo(getCanonicalTypeInternal())
3808 return L == TypeBits.getLinkage();
3811 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
3812 if (!T->isCanonicalUnqualified())
3813 return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
3815 LinkageInfo LV = computeTypeLinkageInfo(T);
3816 assert(LV.getLinkage() == T->getLinkage());
3820 LinkageInfo Type::getLinkageAndVisibility() const {
3821 return LinkageComputer{}.getTypeLinkageAndVisibility(this);
3824 Optional<NullabilityKind>
3825 Type::getNullability(const ASTContext &Context) const {
3826 QualType Type(this, 0);
3827 while (const auto *AT = Type->getAs<AttributedType>()) {
3828 // Check whether this is an attributed type with nullability
3830 if (auto Nullability = AT->getImmediateNullability())
3833 Type = AT->getEquivalentType();
3838 bool Type::canHaveNullability(bool ResultIfUnknown) const {
3839 QualType type = getCanonicalTypeInternal();
3841 switch (type->getTypeClass()) {
3842 // We'll only see canonical types here.
3843 #define NON_CANONICAL_TYPE(Class, Parent) \
3845 llvm_unreachable("non-canonical type");
3846 #define TYPE(Class, Parent)
3847 #include "clang/AST/TypeNodes.inc"
3851 case Type::BlockPointer:
3852 case Type::MemberPointer:
3853 case Type::ObjCObjectPointer:
3856 // Dependent types that could instantiate to pointer types.
3857 case Type::UnresolvedUsing:
3858 case Type::TypeOfExpr:
3860 case Type::Decltype:
3861 case Type::UnaryTransform:
3862 case Type::TemplateTypeParm:
3863 case Type::SubstTemplateTypeParmPack:
3864 case Type::DependentName:
3865 case Type::DependentTemplateSpecialization:
3867 return ResultIfUnknown;
3869 // Dependent template specializations can instantiate to pointer
3870 // types unless they're known to be specializations of a class
3872 case Type::TemplateSpecialization:
3873 if (TemplateDecl *templateDecl
3874 = cast<TemplateSpecializationType>(type.getTypePtr())
3875 ->getTemplateName().getAsTemplateDecl()) {
3876 if (isa<ClassTemplateDecl>(templateDecl))
3879 return ResultIfUnknown;
3882 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
3883 // Signed, unsigned, and floating-point types cannot have nullability.
3884 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3885 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
3886 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
3887 #define BUILTIN_TYPE(Id, SingletonId)
3888 #include "clang/AST/BuiltinTypes.def"
3891 // Dependent types that could instantiate to a pointer type.
3892 case BuiltinType::Dependent:
3893 case BuiltinType::Overload:
3894 case BuiltinType::BoundMember:
3895 case BuiltinType::PseudoObject:
3896 case BuiltinType::UnknownAny:
3897 case BuiltinType::ARCUnbridgedCast:
3898 return ResultIfUnknown;
3900 case BuiltinType::Void:
3901 case BuiltinType::ObjCId:
3902 case BuiltinType::ObjCClass:
3903 case BuiltinType::ObjCSel:
3904 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3905 case BuiltinType::Id:
3906 #include "clang/Basic/OpenCLImageTypes.def"
3907 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3908 case BuiltinType::Id:
3909 #include "clang/Basic/OpenCLExtensionTypes.def"
3910 case BuiltinType::OCLSampler:
3911 case BuiltinType::OCLEvent:
3912 case BuiltinType::OCLClkEvent:
3913 case BuiltinType::OCLQueue:
3914 case BuiltinType::OCLReserveID:
3915 #define SVE_TYPE(Name, Id, SingletonId) \
3916 case BuiltinType::Id:
3917 #include "clang/Basic/AArch64SVEACLETypes.def"
3918 case BuiltinType::BuiltinFn:
3919 case BuiltinType::NullPtr:
3920 case BuiltinType::OMPArraySection:
3923 llvm_unreachable("unknown builtin type");
3925 // Non-pointer types.
3927 case Type::LValueReference:
3928 case Type::RValueReference:
3929 case Type::ConstantArray:
3930 case Type::IncompleteArray:
3931 case Type::VariableArray:
3932 case Type::DependentSizedArray:
3933 case Type::DependentVector:
3934 case Type::DependentSizedExtVector:
3936 case Type::ExtVector:
3937 case Type::DependentAddressSpace:
3938 case Type::FunctionProto:
3939 case Type::FunctionNoProto:
3941 case Type::DeducedTemplateSpecialization:
3943 case Type::InjectedClassName:
3944 case Type::PackExpansion:
3945 case Type::ObjCObject:
3946 case Type::ObjCInterface:
3951 llvm_unreachable("bad type kind!");
3954 llvm::Optional<NullabilityKind>
3955 AttributedType::getImmediateNullability() const {
3956 if (getAttrKind() == attr::TypeNonNull)
3957 return NullabilityKind::NonNull;
3958 if (getAttrKind() == attr::TypeNullable)
3959 return NullabilityKind::Nullable;
3960 if (getAttrKind() == attr::TypeNullUnspecified)
3961 return NullabilityKind::Unspecified;
3965 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
3966 QualType AttrTy = T;
3967 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
3968 AttrTy = MacroTy->getUnderlyingType();
3970 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
3971 if (auto nullability = attributed->getImmediateNullability()) {
3972 T = attributed->getModifiedType();
3980 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
3981 const auto *objcPtr = getAs<ObjCObjectPointerType>();
3985 if (objcPtr->isObjCIdType()) {
3986 // id is always okay.
3990 // Blocks are NSObjects.
3991 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
3992 if (iface->getIdentifier() != ctx.getNSObjectName())
3995 // Continue to check qualifiers, below.
3996 } else if (objcPtr->isObjCQualifiedIdType()) {
3997 // Continue to check qualifiers, below.
4002 // Check protocol qualifiers.
4003 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4004 // Blocks conform to NSObject and NSCopying.
4005 if (proto->getIdentifier() != ctx.getNSObjectName() &&
4006 proto->getIdentifier() != ctx.getNSCopyingName())
4013 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
4014 if (isObjCARCImplicitlyUnretainedType())
4015 return Qualifiers::OCL_ExplicitNone;
4016 return Qualifiers::OCL_Strong;
4019 bool Type::isObjCARCImplicitlyUnretainedType() const {
4020 assert(isObjCLifetimeType() &&
4021 "cannot query implicit lifetime for non-inferrable type");
4023 const Type *canon = getCanonicalTypeInternal().getTypePtr();
4025 // Walk down to the base type. We don't care about qualifiers for this.
4026 while (const auto *array = dyn_cast<ArrayType>(canon))
4027 canon = array->getElementType().getTypePtr();
4029 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4030 // Class and Class<Protocol> don't require retention.
4031 if (opt->getObjectType()->isObjCClass())
4038 bool Type::isObjCNSObjectType() const {
4039 const Type *cur = this;
4041 if (const auto *typedefType = dyn_cast<TypedefType>(cur))
4042 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4044 // Single-step desugar until we run out of sugar.
4045 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
4046 if (next.getTypePtr() == cur) return false;
4047 cur = next.getTypePtr();
4051 bool Type::isObjCIndependentClassType() const {
4052 if (const auto *typedefType = dyn_cast<TypedefType>(this))
4053 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4057 bool Type::isObjCRetainableType() const {
4058 return isObjCObjectPointerType() ||
4059 isBlockPointerType() ||
4060 isObjCNSObjectType();
4063 bool Type::isObjCIndirectLifetimeType() const {
4064 if (isObjCLifetimeType())
4066 if (const auto *OPT = getAs<PointerType>())
4067 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4068 if (const auto *Ref = getAs<ReferenceType>())
4069 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4070 if (const auto *MemPtr = getAs<MemberPointerType>())
4071 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4075 /// Returns true if objects of this type have lifetime semantics under
4077 bool Type::isObjCLifetimeType() const {
4078 const Type *type = this;
4079 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4080 type = array->getElementType().getTypePtr();
4081 return type->isObjCRetainableType();
4084 /// Determine whether the given type T is a "bridgable" Objective-C type,
4085 /// which is either an Objective-C object pointer type or an
4086 bool Type::isObjCARCBridgableType() const {
4087 return isObjCObjectPointerType() || isBlockPointerType();
4090 /// Determine whether the given type T is a "bridgeable" C type.
4091 bool Type::isCARCBridgableType() const {
4092 const auto *Pointer = getAs<PointerType>();
4096 QualType Pointee = Pointer->getPointeeType();
4097 return Pointee->isVoidType() || Pointee->isRecordType();
4100 bool Type::hasSizedVLAType() const {
4101 if (!isVariablyModifiedType()) return false;
4103 if (const auto *ptr = getAs<PointerType>())
4104 return ptr->getPointeeType()->hasSizedVLAType();
4105 if (const auto *ref = getAs<ReferenceType>())
4106 return ref->getPointeeType()->hasSizedVLAType();
4107 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4108 if (isa<VariableArrayType>(arr) &&
4109 cast<VariableArrayType>(arr)->getSizeExpr())
4112 return arr->getElementType()->hasSizedVLAType();
4118 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4119 switch (type.getObjCLifetime()) {
4120 case Qualifiers::OCL_None:
4121 case Qualifiers::OCL_ExplicitNone:
4122 case Qualifiers::OCL_Autoreleasing:
4125 case Qualifiers::OCL_Strong:
4126 return DK_objc_strong_lifetime;
4127 case Qualifiers::OCL_Weak:
4128 return DK_objc_weak_lifetime;
4131 if (const auto *RT =
4132 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4133 const RecordDecl *RD = RT->getDecl();
4134 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4135 /// Check if this is a C++ object with a non-trivial destructor.
4136 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4137 return DK_cxx_destructor;
4139 /// Check if this is a C struct that is non-trivial to destroy or an array
4140 /// that contains such a struct.
4141 if (RD->isNonTrivialToPrimitiveDestroy())
4142 return DK_nontrivial_c_struct;
4149 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
4150 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4153 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
4154 llvm::APSInt Val, unsigned Scale) {
4155 FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4156 /*IsSaturated=*/false,
4157 /*HasUnsignedPadding=*/false);
4158 APFixedPoint(Val, FXSema).toString(Str);