1 //===--- Type.cpp - Type representation and manipulation ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related functionality.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/Type.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/Specifiers.h"
24 #include "llvm/ADT/APSInt.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
31 return (*this != Other) &&
32 // CVR qualifiers superset
33 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
34 // ObjC GC qualifiers superset
35 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
36 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
37 // Address space superset.
38 ((getAddressSpace() == Other.getAddressSpace()) ||
39 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
40 // Lifetime qualifier superset.
41 ((getObjCLifetime() == Other.getObjCLifetime()) ||
42 (hasObjCLifetime() && !Other.hasObjCLifetime()));
45 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
46 const Type* ty = getTypePtr();
48 if (ty->isPointerType() || ty->isReferenceType())
49 return ty->getPointeeType().getBaseTypeIdentifier();
50 else if (ty->isRecordType())
51 ND = ty->getAs<RecordType>()->getDecl();
52 else if (ty->isEnumeralType())
53 ND = ty->getAs<EnumType>()->getDecl();
54 else if (ty->getTypeClass() == Type::Typedef)
55 ND = ty->getAs<TypedefType>()->getDecl();
56 else if (ty->isArrayType())
57 return ty->castAsArrayTypeUnsafe()->
58 getElementType().getBaseTypeIdentifier();
61 return ND->getIdentifier();
65 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
66 if (T.isConstQualified())
69 if (const ArrayType *AT = Ctx.getAsArrayType(T))
70 return AT->getElementType().isConstant(Ctx);
75 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
77 const llvm::APInt &NumElements) {
78 llvm::APSInt SizeExtended(NumElements, true);
79 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
80 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
81 SizeExtended.getBitWidth()) * 2);
84 = Context.getTypeSizeInChars(ElementType).getQuantity();
85 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
86 TotalSize *= SizeExtended;
88 return TotalSize.getActiveBits();
91 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
92 unsigned Bits = Context.getTypeSize(Context.getSizeType());
94 // GCC appears to only allow 63 bits worth of address space when compiling
95 // for 64-bit, so we do the same.
102 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
103 QualType et, QualType can,
104 Expr *e, ArraySizeModifier sm,
106 SourceRange brackets)
107 : ArrayType(DependentSizedArray, et, can, sm, tq,
108 (et->containsUnexpandedParameterPack() ||
109 (e && e->containsUnexpandedParameterPack()))),
110 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
114 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
115 const ASTContext &Context,
117 ArraySizeModifier SizeMod,
120 ID.AddPointer(ET.getAsOpaquePtr());
121 ID.AddInteger(SizeMod);
122 ID.AddInteger(TypeQuals);
123 E->Profile(ID, Context, true);
126 DependentSizedExtVectorType::DependentSizedExtVectorType(const
128 QualType ElementType,
132 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
133 /*InstantiationDependent=*/true,
134 ElementType->isVariablyModifiedType(),
135 (ElementType->containsUnexpandedParameterPack() ||
136 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
137 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
143 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
144 const ASTContext &Context,
145 QualType ElementType, Expr *SizeExpr) {
146 ID.AddPointer(ElementType.getAsOpaquePtr());
147 SizeExpr->Profile(ID, Context, true);
150 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
152 : Type(Vector, canonType, vecType->isDependentType(),
153 vecType->isInstantiationDependentType(),
154 vecType->isVariablyModifiedType(),
155 vecType->containsUnexpandedParameterPack()),
158 VectorTypeBits.VecKind = vecKind;
159 VectorTypeBits.NumElements = nElements;
162 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
163 QualType canonType, VectorKind vecKind)
164 : Type(tc, canonType, vecType->isDependentType(),
165 vecType->isInstantiationDependentType(),
166 vecType->isVariablyModifiedType(),
167 vecType->containsUnexpandedParameterPack()),
170 VectorTypeBits.VecKind = vecKind;
171 VectorTypeBits.NumElements = nElements;
174 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
175 /// element type of the array, potentially with type qualifiers missing.
176 /// This method should never be used when type qualifiers are meaningful.
177 const Type *Type::getArrayElementTypeNoTypeQual() const {
178 // If this is directly an array type, return it.
179 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
180 return ATy->getElementType().getTypePtr();
182 // If the canonical form of this type isn't the right kind, reject it.
183 if (!isa<ArrayType>(CanonicalType))
186 // If this is a typedef for an array type, strip the typedef off without
187 // losing all typedef information.
188 return cast<ArrayType>(getUnqualifiedDesugaredType())
189 ->getElementType().getTypePtr();
192 /// getDesugaredType - Return the specified type with any "sugar" removed from
193 /// the type. This takes off typedefs, typeof's etc. If the outer level of
194 /// the type is already concrete, it returns it unmodified. This is similar
195 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
196 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
198 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
199 SplitQualType split = getSplitDesugaredType(T);
200 return Context.getQualifiedType(split.Ty, split.Quals);
203 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
204 const ASTContext &Context) {
205 SplitQualType split = type.split();
206 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
207 return Context.getQualifiedType(desugar, split.Quals);
210 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
211 switch (getTypeClass()) {
212 #define ABSTRACT_TYPE(Class, Parent)
213 #define TYPE(Class, Parent) \
214 case Type::Class: { \
215 const Class##Type *ty = cast<Class##Type>(this); \
216 if (!ty->isSugared()) return QualType(ty, 0); \
217 return ty->desugar(); \
219 #include "clang/AST/TypeNodes.def"
221 llvm_unreachable("bad type kind!");
224 SplitQualType QualType::getSplitDesugaredType(QualType T) {
225 QualifierCollector Qs;
229 const Type *CurTy = Qs.strip(Cur);
230 switch (CurTy->getTypeClass()) {
231 #define ABSTRACT_TYPE(Class, Parent)
232 #define TYPE(Class, Parent) \
233 case Type::Class: { \
234 const Class##Type *Ty = cast<Class##Type>(CurTy); \
235 if (!Ty->isSugared()) \
236 return SplitQualType(Ty, Qs); \
237 Cur = Ty->desugar(); \
240 #include "clang/AST/TypeNodes.def"
245 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
246 SplitQualType split = type.split();
248 // All the qualifiers we've seen so far.
249 Qualifiers quals = split.Quals;
251 // The last type node we saw with any nodes inside it.
252 const Type *lastTypeWithQuals = split.Ty;
257 // Do a single-step desugar, aborting the loop if the type isn't
259 switch (split.Ty->getTypeClass()) {
260 #define ABSTRACT_TYPE(Class, Parent)
261 #define TYPE(Class, Parent) \
262 case Type::Class: { \
263 const Class##Type *ty = cast<Class##Type>(split.Ty); \
264 if (!ty->isSugared()) goto done; \
265 next = ty->desugar(); \
268 #include "clang/AST/TypeNodes.def"
271 // Otherwise, split the underlying type. If that yields qualifiers,
272 // update the information.
273 split = next.split();
274 if (!split.Quals.empty()) {
275 lastTypeWithQuals = split.Ty;
276 quals.addConsistentQualifiers(split.Quals);
281 return SplitQualType(lastTypeWithQuals, quals);
284 QualType QualType::IgnoreParens(QualType T) {
285 // FIXME: this seems inherently un-qualifiers-safe.
286 while (const ParenType *PT = T->getAs<ParenType>())
287 T = PT->getInnerType();
291 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
292 /// sugar off the given type. This should produce an object of the
293 /// same dynamic type as the canonical type.
294 const Type *Type::getUnqualifiedDesugaredType() const {
295 const Type *Cur = this;
298 switch (Cur->getTypeClass()) {
299 #define ABSTRACT_TYPE(Class, Parent)
300 #define TYPE(Class, Parent) \
302 const Class##Type *Ty = cast<Class##Type>(Cur); \
303 if (!Ty->isSugared()) return Cur; \
304 Cur = Ty->desugar().getTypePtr(); \
307 #include "clang/AST/TypeNodes.def"
312 bool Type::isDerivedType() const {
313 switch (CanonicalType->getTypeClass()) {
317 case IncompleteArray:
319 case FunctionNoProto:
320 case LValueReference:
321 case RValueReference:
328 bool Type::isClassType() const {
329 if (const RecordType *RT = getAs<RecordType>())
330 return RT->getDecl()->isClass();
333 bool Type::isStructureType() const {
334 if (const RecordType *RT = getAs<RecordType>())
335 return RT->getDecl()->isStruct();
338 bool Type::isStructureOrClassType() const {
339 if (const RecordType *RT = getAs<RecordType>())
340 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
343 bool Type::isVoidPointerType() const {
344 if (const PointerType *PT = getAs<PointerType>())
345 return PT->getPointeeType()->isVoidType();
349 bool Type::isUnionType() const {
350 if (const RecordType *RT = getAs<RecordType>())
351 return RT->getDecl()->isUnion();
355 bool Type::isComplexType() const {
356 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
357 return CT->getElementType()->isFloatingType();
361 bool Type::isComplexIntegerType() const {
362 // Check for GCC complex integer extension.
363 return getAsComplexIntegerType();
366 const ComplexType *Type::getAsComplexIntegerType() const {
367 if (const ComplexType *Complex = getAs<ComplexType>())
368 if (Complex->getElementType()->isIntegerType())
373 QualType Type::getPointeeType() const {
374 if (const PointerType *PT = getAs<PointerType>())
375 return PT->getPointeeType();
376 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
377 return OPT->getPointeeType();
378 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
379 return BPT->getPointeeType();
380 if (const ReferenceType *RT = getAs<ReferenceType>())
381 return RT->getPointeeType();
385 const RecordType *Type::getAsStructureType() const {
386 // If this is directly a structure type, return it.
387 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
388 if (RT->getDecl()->isStruct())
392 // If the canonical form of this type isn't the right kind, reject it.
393 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
394 if (!RT->getDecl()->isStruct())
397 // If this is a typedef for a structure type, strip the typedef off without
398 // losing all typedef information.
399 return cast<RecordType>(getUnqualifiedDesugaredType());
404 const RecordType *Type::getAsUnionType() const {
405 // If this is directly a union type, return it.
406 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
407 if (RT->getDecl()->isUnion())
411 // If the canonical form of this type isn't the right kind, reject it.
412 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
413 if (!RT->getDecl()->isUnion())
416 // If this is a typedef for a union type, strip the typedef off without
417 // losing all typedef information.
418 return cast<RecordType>(getUnqualifiedDesugaredType());
424 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
425 ObjCProtocolDecl * const *Protocols,
426 unsigned NumProtocols)
427 : Type(ObjCObject, Canonical, false, false, false, false),
430 ObjCObjectTypeBits.NumProtocols = NumProtocols;
431 assert(getNumProtocols() == NumProtocols &&
432 "bitfield overflow in protocol count");
434 memcpy(getProtocolStorage(), Protocols,
435 NumProtocols * sizeof(ObjCProtocolDecl*));
438 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
439 // There is no sugar for ObjCObjectType's, just return the canonical
440 // type pointer if it is the right class. There is no typedef information to
441 // return and these cannot be Address-space qualified.
442 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
443 if (T->getNumProtocols() && T->getInterface())
448 bool Type::isObjCQualifiedInterfaceType() const {
449 return getAsObjCQualifiedInterfaceType() != 0;
452 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
453 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
454 // type pointer if it is the right class.
455 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
456 if (OPT->isObjCQualifiedIdType())
462 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
463 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
464 // type pointer if it is the right class.
465 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
466 if (OPT->isObjCQualifiedClassType())
472 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
473 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
474 if (OPT->getInterfaceType())
480 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
481 if (const PointerType *PT = getAs<PointerType>())
482 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
483 return dyn_cast<CXXRecordDecl>(RT->getDecl());
487 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
488 if (const RecordType *RT = getAs<RecordType>())
489 return dyn_cast<CXXRecordDecl>(RT->getDecl());
490 else if (const InjectedClassNameType *Injected
491 = getAs<InjectedClassNameType>())
492 return Injected->getDecl();
498 class GetContainedAutoVisitor :
499 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
501 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
502 AutoType *Visit(QualType T) {
505 return Visit(T.getTypePtr());
508 // The 'auto' type itself.
509 AutoType *VisitAutoType(const AutoType *AT) {
510 return const_cast<AutoType*>(AT);
513 // Only these types can contain the desired 'auto' type.
514 AutoType *VisitPointerType(const PointerType *T) {
515 return Visit(T->getPointeeType());
517 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
518 return Visit(T->getPointeeType());
520 AutoType *VisitReferenceType(const ReferenceType *T) {
521 return Visit(T->getPointeeTypeAsWritten());
523 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
524 return Visit(T->getPointeeType());
526 AutoType *VisitArrayType(const ArrayType *T) {
527 return Visit(T->getElementType());
529 AutoType *VisitDependentSizedExtVectorType(
530 const DependentSizedExtVectorType *T) {
531 return Visit(T->getElementType());
533 AutoType *VisitVectorType(const VectorType *T) {
534 return Visit(T->getElementType());
536 AutoType *VisitFunctionType(const FunctionType *T) {
537 return Visit(T->getResultType());
539 AutoType *VisitParenType(const ParenType *T) {
540 return Visit(T->getInnerType());
542 AutoType *VisitAttributedType(const AttributedType *T) {
543 return Visit(T->getModifiedType());
548 AutoType *Type::getContainedAutoType() const {
549 return GetContainedAutoVisitor().Visit(this);
552 bool Type::hasIntegerRepresentation() const {
553 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
554 return VT->getElementType()->isIntegerType();
556 return isIntegerType();
559 /// \brief Determine whether this type is an integral type.
561 /// This routine determines whether the given type is an integral type per
562 /// C++ [basic.fundamental]p7. Although the C standard does not define the
563 /// term "integral type", it has a similar term "integer type", and in C++
564 /// the two terms are equivalent. However, C's "integer type" includes
565 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
566 /// parameter is used to determine whether we should be following the C or
567 /// C++ rules when determining whether this type is an integral/integer type.
569 /// For cases where C permits "an integer type" and C++ permits "an integral
570 /// type", use this routine.
572 /// For cases where C permits "an integer type" and C++ permits "an integral
573 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
575 /// \param Ctx The context in which this type occurs.
577 /// \returns true if the type is considered an integral type, false otherwise.
578 bool Type::isIntegralType(ASTContext &Ctx) const {
579 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
580 return BT->getKind() >= BuiltinType::Bool &&
581 BT->getKind() <= BuiltinType::Int128;
583 if (!Ctx.getLangOpts().CPlusPlus)
584 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
585 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
591 bool Type::isIntegralOrUnscopedEnumerationType() const {
592 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
593 return BT->getKind() >= BuiltinType::Bool &&
594 BT->getKind() <= BuiltinType::Int128;
596 // Check for a complete enum type; incomplete enum types are not properly an
597 // enumeration type in the sense required here.
598 // C++0x: However, if the underlying type of the enum is fixed, it is
599 // considered complete.
600 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
601 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
608 bool Type::isCharType() const {
609 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
610 return BT->getKind() == BuiltinType::Char_U ||
611 BT->getKind() == BuiltinType::UChar ||
612 BT->getKind() == BuiltinType::Char_S ||
613 BT->getKind() == BuiltinType::SChar;
617 bool Type::isWideCharType() const {
618 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
619 return BT->getKind() == BuiltinType::WChar_S ||
620 BT->getKind() == BuiltinType::WChar_U;
624 bool Type::isChar16Type() const {
625 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
626 return BT->getKind() == BuiltinType::Char16;
630 bool Type::isChar32Type() const {
631 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
632 return BT->getKind() == BuiltinType::Char32;
636 /// \brief Determine whether this type is any of the built-in character
638 bool Type::isAnyCharacterType() const {
639 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
640 if (BT == 0) return false;
641 switch (BT->getKind()) {
642 default: return false;
643 case BuiltinType::Char_U:
644 case BuiltinType::UChar:
645 case BuiltinType::WChar_U:
646 case BuiltinType::Char16:
647 case BuiltinType::Char32:
648 case BuiltinType::Char_S:
649 case BuiltinType::SChar:
650 case BuiltinType::WChar_S:
655 /// isSignedIntegerType - Return true if this is an integer type that is
656 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
657 /// an enum decl which has a signed representation
658 bool Type::isSignedIntegerType() const {
659 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
660 return BT->getKind() >= BuiltinType::Char_S &&
661 BT->getKind() <= BuiltinType::Int128;
664 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
665 // Incomplete enum types are not treated as integer types.
666 // FIXME: In C++, enum types are never integer types.
667 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
668 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
674 bool Type::isSignedIntegerOrEnumerationType() const {
675 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
676 return BT->getKind() >= BuiltinType::Char_S &&
677 BT->getKind() <= BuiltinType::Int128;
680 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
681 if (ET->getDecl()->isComplete())
682 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
688 bool Type::hasSignedIntegerRepresentation() const {
689 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
690 return VT->getElementType()->isSignedIntegerType();
692 return isSignedIntegerType();
695 /// isUnsignedIntegerType - Return true if this is an integer type that is
696 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
697 /// decl which has an unsigned representation
698 bool Type::isUnsignedIntegerType() const {
699 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
700 return BT->getKind() >= BuiltinType::Bool &&
701 BT->getKind() <= BuiltinType::UInt128;
704 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
705 // Incomplete enum types are not treated as integer types.
706 // FIXME: In C++, enum types are never integer types.
707 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
708 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
714 bool Type::isUnsignedIntegerOrEnumerationType() const {
715 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
716 return BT->getKind() >= BuiltinType::Bool &&
717 BT->getKind() <= BuiltinType::UInt128;
720 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
721 if (ET->getDecl()->isComplete())
722 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
728 bool Type::hasUnsignedIntegerRepresentation() const {
729 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
730 return VT->getElementType()->isUnsignedIntegerType();
732 return isUnsignedIntegerType();
735 bool Type::isFloatingType() const {
736 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
737 return BT->getKind() >= BuiltinType::Half &&
738 BT->getKind() <= BuiltinType::LongDouble;
739 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
740 return CT->getElementType()->isFloatingType();
744 bool Type::hasFloatingRepresentation() const {
745 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
746 return VT->getElementType()->isFloatingType();
748 return isFloatingType();
751 bool Type::isRealFloatingType() const {
752 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
753 return BT->isFloatingPoint();
757 bool Type::isRealType() const {
758 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
759 return BT->getKind() >= BuiltinType::Bool &&
760 BT->getKind() <= BuiltinType::LongDouble;
761 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
762 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
766 bool Type::isArithmeticType() const {
767 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
768 return BT->getKind() >= BuiltinType::Bool &&
769 BT->getKind() <= BuiltinType::LongDouble;
770 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
771 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
772 // If a body isn't seen by the time we get here, return false.
774 // C++0x: Enumerations are not arithmetic types. For now, just return
775 // false for scoped enumerations since that will disable any
776 // unwanted implicit conversions.
777 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
778 return isa<ComplexType>(CanonicalType);
781 Type::ScalarTypeKind Type::getScalarTypeKind() const {
782 assert(isScalarType());
784 const Type *T = CanonicalType.getTypePtr();
785 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
786 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
787 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
788 if (BT->isInteger()) return STK_Integral;
789 if (BT->isFloatingPoint()) return STK_Floating;
790 llvm_unreachable("unknown scalar builtin type");
791 } else if (isa<PointerType>(T)) {
793 } else if (isa<BlockPointerType>(T)) {
794 return STK_BlockPointer;
795 } else if (isa<ObjCObjectPointerType>(T)) {
796 return STK_ObjCObjectPointer;
797 } else if (isa<MemberPointerType>(T)) {
798 return STK_MemberPointer;
799 } else if (isa<EnumType>(T)) {
800 assert(cast<EnumType>(T)->getDecl()->isComplete());
802 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
803 if (CT->getElementType()->isRealFloatingType())
804 return STK_FloatingComplex;
805 return STK_IntegralComplex;
808 llvm_unreachable("unknown scalar type");
811 /// \brief Determines whether the type is a C++ aggregate type or C
812 /// aggregate or union type.
814 /// An aggregate type is an array or a class type (struct, union, or
815 /// class) that has no user-declared constructors, no private or
816 /// protected non-static data members, no base classes, and no virtual
817 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
818 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
819 /// includes union types.
820 bool Type::isAggregateType() const {
821 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
822 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
823 return ClassDecl->isAggregate();
828 return isa<ArrayType>(CanonicalType);
831 /// isConstantSizeType - Return true if this is not a variable sized type,
832 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
833 /// incomplete types or dependent types.
834 bool Type::isConstantSizeType() const {
835 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
836 assert(!isDependentType() && "This doesn't make sense for dependent types");
837 // The VAT must have a size, as it is known to be complete.
838 return !isa<VariableArrayType>(CanonicalType);
841 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
842 /// - a type that can describe objects, but which lacks information needed to
843 /// determine its size.
844 bool Type::isIncompleteType(NamedDecl **Def) const {
848 switch (CanonicalType->getTypeClass()) {
849 default: return false;
851 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
855 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
859 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
860 if (EnumD->isFixed())
863 return !EnumD->isCompleteDefinition();
866 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
867 // forward declaration, but not a full definition (C99 6.2.5p22).
868 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
871 return !Rec->isCompleteDefinition();
874 // An array is incomplete if its element type is incomplete
875 // (C++ [dcl.array]p1).
876 // We don't handle variable arrays (they're not allowed in C++) or
877 // dependent-sized arrays (dependent types are never treated as incomplete).
878 return cast<ArrayType>(CanonicalType)->getElementType()
879 ->isIncompleteType(Def);
880 case IncompleteArray:
881 // An array of unknown size is an incomplete type (C99 6.2.5p22).
884 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
885 ->isIncompleteType(Def);
886 case ObjCInterface: {
887 // ObjC interfaces are incomplete if they are @class, not @interface.
888 ObjCInterfaceDecl *Interface
889 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
892 return !Interface->hasDefinition();
897 bool QualType::isPODType(ASTContext &Context) const {
898 // The compiler shouldn't query this for incomplete types, but the user might.
899 // We return false for that case. Except for incomplete arrays of PODs, which
900 // are PODs according to the standard.
904 if ((*this)->isIncompleteArrayType())
905 return Context.getBaseElementType(*this).isPODType(Context);
907 if ((*this)->isIncompleteType())
910 if (Context.getLangOpts().ObjCAutoRefCount) {
911 switch (getObjCLifetime()) {
912 case Qualifiers::OCL_ExplicitNone:
915 case Qualifiers::OCL_Strong:
916 case Qualifiers::OCL_Weak:
917 case Qualifiers::OCL_Autoreleasing:
920 case Qualifiers::OCL_None:
925 QualType CanonicalType = getTypePtr()->CanonicalType;
926 switch (CanonicalType->getTypeClass()) {
927 // Everything not explicitly mentioned is not POD.
928 default: return false;
929 case Type::VariableArray:
930 case Type::ConstantArray:
931 // IncompleteArray is handled above.
932 return Context.getBaseElementType(*this).isPODType(Context);
934 case Type::ObjCObjectPointer:
935 case Type::BlockPointer:
939 case Type::MemberPointer:
941 case Type::ExtVector:
948 if (CXXRecordDecl *ClassDecl
949 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
950 return ClassDecl->isPOD();
952 // C struct/union is POD.
957 bool QualType::isTrivialType(ASTContext &Context) const {
958 // The compiler shouldn't query this for incomplete types, but the user might.
959 // We return false for that case. Except for incomplete arrays of PODs, which
960 // are PODs according to the standard.
964 if ((*this)->isArrayType())
965 return Context.getBaseElementType(*this).isTrivialType(Context);
967 // Return false for incomplete types after skipping any incomplete array
968 // types which are expressly allowed by the standard and thus our API.
969 if ((*this)->isIncompleteType())
972 if (Context.getLangOpts().ObjCAutoRefCount) {
973 switch (getObjCLifetime()) {
974 case Qualifiers::OCL_ExplicitNone:
977 case Qualifiers::OCL_Strong:
978 case Qualifiers::OCL_Weak:
979 case Qualifiers::OCL_Autoreleasing:
982 case Qualifiers::OCL_None:
983 if ((*this)->isObjCLifetimeType())
989 QualType CanonicalType = getTypePtr()->CanonicalType;
990 if (CanonicalType->isDependentType())
993 // C++0x [basic.types]p9:
994 // Scalar types, trivial class types, arrays of such types, and
995 // cv-qualified versions of these types are collectively called trivial
998 // As an extension, Clang treats vector types as Scalar types.
999 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1001 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1002 if (const CXXRecordDecl *ClassDecl =
1003 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1005 // A trivial class is a class that has a trivial default constructor
1006 if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
1007 // and is trivially copyable.
1008 if (!ClassDecl->isTriviallyCopyable()) return false;
1014 // No other types can match.
1018 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1019 if ((*this)->isArrayType())
1020 return Context.getBaseElementType(*this).isTrivialType(Context);
1022 if (Context.getLangOpts().ObjCAutoRefCount) {
1023 switch (getObjCLifetime()) {
1024 case Qualifiers::OCL_ExplicitNone:
1027 case Qualifiers::OCL_Strong:
1028 case Qualifiers::OCL_Weak:
1029 case Qualifiers::OCL_Autoreleasing:
1032 case Qualifiers::OCL_None:
1033 if ((*this)->isObjCLifetimeType())
1039 // C++0x [basic.types]p9
1040 // Scalar types, trivially copyable class types, arrays of such types, and
1041 // cv-qualified versions of these types are collectively called trivial
1044 QualType CanonicalType = getCanonicalType();
1045 if (CanonicalType->isDependentType())
1048 // Return false for incomplete types after skipping any incomplete array types
1049 // which are expressly allowed by the standard and thus our API.
1050 if (CanonicalType->isIncompleteType())
1053 // As an extension, Clang treats vector types as Scalar types.
1054 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1057 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1058 if (const CXXRecordDecl *ClassDecl =
1059 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1060 if (!ClassDecl->isTriviallyCopyable()) return false;
1066 // No other types can match.
1072 bool Type::isLiteralType() const {
1073 if (isDependentType())
1076 // C++0x [basic.types]p10:
1077 // A type is a literal type if it is:
1079 // -- an array of literal type.
1080 // Extension: variable arrays cannot be literal types, since they're
1082 if (isVariableArrayType())
1084 const Type *BaseTy = getBaseElementTypeUnsafe();
1085 assert(BaseTy && "NULL element type");
1087 // Return false for incomplete types after skipping any incomplete array
1088 // types; those are expressly allowed by the standard and thus our API.
1089 if (BaseTy->isIncompleteType())
1092 // C++0x [basic.types]p10:
1093 // A type is a literal type if it is:
1094 // -- a scalar type; or
1095 // As an extension, Clang treats vector types and complex types as
1097 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1098 BaseTy->isAnyComplexType())
1100 // -- a reference type; or
1101 if (BaseTy->isReferenceType())
1103 // -- a class type that has all of the following properties:
1104 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1105 // -- a trivial destructor,
1106 // -- every constructor call and full-expression in the
1107 // brace-or-equal-initializers for non-static data members (if any)
1108 // is a constant expression,
1109 // -- it is an aggregate type or has at least one constexpr
1110 // constructor or constructor template that is not a copy or move
1112 // -- all non-static data members and base classes of literal types
1114 // We resolve DR1361 by ignoring the second bullet.
1115 if (const CXXRecordDecl *ClassDecl =
1116 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1117 return ClassDecl->isLiteral();
1125 bool Type::isStandardLayoutType() const {
1126 if (isDependentType())
1129 // C++0x [basic.types]p9:
1130 // Scalar types, standard-layout class types, arrays of such types, and
1131 // cv-qualified versions of these types are collectively called
1132 // standard-layout types.
1133 const Type *BaseTy = getBaseElementTypeUnsafe();
1134 assert(BaseTy && "NULL element type");
1136 // Return false for incomplete types after skipping any incomplete array
1137 // types which are expressly allowed by the standard and thus our API.
1138 if (BaseTy->isIncompleteType())
1141 // As an extension, Clang treats vector types as Scalar types.
1142 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1143 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1144 if (const CXXRecordDecl *ClassDecl =
1145 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1146 if (!ClassDecl->isStandardLayout())
1149 // Default to 'true' for non-C++ class types.
1150 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1151 // all the requirements of standard layout classes.
1155 // No other types can match.
1159 // This is effectively the intersection of isTrivialType and
1160 // isStandardLayoutType. We implement it directly to avoid redundant
1161 // conversions from a type to a CXXRecordDecl.
1162 bool QualType::isCXX11PODType(ASTContext &Context) const {
1163 const Type *ty = getTypePtr();
1164 if (ty->isDependentType())
1167 if (Context.getLangOpts().ObjCAutoRefCount) {
1168 switch (getObjCLifetime()) {
1169 case Qualifiers::OCL_ExplicitNone:
1172 case Qualifiers::OCL_Strong:
1173 case Qualifiers::OCL_Weak:
1174 case Qualifiers::OCL_Autoreleasing:
1177 case Qualifiers::OCL_None:
1178 if (ty->isObjCLifetimeType())
1184 // C++11 [basic.types]p9:
1185 // Scalar types, POD classes, arrays of such types, and cv-qualified
1186 // versions of these types are collectively called trivial types.
1187 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1188 assert(BaseTy && "NULL element type");
1190 // Return false for incomplete types after skipping any incomplete array
1191 // types which are expressly allowed by the standard and thus our API.
1192 if (BaseTy->isIncompleteType())
1195 // As an extension, Clang treats vector types as Scalar types.
1196 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1197 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1198 if (const CXXRecordDecl *ClassDecl =
1199 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1200 // C++11 [class]p10:
1201 // A POD struct is a non-union class that is both a trivial class [...]
1202 if (!ClassDecl->isTrivial()) return false;
1204 // C++11 [class]p10:
1205 // A POD struct is a non-union class that is both a trivial class and
1206 // a standard-layout class [...]
1207 if (!ClassDecl->isStandardLayout()) return false;
1209 // C++11 [class]p10:
1210 // A POD struct is a non-union class that is both a trivial class and
1211 // a standard-layout class, and has no non-static data members of type
1212 // non-POD struct, non-POD union (or array of such types). [...]
1214 // We don't directly query the recursive aspect as the requiremets for
1215 // both standard-layout classes and trivial classes apply recursively
1222 // No other types can match.
1226 bool Type::isPromotableIntegerType() const {
1227 if (const BuiltinType *BT = getAs<BuiltinType>())
1228 switch (BT->getKind()) {
1229 case BuiltinType::Bool:
1230 case BuiltinType::Char_S:
1231 case BuiltinType::Char_U:
1232 case BuiltinType::SChar:
1233 case BuiltinType::UChar:
1234 case BuiltinType::Short:
1235 case BuiltinType::UShort:
1236 case BuiltinType::WChar_S:
1237 case BuiltinType::WChar_U:
1238 case BuiltinType::Char16:
1239 case BuiltinType::Char32:
1245 // Enumerated types are promotable to their compatible integer types
1246 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1247 if (const EnumType *ET = getAs<EnumType>()){
1248 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1249 || ET->getDecl()->isScoped())
1258 bool Type::isSpecifierType() const {
1259 // Note that this intentionally does not use the canonical type.
1260 switch (getTypeClass()) {
1268 case TemplateTypeParm:
1269 case SubstTemplateTypeParm:
1270 case TemplateSpecialization:
1273 case DependentTemplateSpecialization:
1276 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1283 ElaboratedTypeKeyword
1284 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1286 default: return ETK_None;
1287 case TST_typename: return ETK_Typename;
1288 case TST_class: return ETK_Class;
1289 case TST_struct: return ETK_Struct;
1290 case TST_union: return ETK_Union;
1291 case TST_enum: return ETK_Enum;
1296 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1298 case TST_class: return TTK_Class;
1299 case TST_struct: return TTK_Struct;
1300 case TST_union: return TTK_Union;
1301 case TST_enum: return TTK_Enum;
1304 llvm_unreachable("Type specifier is not a tag type kind.");
1307 ElaboratedTypeKeyword
1308 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1310 case TTK_Class: return ETK_Class;
1311 case TTK_Struct: return ETK_Struct;
1312 case TTK_Union: return ETK_Union;
1313 case TTK_Enum: return ETK_Enum;
1315 llvm_unreachable("Unknown tag type kind.");
1319 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1321 case ETK_Class: return TTK_Class;
1322 case ETK_Struct: return TTK_Struct;
1323 case ETK_Union: return TTK_Union;
1324 case ETK_Enum: return TTK_Enum;
1325 case ETK_None: // Fall through.
1327 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1329 llvm_unreachable("Unknown elaborated type keyword.");
1333 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1344 llvm_unreachable("Unknown elaborated type keyword.");
1348 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1350 case ETK_None: return "";
1351 case ETK_Typename: return "typename";
1352 case ETK_Class: return "class";
1353 case ETK_Struct: return "struct";
1354 case ETK_Union: return "union";
1355 case ETK_Enum: return "enum";
1358 llvm_unreachable("Unknown elaborated type keyword.");
1361 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1362 ElaboratedTypeKeyword Keyword,
1363 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1364 unsigned NumArgs, const TemplateArgument *Args,
1366 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1367 /*VariablyModified=*/false,
1368 NNS && NNS->containsUnexpandedParameterPack()),
1369 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1370 assert((!NNS || NNS->isDependent()) &&
1371 "DependentTemplateSpecializatonType requires dependent qualifier");
1372 for (unsigned I = 0; I != NumArgs; ++I) {
1373 if (Args[I].containsUnexpandedParameterPack())
1374 setContainsUnexpandedParameterPack();
1376 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1381 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1382 const ASTContext &Context,
1383 ElaboratedTypeKeyword Keyword,
1384 NestedNameSpecifier *Qualifier,
1385 const IdentifierInfo *Name,
1387 const TemplateArgument *Args) {
1388 ID.AddInteger(Keyword);
1389 ID.AddPointer(Qualifier);
1390 ID.AddPointer(Name);
1391 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1392 Args[Idx].Profile(ID, Context);
1395 bool Type::isElaboratedTypeSpecifier() const {
1396 ElaboratedTypeKeyword Keyword;
1397 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1398 Keyword = Elab->getKeyword();
1399 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1400 Keyword = DepName->getKeyword();
1401 else if (const DependentTemplateSpecializationType *DepTST =
1402 dyn_cast<DependentTemplateSpecializationType>(this))
1403 Keyword = DepTST->getKeyword();
1407 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1410 const char *Type::getTypeClassName() const {
1411 switch (TypeBits.TC) {
1412 #define ABSTRACT_TYPE(Derived, Base)
1413 #define TYPE(Derived, Base) case Derived: return #Derived;
1414 #include "clang/AST/TypeNodes.def"
1417 llvm_unreachable("Invalid type class.");
1420 const char *BuiltinType::getName(const PrintingPolicy &Policy) const {
1421 switch (getKind()) {
1422 case Void: return "void";
1423 case Bool: return Policy.Bool ? "bool" : "_Bool";
1424 case Char_S: return "char";
1425 case Char_U: return "char";
1426 case SChar: return "signed char";
1427 case Short: return "short";
1428 case Int: return "int";
1429 case Long: return "long";
1430 case LongLong: return "long long";
1431 case Int128: return "__int128";
1432 case UChar: return "unsigned char";
1433 case UShort: return "unsigned short";
1434 case UInt: return "unsigned int";
1435 case ULong: return "unsigned long";
1436 case ULongLong: return "unsigned long long";
1437 case UInt128: return "unsigned __int128";
1438 case Half: return "half";
1439 case Float: return "float";
1440 case Double: return "double";
1441 case LongDouble: return "long double";
1443 case WChar_U: return "wchar_t";
1444 case Char16: return "char16_t";
1445 case Char32: return "char32_t";
1446 case NullPtr: return "nullptr_t";
1447 case Overload: return "<overloaded function type>";
1448 case BoundMember: return "<bound member function type>";
1449 case PseudoObject: return "<pseudo-object type>";
1450 case Dependent: return "<dependent type>";
1451 case UnknownAny: return "<unknown type>";
1452 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1453 case ObjCId: return "id";
1454 case ObjCClass: return "Class";
1455 case ObjCSel: return "SEL";
1458 llvm_unreachable("Invalid builtin type.");
1461 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1462 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1463 return RefType->getPointeeType();
1465 // C++0x [basic.lval]:
1466 // Class prvalues can have cv-qualified types; non-class prvalues always
1467 // have cv-unqualified types.
1469 // See also C99 6.3.2.1p2.
1470 if (!Context.getLangOpts().CPlusPlus ||
1471 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1472 return getUnqualifiedType();
1477 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1480 llvm_unreachable("no name for default cc");
1482 case CC_C: return "cdecl";
1483 case CC_X86StdCall: return "stdcall";
1484 case CC_X86FastCall: return "fastcall";
1485 case CC_X86ThisCall: return "thiscall";
1486 case CC_X86Pascal: return "pascal";
1487 case CC_AAPCS: return "aapcs";
1488 case CC_AAPCS_VFP: return "aapcs-vfp";
1491 llvm_unreachable("Invalid calling convention.");
1494 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1495 unsigned numArgs, QualType canonical,
1496 const ExtProtoInfo &epi)
1497 : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
1499 result->isDependentType(),
1500 result->isInstantiationDependentType(),
1501 result->isVariablyModifiedType(),
1502 result->containsUnexpandedParameterPack(),
1504 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1505 ExceptionSpecType(epi.ExceptionSpecType),
1506 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1507 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
1509 // Fill in the trailing argument array.
1510 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1511 for (unsigned i = 0; i != numArgs; ++i) {
1512 if (args[i]->isDependentType())
1514 else if (args[i]->isInstantiationDependentType())
1515 setInstantiationDependent();
1517 if (args[i]->containsUnexpandedParameterPack())
1518 setContainsUnexpandedParameterPack();
1520 argSlot[i] = args[i];
1523 if (getExceptionSpecType() == EST_Dynamic) {
1524 // Fill in the exception array.
1525 QualType *exnSlot = argSlot + numArgs;
1526 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1527 if (epi.Exceptions[i]->isDependentType())
1529 else if (epi.Exceptions[i]->isInstantiationDependentType())
1530 setInstantiationDependent();
1532 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1533 setContainsUnexpandedParameterPack();
1535 exnSlot[i] = epi.Exceptions[i];
1537 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1538 // Store the noexcept expression and context.
1539 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1540 *noexSlot = epi.NoexceptExpr;
1542 if (epi.NoexceptExpr) {
1543 if (epi.NoexceptExpr->isValueDependent()
1544 || epi.NoexceptExpr->isTypeDependent())
1546 else if (epi.NoexceptExpr->isInstantiationDependent())
1547 setInstantiationDependent();
1549 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1550 // Store the function decl from which we will resolve our
1551 // exception specification.
1552 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1553 slot[0] = epi.ExceptionSpecDecl;
1554 slot[1] = epi.ExceptionSpecTemplate;
1555 // This exception specification doesn't make the type dependent, because
1556 // it's not instantiated as part of instantiating the type.
1559 if (epi.ConsumedArguments) {
1560 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1561 for (unsigned i = 0; i != numArgs; ++i)
1562 consumedArgs[i] = epi.ConsumedArguments[i];
1566 FunctionProtoType::NoexceptResult
1567 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1568 ExceptionSpecificationType est = getExceptionSpecType();
1569 if (est == EST_BasicNoexcept)
1572 if (est != EST_ComputedNoexcept)
1573 return NR_NoNoexcept;
1575 Expr *noexceptExpr = getNoexceptExpr();
1577 return NR_BadNoexcept;
1578 if (noexceptExpr->isValueDependent())
1579 return NR_Dependent;
1582 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1583 /*evaluated*/false);
1585 assert(isICE && "AST should not contain bad noexcept expressions.");
1587 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1590 bool FunctionProtoType::isTemplateVariadic() const {
1591 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1592 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1598 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1599 const QualType *ArgTys, unsigned NumArgs,
1600 const ExtProtoInfo &epi,
1601 const ASTContext &Context) {
1603 // We have to be careful not to get ambiguous profile encodings.
1604 // Note that valid type pointers are never ambiguous with anything else.
1606 // The encoding grammar begins:
1607 // type type* bool int bool
1608 // If that final bool is true, then there is a section for the EH spec:
1610 // This is followed by an optional "consumed argument" section of the
1611 // same length as the first type sequence:
1613 // Finally, we have the ext info and trailing return type flag:
1616 // There is no ambiguity between the consumed arguments and an empty EH
1617 // spec because of the leading 'bool' which unambiguously indicates
1618 // whether the following bool is the EH spec or part of the arguments.
1620 ID.AddPointer(Result.getAsOpaquePtr());
1621 for (unsigned i = 0; i != NumArgs; ++i)
1622 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1623 // This method is relatively performance sensitive, so as a performance
1624 // shortcut, use one AddInteger call instead of four for the next four
1626 assert(!(unsigned(epi.Variadic) & ~1) &&
1627 !(unsigned(epi.TypeQuals) & ~255) &&
1628 !(unsigned(epi.RefQualifier) & ~3) &&
1629 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1630 "Values larger than expected.");
1631 ID.AddInteger(unsigned(epi.Variadic) +
1632 (epi.TypeQuals << 1) +
1633 (epi.RefQualifier << 9) +
1634 (epi.ExceptionSpecType << 11));
1635 if (epi.ExceptionSpecType == EST_Dynamic) {
1636 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1637 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1638 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1639 epi.NoexceptExpr->Profile(ID, Context, false);
1640 } else if (epi.ExceptionSpecType == EST_Uninstantiated) {
1641 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1643 if (epi.ConsumedArguments) {
1644 for (unsigned i = 0; i != NumArgs; ++i)
1645 ID.AddBoolean(epi.ConsumedArguments[i]);
1647 epi.ExtInfo.Profile(ID);
1648 ID.AddBoolean(epi.HasTrailingReturn);
1651 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1652 const ASTContext &Ctx) {
1653 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1657 QualType TypedefType::desugar() const {
1658 return getDecl()->getUnderlyingType();
1661 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1662 : Type(TypeOfExpr, can, E->isTypeDependent(),
1663 E->isInstantiationDependent(),
1664 E->getType()->isVariablyModifiedType(),
1665 E->containsUnexpandedParameterPack()),
1669 bool TypeOfExprType::isSugared() const {
1670 return !TOExpr->isTypeDependent();
1673 QualType TypeOfExprType::desugar() const {
1675 return getUnderlyingExpr()->getType();
1677 return QualType(this, 0);
1680 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1681 const ASTContext &Context, Expr *E) {
1682 E->Profile(ID, Context, true);
1685 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1686 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1687 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1688 // type-dependent even if its expression is only instantiation-dependent.
1689 : Type(Decltype, can, E->isInstantiationDependent(),
1690 E->isInstantiationDependent(),
1691 E->getType()->isVariablyModifiedType(),
1692 E->containsUnexpandedParameterPack()),
1694 UnderlyingType(underlyingType) {
1697 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1699 QualType DecltypeType::desugar() const {
1701 return getUnderlyingType();
1703 return QualType(this, 0);
1706 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1707 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1709 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1710 const ASTContext &Context, Expr *E) {
1711 E->Profile(ID, Context, true);
1714 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1715 : Type(TC, can, D->isDependentType(),
1716 /*InstantiationDependent=*/D->isDependentType(),
1717 /*VariablyModified=*/false,
1718 /*ContainsUnexpandedParameterPack=*/false),
1719 decl(const_cast<TagDecl*>(D)) {}
1721 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1722 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1723 E = decl->redecls_end();
1725 if (I->isCompleteDefinition() || I->isBeingDefined())
1728 // If there's no definition (not even in progress), return what we have.
1732 UnaryTransformType::UnaryTransformType(QualType BaseType,
1733 QualType UnderlyingType,
1735 QualType CanonicalType)
1736 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1737 UnderlyingType->isInstantiationDependentType(),
1738 UnderlyingType->isVariablyModifiedType(),
1739 BaseType->containsUnexpandedParameterPack())
1740 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1743 TagDecl *TagType::getDecl() const {
1744 return getInterestingTagDecl(decl);
1747 bool TagType::isBeingDefined() const {
1748 return getDecl()->isBeingDefined();
1751 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1752 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1755 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1756 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1759 SubstTemplateTypeParmPackType::
1760 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1762 const TemplateArgument &ArgPack)
1763 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1765 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1769 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1770 return TemplateArgument(Arguments, NumArguments);
1773 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1774 Profile(ID, getReplacedParameter(), getArgumentPack());
1777 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1778 const TemplateTypeParmType *Replaced,
1779 const TemplateArgument &ArgPack) {
1780 ID.AddPointer(Replaced);
1781 ID.AddInteger(ArgPack.pack_size());
1782 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1783 PEnd = ArgPack.pack_end();
1785 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1788 bool TemplateSpecializationType::
1789 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1790 bool &InstantiationDependent) {
1791 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1792 InstantiationDependent);
1795 bool TemplateSpecializationType::
1796 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1797 bool &InstantiationDependent) {
1798 for (unsigned i = 0; i != N; ++i) {
1799 if (Args[i].getArgument().isDependent()) {
1800 InstantiationDependent = true;
1804 if (Args[i].getArgument().isInstantiationDependent())
1805 InstantiationDependent = true;
1810 bool TemplateSpecializationType::
1811 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1812 bool &InstantiationDependent) {
1813 for (unsigned i = 0; i != N; ++i) {
1814 if (Args[i].isDependent()) {
1815 InstantiationDependent = true;
1819 if (Args[i].isInstantiationDependent())
1820 InstantiationDependent = true;
1825 TemplateSpecializationType::
1826 TemplateSpecializationType(TemplateName T,
1827 const TemplateArgument *Args, unsigned NumArgs,
1828 QualType Canon, QualType AliasedType)
1829 : Type(TemplateSpecialization,
1830 Canon.isNull()? QualType(this, 0) : Canon,
1831 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1832 Canon.isNull()? T.isDependent()
1833 : Canon->isInstantiationDependentType(),
1835 Canon.isNull()? T.containsUnexpandedParameterPack()
1836 : Canon->containsUnexpandedParameterPack()),
1837 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1838 assert(!T.getAsDependentTemplateName() &&
1839 "Use DependentTemplateSpecializationType for dependent template-name");
1840 assert((T.getKind() == TemplateName::Template ||
1841 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1842 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1843 "Unexpected template name for TemplateSpecializationType");
1844 bool InstantiationDependent;
1845 (void)InstantiationDependent;
1846 assert((!Canon.isNull() ||
1848 anyDependentTemplateArguments(Args, NumArgs,
1849 InstantiationDependent)) &&
1850 "No canonical type for non-dependent class template specialization");
1852 TemplateArgument *TemplateArgs
1853 = reinterpret_cast<TemplateArgument *>(this + 1);
1854 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1855 // Update dependent and variably-modified bits.
1856 // If the canonical type exists and is non-dependent, the template
1857 // specialization type can be non-dependent even if one of the type
1858 // arguments is. Given:
1859 // template<typename T> using U = int;
1860 // U<T> is always non-dependent, irrespective of the type T.
1861 if (Canon.isNull() && Args[Arg].isDependent())
1863 else if (Args[Arg].isInstantiationDependent())
1864 setInstantiationDependent();
1866 if (Args[Arg].getKind() == TemplateArgument::Type &&
1867 Args[Arg].getAsType()->isVariablyModifiedType())
1868 setVariablyModified();
1869 if (Canon.isNull() && Args[Arg].containsUnexpandedParameterPack())
1870 setContainsUnexpandedParameterPack();
1872 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1875 // Store the aliased type if this is a type alias template specialization.
1877 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1878 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1883 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1885 const TemplateArgument *Args,
1887 const ASTContext &Context) {
1889 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1890 Args[Idx].Profile(ID, Context);
1894 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1895 if (!hasNonFastQualifiers())
1896 return QT.withFastQualifiers(getFastQualifiers());
1898 return Context.getQualifiedType(QT, *this);
1902 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1903 if (!hasNonFastQualifiers())
1904 return QualType(T, getFastQualifiers());
1906 return Context.getQualifiedType(T, *this);
1909 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1911 ObjCProtocolDecl * const *Protocols,
1912 unsigned NumProtocols) {
1913 ID.AddPointer(BaseType.getAsOpaquePtr());
1914 for (unsigned i = 0; i != NumProtocols; i++)
1915 ID.AddPointer(Protocols[i]);
1918 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1919 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1924 /// \brief The cached properties of a type.
1925 class CachedProperties {
1926 NamedDecl::LinkageInfo LV;
1930 CachedProperties(NamedDecl::LinkageInfo LV, bool local)
1931 : LV(LV), local(local) {}
1933 Linkage getLinkage() const { return LV.linkage(); }
1934 Visibility getVisibility() const { return LV.visibility(); }
1935 bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
1936 bool hasLocalOrUnnamedType() const { return local; }
1938 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1939 NamedDecl::LinkageInfo MergedLV = L.LV;
1940 MergedLV.merge(R.LV);
1941 return CachedProperties(MergedLV,
1942 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1947 static CachedProperties computeCachedProperties(const Type *T);
1950 /// The type-property cache. This is templated so as to be
1951 /// instantiated at an internal type to prevent unnecessary symbol
1953 template <class Private> class TypePropertyCache {
1955 static CachedProperties get(QualType T) {
1956 return get(T.getTypePtr());
1959 static CachedProperties get(const Type *T) {
1961 NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
1962 T->TypeBits.getVisibility(),
1963 T->TypeBits.isVisibilityExplicit());
1964 return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
1967 static void ensure(const Type *T) {
1968 // If the cache is valid, we're okay.
1969 if (T->TypeBits.isCacheValid()) return;
1971 // If this type is non-canonical, ask its canonical type for the
1972 // relevant information.
1973 if (!T->isCanonicalUnqualified()) {
1974 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1976 T->TypeBits.CacheValidAndVisibility =
1977 CT->TypeBits.CacheValidAndVisibility;
1978 T->TypeBits.CachedExplicitVisibility =
1979 CT->TypeBits.CachedExplicitVisibility;
1980 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1981 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1985 // Compute the cached properties and then set the cache.
1986 CachedProperties Result = computeCachedProperties(T);
1987 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1988 T->TypeBits.CachedExplicitVisibility = Result.isVisibilityExplicit();
1989 assert(T->TypeBits.isCacheValid() &&
1990 T->TypeBits.getVisibility() == Result.getVisibility());
1991 T->TypeBits.CachedLinkage = Result.getLinkage();
1992 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1997 // Instantiate the friend template at a private class. In a
1998 // reasonable implementation, these symbols will be internal.
1999 // It is terrible that this is the best way to accomplish this.
2000 namespace { class Private {}; }
2001 typedef TypePropertyCache<Private> Cache;
2003 static CachedProperties computeCachedProperties(const Type *T) {
2004 switch (T->getTypeClass()) {
2005 #define TYPE(Class,Base)
2006 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2007 #include "clang/AST/TypeNodes.def"
2008 llvm_unreachable("didn't expect a non-canonical type here");
2010 #define TYPE(Class,Base)
2011 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2012 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2013 #include "clang/AST/TypeNodes.def"
2014 // Treat instantiation-dependent types as external.
2015 assert(T->isInstantiationDependentType());
2016 return CachedProperties(NamedDecl::LinkageInfo(), false);
2019 // C++ [basic.link]p8:
2020 // A type is said to have linkage if and only if:
2021 // - it is a fundamental type (3.9.1); or
2022 return CachedProperties(NamedDecl::LinkageInfo(), false);
2026 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2028 // C++ [basic.link]p8:
2029 // - it is a class or enumeration type that is named (or has a name
2030 // for linkage purposes (7.1.3)) and the name has linkage; or
2031 // - it is a specialization of a class template (14); or
2032 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2033 bool IsLocalOrUnnamed =
2034 Tag->getDeclContext()->isFunctionOrMethod() ||
2035 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2036 return CachedProperties(LV, IsLocalOrUnnamed);
2039 // C++ [basic.link]p8:
2040 // - it is a compound type (3.9.2) other than a class or enumeration,
2041 // compounded exclusively from types that have linkage; or
2043 return Cache::get(cast<ComplexType>(T)->getElementType());
2045 return Cache::get(cast<PointerType>(T)->getPointeeType());
2046 case Type::BlockPointer:
2047 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2048 case Type::LValueReference:
2049 case Type::RValueReference:
2050 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2051 case Type::MemberPointer: {
2052 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2053 return merge(Cache::get(MPT->getClass()),
2054 Cache::get(MPT->getPointeeType()));
2056 case Type::ConstantArray:
2057 case Type::IncompleteArray:
2058 case Type::VariableArray:
2059 return Cache::get(cast<ArrayType>(T)->getElementType());
2061 case Type::ExtVector:
2062 return Cache::get(cast<VectorType>(T)->getElementType());
2063 case Type::FunctionNoProto:
2064 return Cache::get(cast<FunctionType>(T)->getResultType());
2065 case Type::FunctionProto: {
2066 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2067 CachedProperties result = Cache::get(FPT->getResultType());
2068 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2069 ae = FPT->arg_type_end(); ai != ae; ++ai)
2070 result = merge(result, Cache::get(*ai));
2073 case Type::ObjCInterface: {
2074 NamedDecl::LinkageInfo LV =
2075 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2076 return CachedProperties(LV, false);
2078 case Type::ObjCObject:
2079 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2080 case Type::ObjCObjectPointer:
2081 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2083 return Cache::get(cast<AtomicType>(T)->getValueType());
2086 llvm_unreachable("unhandled type class");
2089 /// \brief Determine the linkage of this type.
2090 Linkage Type::getLinkage() const {
2091 Cache::ensure(this);
2092 return TypeBits.getLinkage();
2095 /// \brief Determine the linkage of this type.
2096 Visibility Type::getVisibility() const {
2097 Cache::ensure(this);
2098 return TypeBits.getVisibility();
2101 bool Type::isVisibilityExplicit() const {
2102 Cache::ensure(this);
2103 return TypeBits.isVisibilityExplicit();
2106 bool Type::hasUnnamedOrLocalType() const {
2107 Cache::ensure(this);
2108 return TypeBits.hasLocalOrUnnamedType();
2111 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2112 Cache::ensure(this);
2113 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2116 void Type::ClearLinkageCache() {
2117 TypeBits.CacheValidAndVisibility = 0;
2118 if (QualType(this, 0) != CanonicalType)
2119 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2122 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2123 if (isObjCARCImplicitlyUnretainedType())
2124 return Qualifiers::OCL_ExplicitNone;
2125 return Qualifiers::OCL_Strong;
2128 bool Type::isObjCARCImplicitlyUnretainedType() const {
2129 assert(isObjCLifetimeType() &&
2130 "cannot query implicit lifetime for non-inferrable type");
2132 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2134 // Walk down to the base type. We don't care about qualifiers for this.
2135 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2136 canon = array->getElementType().getTypePtr();
2138 if (const ObjCObjectPointerType *opt
2139 = dyn_cast<ObjCObjectPointerType>(canon)) {
2140 // Class and Class<Protocol> don't require retension.
2141 if (opt->getObjectType()->isObjCClass())
2148 bool Type::isObjCNSObjectType() const {
2149 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2150 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2153 bool Type::isObjCRetainableType() const {
2154 return isObjCObjectPointerType() ||
2155 isBlockPointerType() ||
2156 isObjCNSObjectType();
2158 bool Type::isObjCIndirectLifetimeType() const {
2159 if (isObjCLifetimeType())
2161 if (const PointerType *OPT = getAs<PointerType>())
2162 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2163 if (const ReferenceType *Ref = getAs<ReferenceType>())
2164 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2165 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2166 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2170 /// Returns true if objects of this type have lifetime semantics under
2172 bool Type::isObjCLifetimeType() const {
2173 const Type *type = this;
2174 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2175 type = array->getElementType().getTypePtr();
2176 return type->isObjCRetainableType();
2179 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2180 /// which is either an Objective-C object pointer type or an
2181 bool Type::isObjCARCBridgableType() const {
2182 return isObjCObjectPointerType() || isBlockPointerType();
2185 /// \brief Determine whether the given type T is a "bridgeable" C type.
2186 bool Type::isCARCBridgableType() const {
2187 const PointerType *Pointer = getAs<PointerType>();
2191 QualType Pointee = Pointer->getPointeeType();
2192 return Pointee->isVoidType() || Pointee->isRecordType();
2195 bool Type::hasSizedVLAType() const {
2196 if (!isVariablyModifiedType()) return false;
2198 if (const PointerType *ptr = getAs<PointerType>())
2199 return ptr->getPointeeType()->hasSizedVLAType();
2200 if (const ReferenceType *ref = getAs<ReferenceType>())
2201 return ref->getPointeeType()->hasSizedVLAType();
2202 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2203 if (isa<VariableArrayType>(arr) &&
2204 cast<VariableArrayType>(arr)->getSizeExpr())
2207 return arr->getElementType()->hasSizedVLAType();
2213 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2214 switch (type.getObjCLifetime()) {
2215 case Qualifiers::OCL_None:
2216 case Qualifiers::OCL_ExplicitNone:
2217 case Qualifiers::OCL_Autoreleasing:
2220 case Qualifiers::OCL_Strong:
2221 return DK_objc_strong_lifetime;
2222 case Qualifiers::OCL_Weak:
2223 return DK_objc_weak_lifetime;
2226 /// Currently, the only destruction kind we recognize is C++ objects
2227 /// with non-trivial destructors.
2228 const CXXRecordDecl *record =
2229 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2230 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2231 return DK_cxx_destructor;
2236 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
2237 switch (getObjCLifetime()) {
2238 case Qualifiers::OCL_None:
2241 case Qualifiers::OCL_ExplicitNone:
2244 case Qualifiers::OCL_Autoreleasing:
2245 case Qualifiers::OCL_Strong:
2246 case Qualifiers::OCL_Weak:
2247 return !Context.getLangOpts().ObjCAutoRefCount;
2250 if (const CXXRecordDecl *Record
2251 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2252 return Copying ? Record->hasTrivialCopyAssignment() :
2253 Record->hasTrivialMoveAssignment();