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 /// \brief This will check for a TypedefType by removing any existing sugar
292 /// until it reaches a TypedefType or a non-sugared type.
293 template <> const TypedefType *Type::getAs() const {
294 const Type *Cur = this;
297 if (const TypedefType *TDT = dyn_cast<TypedefType>(Cur))
299 switch (Cur->getTypeClass()) {
300 #define ABSTRACT_TYPE(Class, Parent)
301 #define TYPE(Class, Parent) \
303 const Class##Type *Ty = cast<Class##Type>(Cur); \
304 if (!Ty->isSugared()) return 0; \
305 Cur = Ty->desugar().getTypePtr(); \
308 #include "clang/AST/TypeNodes.def"
313 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
314 /// sugar off the given type. This should produce an object of the
315 /// same dynamic type as the canonical type.
316 const Type *Type::getUnqualifiedDesugaredType() const {
317 const Type *Cur = this;
320 switch (Cur->getTypeClass()) {
321 #define ABSTRACT_TYPE(Class, Parent)
322 #define TYPE(Class, Parent) \
324 const Class##Type *Ty = cast<Class##Type>(Cur); \
325 if (!Ty->isSugared()) return Cur; \
326 Cur = Ty->desugar().getTypePtr(); \
329 #include "clang/AST/TypeNodes.def"
334 bool Type::isDerivedType() const {
335 switch (CanonicalType->getTypeClass()) {
339 case IncompleteArray:
341 case FunctionNoProto:
342 case LValueReference:
343 case RValueReference:
350 bool Type::isClassType() const {
351 if (const RecordType *RT = getAs<RecordType>())
352 return RT->getDecl()->isClass();
355 bool Type::isStructureType() const {
356 if (const RecordType *RT = getAs<RecordType>())
357 return RT->getDecl()->isStruct();
360 bool Type::isStructureOrClassType() const {
361 if (const RecordType *RT = getAs<RecordType>())
362 return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
365 bool Type::isVoidPointerType() const {
366 if (const PointerType *PT = getAs<PointerType>())
367 return PT->getPointeeType()->isVoidType();
371 bool Type::isUnionType() const {
372 if (const RecordType *RT = getAs<RecordType>())
373 return RT->getDecl()->isUnion();
377 bool Type::isComplexType() const {
378 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
379 return CT->getElementType()->isFloatingType();
383 bool Type::isComplexIntegerType() const {
384 // Check for GCC complex integer extension.
385 return getAsComplexIntegerType();
388 const ComplexType *Type::getAsComplexIntegerType() const {
389 if (const ComplexType *Complex = getAs<ComplexType>())
390 if (Complex->getElementType()->isIntegerType())
395 QualType Type::getPointeeType() const {
396 if (const PointerType *PT = getAs<PointerType>())
397 return PT->getPointeeType();
398 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
399 return OPT->getPointeeType();
400 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
401 return BPT->getPointeeType();
402 if (const ReferenceType *RT = getAs<ReferenceType>())
403 return RT->getPointeeType();
407 const RecordType *Type::getAsStructureType() const {
408 // If this is directly a structure type, return it.
409 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
410 if (RT->getDecl()->isStruct())
414 // If the canonical form of this type isn't the right kind, reject it.
415 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
416 if (!RT->getDecl()->isStruct())
419 // If this is a typedef for a structure type, strip the typedef off without
420 // losing all typedef information.
421 return cast<RecordType>(getUnqualifiedDesugaredType());
426 const RecordType *Type::getAsUnionType() const {
427 // If this is directly a union type, return it.
428 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
429 if (RT->getDecl()->isUnion())
433 // If the canonical form of this type isn't the right kind, reject it.
434 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
435 if (!RT->getDecl()->isUnion())
438 // If this is a typedef for a union type, strip the typedef off without
439 // losing all typedef information.
440 return cast<RecordType>(getUnqualifiedDesugaredType());
446 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
447 ObjCProtocolDecl * const *Protocols,
448 unsigned NumProtocols)
449 : Type(ObjCObject, Canonical, false, false, false, false),
452 ObjCObjectTypeBits.NumProtocols = NumProtocols;
453 assert(getNumProtocols() == NumProtocols &&
454 "bitfield overflow in protocol count");
456 memcpy(getProtocolStorage(), Protocols,
457 NumProtocols * sizeof(ObjCProtocolDecl*));
460 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
461 // There is no sugar for ObjCObjectType's, just return the canonical
462 // type pointer if it is the right class. There is no typedef information to
463 // return and these cannot be Address-space qualified.
464 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
465 if (T->getNumProtocols() && T->getInterface())
470 bool Type::isObjCQualifiedInterfaceType() const {
471 return getAsObjCQualifiedInterfaceType() != 0;
474 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
475 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
476 // type pointer if it is the right class.
477 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
478 if (OPT->isObjCQualifiedIdType())
484 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
485 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
486 // type pointer if it is the right class.
487 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
488 if (OPT->isObjCQualifiedClassType())
494 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
495 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
496 if (OPT->getInterfaceType())
502 const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
503 if (const PointerType *PT = getAs<PointerType>())
504 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
505 return dyn_cast<CXXRecordDecl>(RT->getDecl());
509 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
510 if (const RecordType *RT = getAs<RecordType>())
511 return dyn_cast<CXXRecordDecl>(RT->getDecl());
512 else if (const InjectedClassNameType *Injected
513 = getAs<InjectedClassNameType>())
514 return Injected->getDecl();
520 class GetContainedAutoVisitor :
521 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
523 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
524 AutoType *Visit(QualType T) {
527 return Visit(T.getTypePtr());
530 // The 'auto' type itself.
531 AutoType *VisitAutoType(const AutoType *AT) {
532 return const_cast<AutoType*>(AT);
535 // Only these types can contain the desired 'auto' type.
536 AutoType *VisitPointerType(const PointerType *T) {
537 return Visit(T->getPointeeType());
539 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
540 return Visit(T->getPointeeType());
542 AutoType *VisitReferenceType(const ReferenceType *T) {
543 return Visit(T->getPointeeTypeAsWritten());
545 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
546 return Visit(T->getPointeeType());
548 AutoType *VisitArrayType(const ArrayType *T) {
549 return Visit(T->getElementType());
551 AutoType *VisitDependentSizedExtVectorType(
552 const DependentSizedExtVectorType *T) {
553 return Visit(T->getElementType());
555 AutoType *VisitVectorType(const VectorType *T) {
556 return Visit(T->getElementType());
558 AutoType *VisitFunctionType(const FunctionType *T) {
559 return Visit(T->getResultType());
561 AutoType *VisitParenType(const ParenType *T) {
562 return Visit(T->getInnerType());
564 AutoType *VisitAttributedType(const AttributedType *T) {
565 return Visit(T->getModifiedType());
570 AutoType *Type::getContainedAutoType() const {
571 return GetContainedAutoVisitor().Visit(this);
574 bool Type::hasIntegerRepresentation() const {
575 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
576 return VT->getElementType()->isIntegerType();
578 return isIntegerType();
581 /// \brief Determine whether this type is an integral type.
583 /// This routine determines whether the given type is an integral type per
584 /// C++ [basic.fundamental]p7. Although the C standard does not define the
585 /// term "integral type", it has a similar term "integer type", and in C++
586 /// the two terms are equivalent. However, C's "integer type" includes
587 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
588 /// parameter is used to determine whether we should be following the C or
589 /// C++ rules when determining whether this type is an integral/integer type.
591 /// For cases where C permits "an integer type" and C++ permits "an integral
592 /// type", use this routine.
594 /// For cases where C permits "an integer type" and C++ permits "an integral
595 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
597 /// \param Ctx The context in which this type occurs.
599 /// \returns true if the type is considered an integral type, false otherwise.
600 bool Type::isIntegralType(ASTContext &Ctx) const {
601 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
602 return BT->getKind() >= BuiltinType::Bool &&
603 BT->getKind() <= BuiltinType::Int128;
605 if (!Ctx.getLangOpts().CPlusPlus)
606 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
607 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
613 bool Type::isIntegralOrUnscopedEnumerationType() const {
614 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
615 return BT->getKind() >= BuiltinType::Bool &&
616 BT->getKind() <= BuiltinType::Int128;
618 // Check for a complete enum type; incomplete enum types are not properly an
619 // enumeration type in the sense required here.
620 // C++0x: However, if the underlying type of the enum is fixed, it is
621 // considered complete.
622 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
623 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
630 bool Type::isCharType() const {
631 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
632 return BT->getKind() == BuiltinType::Char_U ||
633 BT->getKind() == BuiltinType::UChar ||
634 BT->getKind() == BuiltinType::Char_S ||
635 BT->getKind() == BuiltinType::SChar;
639 bool Type::isWideCharType() const {
640 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
641 return BT->getKind() == BuiltinType::WChar_S ||
642 BT->getKind() == BuiltinType::WChar_U;
646 bool Type::isChar16Type() const {
647 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
648 return BT->getKind() == BuiltinType::Char16;
652 bool Type::isChar32Type() const {
653 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
654 return BT->getKind() == BuiltinType::Char32;
658 /// \brief Determine whether this type is any of the built-in character
660 bool Type::isAnyCharacterType() const {
661 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
662 if (BT == 0) return false;
663 switch (BT->getKind()) {
664 default: return false;
665 case BuiltinType::Char_U:
666 case BuiltinType::UChar:
667 case BuiltinType::WChar_U:
668 case BuiltinType::Char16:
669 case BuiltinType::Char32:
670 case BuiltinType::Char_S:
671 case BuiltinType::SChar:
672 case BuiltinType::WChar_S:
677 /// isSignedIntegerType - Return true if this is an integer type that is
678 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
679 /// an enum decl which has a signed representation
680 bool Type::isSignedIntegerType() const {
681 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
682 return BT->getKind() >= BuiltinType::Char_S &&
683 BT->getKind() <= BuiltinType::Int128;
686 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
687 // Incomplete enum types are not treated as integer types.
688 // FIXME: In C++, enum types are never integer types.
689 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
690 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
696 bool Type::isSignedIntegerOrEnumerationType() const {
697 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
698 return BT->getKind() >= BuiltinType::Char_S &&
699 BT->getKind() <= BuiltinType::Int128;
702 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
703 if (ET->getDecl()->isComplete())
704 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
710 bool Type::hasSignedIntegerRepresentation() const {
711 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
712 return VT->getElementType()->isSignedIntegerType();
714 return isSignedIntegerType();
717 /// isUnsignedIntegerType - Return true if this is an integer type that is
718 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
719 /// decl which has an unsigned representation
720 bool Type::isUnsignedIntegerType() const {
721 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
722 return BT->getKind() >= BuiltinType::Bool &&
723 BT->getKind() <= BuiltinType::UInt128;
726 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
727 // Incomplete enum types are not treated as integer types.
728 // FIXME: In C++, enum types are never integer types.
729 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
730 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
736 bool Type::isUnsignedIntegerOrEnumerationType() const {
737 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
738 return BT->getKind() >= BuiltinType::Bool &&
739 BT->getKind() <= BuiltinType::UInt128;
742 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
743 if (ET->getDecl()->isComplete())
744 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
750 bool Type::hasUnsignedIntegerRepresentation() const {
751 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
752 return VT->getElementType()->isUnsignedIntegerType();
754 return isUnsignedIntegerType();
757 bool Type::isFloatingType() const {
758 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
759 return BT->getKind() >= BuiltinType::Half &&
760 BT->getKind() <= BuiltinType::LongDouble;
761 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
762 return CT->getElementType()->isFloatingType();
766 bool Type::hasFloatingRepresentation() const {
767 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
768 return VT->getElementType()->isFloatingType();
770 return isFloatingType();
773 bool Type::isRealFloatingType() const {
774 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
775 return BT->isFloatingPoint();
779 bool Type::isRealType() const {
780 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
781 return BT->getKind() >= BuiltinType::Bool &&
782 BT->getKind() <= BuiltinType::LongDouble;
783 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
784 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
788 bool Type::isArithmeticType() const {
789 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
790 return BT->getKind() >= BuiltinType::Bool &&
791 BT->getKind() <= BuiltinType::LongDouble;
792 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
793 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
794 // If a body isn't seen by the time we get here, return false.
796 // C++0x: Enumerations are not arithmetic types. For now, just return
797 // false for scoped enumerations since that will disable any
798 // unwanted implicit conversions.
799 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
800 return isa<ComplexType>(CanonicalType);
803 Type::ScalarTypeKind Type::getScalarTypeKind() const {
804 assert(isScalarType());
806 const Type *T = CanonicalType.getTypePtr();
807 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
808 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
809 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
810 if (BT->isInteger()) return STK_Integral;
811 if (BT->isFloatingPoint()) return STK_Floating;
812 llvm_unreachable("unknown scalar builtin type");
813 } else if (isa<PointerType>(T)) {
815 } else if (isa<BlockPointerType>(T)) {
816 return STK_BlockPointer;
817 } else if (isa<ObjCObjectPointerType>(T)) {
818 return STK_ObjCObjectPointer;
819 } else if (isa<MemberPointerType>(T)) {
820 return STK_MemberPointer;
821 } else if (isa<EnumType>(T)) {
822 assert(cast<EnumType>(T)->getDecl()->isComplete());
824 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
825 if (CT->getElementType()->isRealFloatingType())
826 return STK_FloatingComplex;
827 return STK_IntegralComplex;
830 llvm_unreachable("unknown scalar type");
833 /// \brief Determines whether the type is a C++ aggregate type or C
834 /// aggregate or union type.
836 /// An aggregate type is an array or a class type (struct, union, or
837 /// class) that has no user-declared constructors, no private or
838 /// protected non-static data members, no base classes, and no virtual
839 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
840 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
841 /// includes union types.
842 bool Type::isAggregateType() const {
843 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
844 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
845 return ClassDecl->isAggregate();
850 return isa<ArrayType>(CanonicalType);
853 /// isConstantSizeType - Return true if this is not a variable sized type,
854 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
855 /// incomplete types or dependent types.
856 bool Type::isConstantSizeType() const {
857 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
858 assert(!isDependentType() && "This doesn't make sense for dependent types");
859 // The VAT must have a size, as it is known to be complete.
860 return !isa<VariableArrayType>(CanonicalType);
863 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
864 /// - a type that can describe objects, but which lacks information needed to
865 /// determine its size.
866 bool Type::isIncompleteType(NamedDecl **Def) const {
870 switch (CanonicalType->getTypeClass()) {
871 default: return false;
873 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
877 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
881 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
882 if (EnumD->isFixed())
885 return !EnumD->isCompleteDefinition();
888 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
889 // forward declaration, but not a full definition (C99 6.2.5p22).
890 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
893 return !Rec->isCompleteDefinition();
896 // An array is incomplete if its element type is incomplete
897 // (C++ [dcl.array]p1).
898 // We don't handle variable arrays (they're not allowed in C++) or
899 // dependent-sized arrays (dependent types are never treated as incomplete).
900 return cast<ArrayType>(CanonicalType)->getElementType()
901 ->isIncompleteType(Def);
902 case IncompleteArray:
903 // An array of unknown size is an incomplete type (C99 6.2.5p22).
906 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
907 ->isIncompleteType(Def);
908 case ObjCInterface: {
909 // ObjC interfaces are incomplete if they are @class, not @interface.
910 ObjCInterfaceDecl *Interface
911 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
914 return !Interface->hasDefinition();
919 bool QualType::isPODType(ASTContext &Context) const {
920 // C++11 has a more relaxed definition of POD.
921 if (Context.getLangOpts().CPlusPlus0x)
922 return isCXX11PODType(Context);
924 return isCXX98PODType(Context);
927 bool QualType::isCXX98PODType(ASTContext &Context) const {
928 // The compiler shouldn't query this for incomplete types, but the user might.
929 // We return false for that case. Except for incomplete arrays of PODs, which
930 // are PODs according to the standard.
934 if ((*this)->isIncompleteArrayType())
935 return Context.getBaseElementType(*this).isCXX98PODType(Context);
937 if ((*this)->isIncompleteType())
940 if (Context.getLangOpts().ObjCAutoRefCount) {
941 switch (getObjCLifetime()) {
942 case Qualifiers::OCL_ExplicitNone:
945 case Qualifiers::OCL_Strong:
946 case Qualifiers::OCL_Weak:
947 case Qualifiers::OCL_Autoreleasing:
950 case Qualifiers::OCL_None:
955 QualType CanonicalType = getTypePtr()->CanonicalType;
956 switch (CanonicalType->getTypeClass()) {
957 // Everything not explicitly mentioned is not POD.
958 default: return false;
959 case Type::VariableArray:
960 case Type::ConstantArray:
961 // IncompleteArray is handled above.
962 return Context.getBaseElementType(*this).isCXX98PODType(Context);
964 case Type::ObjCObjectPointer:
965 case Type::BlockPointer:
969 case Type::MemberPointer:
971 case Type::ExtVector:
978 if (CXXRecordDecl *ClassDecl
979 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
980 return ClassDecl->isPOD();
982 // C struct/union is POD.
987 bool QualType::isTrivialType(ASTContext &Context) const {
988 // The compiler shouldn't query this for incomplete types, but the user might.
989 // We return false for that case. Except for incomplete arrays of PODs, which
990 // are PODs according to the standard.
994 if ((*this)->isArrayType())
995 return Context.getBaseElementType(*this).isTrivialType(Context);
997 // Return false for incomplete types after skipping any incomplete array
998 // types which are expressly allowed by the standard and thus our API.
999 if ((*this)->isIncompleteType())
1002 if (Context.getLangOpts().ObjCAutoRefCount) {
1003 switch (getObjCLifetime()) {
1004 case Qualifiers::OCL_ExplicitNone:
1007 case Qualifiers::OCL_Strong:
1008 case Qualifiers::OCL_Weak:
1009 case Qualifiers::OCL_Autoreleasing:
1012 case Qualifiers::OCL_None:
1013 if ((*this)->isObjCLifetimeType())
1019 QualType CanonicalType = getTypePtr()->CanonicalType;
1020 if (CanonicalType->isDependentType())
1023 // C++0x [basic.types]p9:
1024 // Scalar types, trivial class types, arrays of such types, and
1025 // cv-qualified versions of these types are collectively called trivial
1028 // As an extension, Clang treats vector types as Scalar types.
1029 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1031 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1032 if (const CXXRecordDecl *ClassDecl =
1033 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1035 // A trivial class is a class that has a trivial default constructor
1036 if (!ClassDecl->hasTrivialDefaultConstructor()) return false;
1037 // and is trivially copyable.
1038 if (!ClassDecl->isTriviallyCopyable()) return false;
1044 // No other types can match.
1048 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1049 if ((*this)->isArrayType())
1050 return Context.getBaseElementType(*this).isTrivialType(Context);
1052 if (Context.getLangOpts().ObjCAutoRefCount) {
1053 switch (getObjCLifetime()) {
1054 case Qualifiers::OCL_ExplicitNone:
1057 case Qualifiers::OCL_Strong:
1058 case Qualifiers::OCL_Weak:
1059 case Qualifiers::OCL_Autoreleasing:
1062 case Qualifiers::OCL_None:
1063 if ((*this)->isObjCLifetimeType())
1069 // C++0x [basic.types]p9
1070 // Scalar types, trivially copyable class types, arrays of such types, and
1071 // cv-qualified versions of these types are collectively called trivial
1074 QualType CanonicalType = getCanonicalType();
1075 if (CanonicalType->isDependentType())
1078 // Return false for incomplete types after skipping any incomplete array types
1079 // which are expressly allowed by the standard and thus our API.
1080 if (CanonicalType->isIncompleteType())
1083 // As an extension, Clang treats vector types as Scalar types.
1084 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1087 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1088 if (const CXXRecordDecl *ClassDecl =
1089 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1090 if (!ClassDecl->isTriviallyCopyable()) return false;
1096 // No other types can match.
1102 bool Type::isLiteralType() const {
1103 if (isDependentType())
1106 // C++0x [basic.types]p10:
1107 // A type is a literal type if it is:
1109 // -- an array of literal type.
1110 // Extension: variable arrays cannot be literal types, since they're
1112 if (isVariableArrayType())
1114 const Type *BaseTy = getBaseElementTypeUnsafe();
1115 assert(BaseTy && "NULL element type");
1117 // Return false for incomplete types after skipping any incomplete array
1118 // types; those are expressly allowed by the standard and thus our API.
1119 if (BaseTy->isIncompleteType())
1122 // C++0x [basic.types]p10:
1123 // A type is a literal type if it is:
1124 // -- a scalar type; or
1125 // As an extension, Clang treats vector types and complex types as
1127 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1128 BaseTy->isAnyComplexType())
1130 // -- a reference type; or
1131 if (BaseTy->isReferenceType())
1133 // -- a class type that has all of the following properties:
1134 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1135 // -- a trivial destructor,
1136 // -- every constructor call and full-expression in the
1137 // brace-or-equal-initializers for non-static data members (if any)
1138 // is a constant expression,
1139 // -- it is an aggregate type or has at least one constexpr
1140 // constructor or constructor template that is not a copy or move
1142 // -- all non-static data members and base classes of literal types
1144 // We resolve DR1361 by ignoring the second bullet.
1145 if (const CXXRecordDecl *ClassDecl =
1146 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1147 return ClassDecl->isLiteral();
1155 bool Type::isStandardLayoutType() const {
1156 if (isDependentType())
1159 // C++0x [basic.types]p9:
1160 // Scalar types, standard-layout class types, arrays of such types, and
1161 // cv-qualified versions of these types are collectively called
1162 // standard-layout types.
1163 const Type *BaseTy = getBaseElementTypeUnsafe();
1164 assert(BaseTy && "NULL element type");
1166 // Return false for incomplete types after skipping any incomplete array
1167 // types which are expressly allowed by the standard and thus our API.
1168 if (BaseTy->isIncompleteType())
1171 // As an extension, Clang treats vector types as Scalar types.
1172 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1173 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1174 if (const CXXRecordDecl *ClassDecl =
1175 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1176 if (!ClassDecl->isStandardLayout())
1179 // Default to 'true' for non-C++ class types.
1180 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1181 // all the requirements of standard layout classes.
1185 // No other types can match.
1189 // This is effectively the intersection of isTrivialType and
1190 // isStandardLayoutType. We implement it directly to avoid redundant
1191 // conversions from a type to a CXXRecordDecl.
1192 bool QualType::isCXX11PODType(ASTContext &Context) const {
1193 const Type *ty = getTypePtr();
1194 if (ty->isDependentType())
1197 if (Context.getLangOpts().ObjCAutoRefCount) {
1198 switch (getObjCLifetime()) {
1199 case Qualifiers::OCL_ExplicitNone:
1202 case Qualifiers::OCL_Strong:
1203 case Qualifiers::OCL_Weak:
1204 case Qualifiers::OCL_Autoreleasing:
1207 case Qualifiers::OCL_None:
1208 if (ty->isObjCLifetimeType())
1214 // C++11 [basic.types]p9:
1215 // Scalar types, POD classes, arrays of such types, and cv-qualified
1216 // versions of these types are collectively called trivial types.
1217 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1218 assert(BaseTy && "NULL element type");
1220 // Return false for incomplete types after skipping any incomplete array
1221 // types which are expressly allowed by the standard and thus our API.
1222 if (BaseTy->isIncompleteType())
1225 // As an extension, Clang treats vector types as Scalar types.
1226 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1227 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1228 if (const CXXRecordDecl *ClassDecl =
1229 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1230 // C++11 [class]p10:
1231 // A POD struct is a non-union class that is both a trivial class [...]
1232 if (!ClassDecl->isTrivial()) return false;
1234 // C++11 [class]p10:
1235 // A POD struct is a non-union class that is both a trivial class and
1236 // a standard-layout class [...]
1237 if (!ClassDecl->isStandardLayout()) return false;
1239 // C++11 [class]p10:
1240 // A POD struct is a non-union class that is both a trivial class and
1241 // a standard-layout class, and has no non-static data members of type
1242 // non-POD struct, non-POD union (or array of such types). [...]
1244 // We don't directly query the recursive aspect as the requiremets for
1245 // both standard-layout classes and trivial classes apply recursively
1252 // No other types can match.
1256 bool Type::isPromotableIntegerType() const {
1257 if (const BuiltinType *BT = getAs<BuiltinType>())
1258 switch (BT->getKind()) {
1259 case BuiltinType::Bool:
1260 case BuiltinType::Char_S:
1261 case BuiltinType::Char_U:
1262 case BuiltinType::SChar:
1263 case BuiltinType::UChar:
1264 case BuiltinType::Short:
1265 case BuiltinType::UShort:
1266 case BuiltinType::WChar_S:
1267 case BuiltinType::WChar_U:
1268 case BuiltinType::Char16:
1269 case BuiltinType::Char32:
1275 // Enumerated types are promotable to their compatible integer types
1276 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1277 if (const EnumType *ET = getAs<EnumType>()){
1278 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1279 || ET->getDecl()->isScoped())
1288 bool Type::isSpecifierType() const {
1289 // Note that this intentionally does not use the canonical type.
1290 switch (getTypeClass()) {
1298 case TemplateTypeParm:
1299 case SubstTemplateTypeParm:
1300 case TemplateSpecialization:
1303 case DependentTemplateSpecialization:
1306 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1313 ElaboratedTypeKeyword
1314 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1316 default: return ETK_None;
1317 case TST_typename: return ETK_Typename;
1318 case TST_class: return ETK_Class;
1319 case TST_struct: return ETK_Struct;
1320 case TST_union: return ETK_Union;
1321 case TST_enum: return ETK_Enum;
1326 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1328 case TST_class: return TTK_Class;
1329 case TST_struct: return TTK_Struct;
1330 case TST_union: return TTK_Union;
1331 case TST_enum: return TTK_Enum;
1334 llvm_unreachable("Type specifier is not a tag type kind.");
1337 ElaboratedTypeKeyword
1338 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1340 case TTK_Class: return ETK_Class;
1341 case TTK_Struct: return ETK_Struct;
1342 case TTK_Union: return ETK_Union;
1343 case TTK_Enum: return ETK_Enum;
1345 llvm_unreachable("Unknown tag type kind.");
1349 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1351 case ETK_Class: return TTK_Class;
1352 case ETK_Struct: return TTK_Struct;
1353 case ETK_Union: return TTK_Union;
1354 case ETK_Enum: return TTK_Enum;
1355 case ETK_None: // Fall through.
1357 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1359 llvm_unreachable("Unknown elaborated type keyword.");
1363 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1374 llvm_unreachable("Unknown elaborated type keyword.");
1378 TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1380 case ETK_None: return "";
1381 case ETK_Typename: return "typename";
1382 case ETK_Class: return "class";
1383 case ETK_Struct: return "struct";
1384 case ETK_Union: return "union";
1385 case ETK_Enum: return "enum";
1388 llvm_unreachable("Unknown elaborated type keyword.");
1391 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1392 ElaboratedTypeKeyword Keyword,
1393 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1394 unsigned NumArgs, const TemplateArgument *Args,
1396 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1397 /*VariablyModified=*/false,
1398 NNS && NNS->containsUnexpandedParameterPack()),
1399 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1400 assert((!NNS || NNS->isDependent()) &&
1401 "DependentTemplateSpecializatonType requires dependent qualifier");
1402 for (unsigned I = 0; I != NumArgs; ++I) {
1403 if (Args[I].containsUnexpandedParameterPack())
1404 setContainsUnexpandedParameterPack();
1406 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1411 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1412 const ASTContext &Context,
1413 ElaboratedTypeKeyword Keyword,
1414 NestedNameSpecifier *Qualifier,
1415 const IdentifierInfo *Name,
1417 const TemplateArgument *Args) {
1418 ID.AddInteger(Keyword);
1419 ID.AddPointer(Qualifier);
1420 ID.AddPointer(Name);
1421 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1422 Args[Idx].Profile(ID, Context);
1425 bool Type::isElaboratedTypeSpecifier() const {
1426 ElaboratedTypeKeyword Keyword;
1427 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1428 Keyword = Elab->getKeyword();
1429 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1430 Keyword = DepName->getKeyword();
1431 else if (const DependentTemplateSpecializationType *DepTST =
1432 dyn_cast<DependentTemplateSpecializationType>(this))
1433 Keyword = DepTST->getKeyword();
1437 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1440 const char *Type::getTypeClassName() const {
1441 switch (TypeBits.TC) {
1442 #define ABSTRACT_TYPE(Derived, Base)
1443 #define TYPE(Derived, Base) case Derived: return #Derived;
1444 #include "clang/AST/TypeNodes.def"
1447 llvm_unreachable("Invalid type class.");
1450 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1451 switch (getKind()) {
1452 case Void: return "void";
1453 case Bool: return Policy.Bool ? "bool" : "_Bool";
1454 case Char_S: return "char";
1455 case Char_U: return "char";
1456 case SChar: return "signed char";
1457 case Short: return "short";
1458 case Int: return "int";
1459 case Long: return "long";
1460 case LongLong: return "long long";
1461 case Int128: return "__int128";
1462 case UChar: return "unsigned char";
1463 case UShort: return "unsigned short";
1464 case UInt: return "unsigned int";
1465 case ULong: return "unsigned long";
1466 case ULongLong: return "unsigned long long";
1467 case UInt128: return "unsigned __int128";
1468 case Half: return "half";
1469 case Float: return "float";
1470 case Double: return "double";
1471 case LongDouble: return "long double";
1473 case WChar_U: return "wchar_t";
1474 case Char16: return "char16_t";
1475 case Char32: return "char32_t";
1476 case NullPtr: return "nullptr_t";
1477 case Overload: return "<overloaded function type>";
1478 case BoundMember: return "<bound member function type>";
1479 case PseudoObject: return "<pseudo-object type>";
1480 case Dependent: return "<dependent type>";
1481 case UnknownAny: return "<unknown type>";
1482 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1483 case ObjCId: return "id";
1484 case ObjCClass: return "Class";
1485 case ObjCSel: return "SEL";
1488 llvm_unreachable("Invalid builtin type.");
1491 QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1492 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1493 return RefType->getPointeeType();
1495 // C++0x [basic.lval]:
1496 // Class prvalues can have cv-qualified types; non-class prvalues always
1497 // have cv-unqualified types.
1499 // See also C99 6.3.2.1p2.
1500 if (!Context.getLangOpts().CPlusPlus ||
1501 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1502 return getUnqualifiedType();
1507 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1510 llvm_unreachable("no name for default cc");
1512 case CC_C: return "cdecl";
1513 case CC_X86StdCall: return "stdcall";
1514 case CC_X86FastCall: return "fastcall";
1515 case CC_X86ThisCall: return "thiscall";
1516 case CC_X86Pascal: return "pascal";
1517 case CC_AAPCS: return "aapcs";
1518 case CC_AAPCS_VFP: return "aapcs-vfp";
1521 llvm_unreachable("Invalid calling convention.");
1524 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1525 unsigned numArgs, QualType canonical,
1526 const ExtProtoInfo &epi)
1527 : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
1529 result->isDependentType(),
1530 result->isInstantiationDependentType(),
1531 result->isVariablyModifiedType(),
1532 result->containsUnexpandedParameterPack(),
1534 NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1535 ExceptionSpecType(epi.ExceptionSpecType),
1536 HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1537 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
1539 // Fill in the trailing argument array.
1540 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1541 for (unsigned i = 0; i != numArgs; ++i) {
1542 if (args[i]->isDependentType())
1544 else if (args[i]->isInstantiationDependentType())
1545 setInstantiationDependent();
1547 if (args[i]->containsUnexpandedParameterPack())
1548 setContainsUnexpandedParameterPack();
1550 argSlot[i] = args[i];
1553 if (getExceptionSpecType() == EST_Dynamic) {
1554 // Fill in the exception array.
1555 QualType *exnSlot = argSlot + numArgs;
1556 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1557 if (epi.Exceptions[i]->isDependentType())
1559 else if (epi.Exceptions[i]->isInstantiationDependentType())
1560 setInstantiationDependent();
1562 if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1563 setContainsUnexpandedParameterPack();
1565 exnSlot[i] = epi.Exceptions[i];
1567 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1568 // Store the noexcept expression and context.
1569 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1570 *noexSlot = epi.NoexceptExpr;
1572 if (epi.NoexceptExpr) {
1573 if (epi.NoexceptExpr->isValueDependent()
1574 || epi.NoexceptExpr->isTypeDependent())
1576 else if (epi.NoexceptExpr->isInstantiationDependent())
1577 setInstantiationDependent();
1579 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1580 // Store the function decl from which we will resolve our
1581 // exception specification.
1582 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1583 slot[0] = epi.ExceptionSpecDecl;
1584 slot[1] = epi.ExceptionSpecTemplate;
1585 // This exception specification doesn't make the type dependent, because
1586 // it's not instantiated as part of instantiating the type.
1587 } else if (getExceptionSpecType() == EST_Unevaluated) {
1588 // Store the function decl from which we will resolve our
1589 // exception specification.
1590 FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1591 slot[0] = epi.ExceptionSpecDecl;
1594 if (epi.ConsumedArguments) {
1595 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1596 for (unsigned i = 0; i != numArgs; ++i)
1597 consumedArgs[i] = epi.ConsumedArguments[i];
1601 FunctionProtoType::NoexceptResult
1602 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1603 ExceptionSpecificationType est = getExceptionSpecType();
1604 if (est == EST_BasicNoexcept)
1607 if (est != EST_ComputedNoexcept)
1608 return NR_NoNoexcept;
1610 Expr *noexceptExpr = getNoexceptExpr();
1612 return NR_BadNoexcept;
1613 if (noexceptExpr->isValueDependent())
1614 return NR_Dependent;
1617 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1618 /*evaluated*/false);
1620 assert(isICE && "AST should not contain bad noexcept expressions.");
1622 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1625 bool FunctionProtoType::isTemplateVariadic() const {
1626 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1627 if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1633 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1634 const QualType *ArgTys, unsigned NumArgs,
1635 const ExtProtoInfo &epi,
1636 const ASTContext &Context) {
1638 // We have to be careful not to get ambiguous profile encodings.
1639 // Note that valid type pointers are never ambiguous with anything else.
1641 // The encoding grammar begins:
1642 // type type* bool int bool
1643 // If that final bool is true, then there is a section for the EH spec:
1645 // This is followed by an optional "consumed argument" section of the
1646 // same length as the first type sequence:
1648 // Finally, we have the ext info and trailing return type flag:
1651 // There is no ambiguity between the consumed arguments and an empty EH
1652 // spec because of the leading 'bool' which unambiguously indicates
1653 // whether the following bool is the EH spec or part of the arguments.
1655 ID.AddPointer(Result.getAsOpaquePtr());
1656 for (unsigned i = 0; i != NumArgs; ++i)
1657 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1658 // This method is relatively performance sensitive, so as a performance
1659 // shortcut, use one AddInteger call instead of four for the next four
1661 assert(!(unsigned(epi.Variadic) & ~1) &&
1662 !(unsigned(epi.TypeQuals) & ~255) &&
1663 !(unsigned(epi.RefQualifier) & ~3) &&
1664 !(unsigned(epi.ExceptionSpecType) & ~7) &&
1665 "Values larger than expected.");
1666 ID.AddInteger(unsigned(epi.Variadic) +
1667 (epi.TypeQuals << 1) +
1668 (epi.RefQualifier << 9) +
1669 (epi.ExceptionSpecType << 11));
1670 if (epi.ExceptionSpecType == EST_Dynamic) {
1671 for (unsigned i = 0; i != epi.NumExceptions; ++i)
1672 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1673 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1674 epi.NoexceptExpr->Profile(ID, Context, false);
1675 } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1676 epi.ExceptionSpecType == EST_Unevaluated) {
1677 ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1679 if (epi.ConsumedArguments) {
1680 for (unsigned i = 0; i != NumArgs; ++i)
1681 ID.AddBoolean(epi.ConsumedArguments[i]);
1683 epi.ExtInfo.Profile(ID);
1684 ID.AddBoolean(epi.HasTrailingReturn);
1687 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1688 const ASTContext &Ctx) {
1689 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1693 QualType TypedefType::desugar() const {
1694 return getDecl()->getUnderlyingType();
1697 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1698 : Type(TypeOfExpr, can, E->isTypeDependent(),
1699 E->isInstantiationDependent(),
1700 E->getType()->isVariablyModifiedType(),
1701 E->containsUnexpandedParameterPack()),
1705 bool TypeOfExprType::isSugared() const {
1706 return !TOExpr->isTypeDependent();
1709 QualType TypeOfExprType::desugar() const {
1711 return getUnderlyingExpr()->getType();
1713 return QualType(this, 0);
1716 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1717 const ASTContext &Context, Expr *E) {
1718 E->Profile(ID, Context, true);
1721 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1722 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1723 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1724 // type-dependent even if its expression is only instantiation-dependent.
1725 : Type(Decltype, can, E->isInstantiationDependent(),
1726 E->isInstantiationDependent(),
1727 E->getType()->isVariablyModifiedType(),
1728 E->containsUnexpandedParameterPack()),
1730 UnderlyingType(underlyingType) {
1733 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1735 QualType DecltypeType::desugar() const {
1737 return getUnderlyingType();
1739 return QualType(this, 0);
1742 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1743 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1745 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1746 const ASTContext &Context, Expr *E) {
1747 E->Profile(ID, Context, true);
1750 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1751 : Type(TC, can, D->isDependentType(),
1752 /*InstantiationDependent=*/D->isDependentType(),
1753 /*VariablyModified=*/false,
1754 /*ContainsUnexpandedParameterPack=*/false),
1755 decl(const_cast<TagDecl*>(D)) {}
1757 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1758 for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1759 E = decl->redecls_end();
1761 if (I->isCompleteDefinition() || I->isBeingDefined())
1764 // If there's no definition (not even in progress), return what we have.
1768 UnaryTransformType::UnaryTransformType(QualType BaseType,
1769 QualType UnderlyingType,
1771 QualType CanonicalType)
1772 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1773 UnderlyingType->isInstantiationDependentType(),
1774 UnderlyingType->isVariablyModifiedType(),
1775 BaseType->containsUnexpandedParameterPack())
1776 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1779 TagDecl *TagType::getDecl() const {
1780 return getInterestingTagDecl(decl);
1783 bool TagType::isBeingDefined() const {
1784 return getDecl()->isBeingDefined();
1787 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1788 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1791 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1792 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1795 SubstTemplateTypeParmPackType::
1796 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1798 const TemplateArgument &ArgPack)
1799 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1801 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1805 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1806 return TemplateArgument(Arguments, NumArguments);
1809 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1810 Profile(ID, getReplacedParameter(), getArgumentPack());
1813 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1814 const TemplateTypeParmType *Replaced,
1815 const TemplateArgument &ArgPack) {
1816 ID.AddPointer(Replaced);
1817 ID.AddInteger(ArgPack.pack_size());
1818 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1819 PEnd = ArgPack.pack_end();
1821 ID.AddPointer(P->getAsType().getAsOpaquePtr());
1824 bool TemplateSpecializationType::
1825 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1826 bool &InstantiationDependent) {
1827 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1828 InstantiationDependent);
1831 bool TemplateSpecializationType::
1832 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1833 bool &InstantiationDependent) {
1834 for (unsigned i = 0; i != N; ++i) {
1835 if (Args[i].getArgument().isDependent()) {
1836 InstantiationDependent = true;
1840 if (Args[i].getArgument().isInstantiationDependent())
1841 InstantiationDependent = true;
1846 bool TemplateSpecializationType::
1847 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1848 bool &InstantiationDependent) {
1849 for (unsigned i = 0; i != N; ++i) {
1850 if (Args[i].isDependent()) {
1851 InstantiationDependent = true;
1855 if (Args[i].isInstantiationDependent())
1856 InstantiationDependent = true;
1861 TemplateSpecializationType::
1862 TemplateSpecializationType(TemplateName T,
1863 const TemplateArgument *Args, unsigned NumArgs,
1864 QualType Canon, QualType AliasedType)
1865 : Type(TemplateSpecialization,
1866 Canon.isNull()? QualType(this, 0) : Canon,
1867 Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1868 Canon.isNull()? T.isDependent()
1869 : Canon->isInstantiationDependentType(),
1871 T.containsUnexpandedParameterPack()),
1872 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1873 assert(!T.getAsDependentTemplateName() &&
1874 "Use DependentTemplateSpecializationType for dependent template-name");
1875 assert((T.getKind() == TemplateName::Template ||
1876 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1877 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1878 "Unexpected template name for TemplateSpecializationType");
1879 bool InstantiationDependent;
1880 (void)InstantiationDependent;
1881 assert((!Canon.isNull() ||
1883 anyDependentTemplateArguments(Args, NumArgs,
1884 InstantiationDependent)) &&
1885 "No canonical type for non-dependent class template specialization");
1887 TemplateArgument *TemplateArgs
1888 = reinterpret_cast<TemplateArgument *>(this + 1);
1889 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1890 // Update dependent and variably-modified bits.
1891 // If the canonical type exists and is non-dependent, the template
1892 // specialization type can be non-dependent even if one of the type
1893 // arguments is. Given:
1894 // template<typename T> using U = int;
1895 // U<T> is always non-dependent, irrespective of the type T.
1896 // However, U<Ts> contains an unexpanded parameter pack, even though
1897 // its expansion (and thus its desugared type) doesn't.
1898 if (Canon.isNull() && Args[Arg].isDependent())
1900 else if (Args[Arg].isInstantiationDependent())
1901 setInstantiationDependent();
1903 if (Args[Arg].getKind() == TemplateArgument::Type &&
1904 Args[Arg].getAsType()->isVariablyModifiedType())
1905 setVariablyModified();
1906 if (Args[Arg].containsUnexpandedParameterPack())
1907 setContainsUnexpandedParameterPack();
1909 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1912 // Store the aliased type if this is a type alias template specialization.
1914 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1915 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1920 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1922 const TemplateArgument *Args,
1924 const ASTContext &Context) {
1926 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1927 Args[Idx].Profile(ID, Context);
1931 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1932 if (!hasNonFastQualifiers())
1933 return QT.withFastQualifiers(getFastQualifiers());
1935 return Context.getQualifiedType(QT, *this);
1939 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1940 if (!hasNonFastQualifiers())
1941 return QualType(T, getFastQualifiers());
1943 return Context.getQualifiedType(T, *this);
1946 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1948 ObjCProtocolDecl * const *Protocols,
1949 unsigned NumProtocols) {
1950 ID.AddPointer(BaseType.getAsOpaquePtr());
1951 for (unsigned i = 0; i != NumProtocols; i++)
1952 ID.AddPointer(Protocols[i]);
1955 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1956 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1961 /// \brief The cached properties of a type.
1962 class CachedProperties {
1963 NamedDecl::LinkageInfo LV;
1967 CachedProperties(NamedDecl::LinkageInfo LV, bool local)
1968 : LV(LV), local(local) {}
1970 Linkage getLinkage() const { return LV.linkage(); }
1971 Visibility getVisibility() const { return LV.visibility(); }
1972 bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
1973 bool hasLocalOrUnnamedType() const { return local; }
1975 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1976 NamedDecl::LinkageInfo MergedLV = L.LV;
1977 MergedLV.merge(R.LV);
1978 return CachedProperties(MergedLV,
1979 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1984 static CachedProperties computeCachedProperties(const Type *T);
1987 /// The type-property cache. This is templated so as to be
1988 /// instantiated at an internal type to prevent unnecessary symbol
1990 template <class Private> class TypePropertyCache {
1992 static CachedProperties get(QualType T) {
1993 return get(T.getTypePtr());
1996 static CachedProperties get(const Type *T) {
1998 NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
1999 T->TypeBits.getVisibility(),
2000 T->TypeBits.isVisibilityExplicit());
2001 return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
2004 static void ensure(const Type *T) {
2005 // If the cache is valid, we're okay.
2006 if (T->TypeBits.isCacheValid()) return;
2008 // If this type is non-canonical, ask its canonical type for the
2009 // relevant information.
2010 if (!T->isCanonicalUnqualified()) {
2011 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2013 T->TypeBits.CacheValidAndVisibility =
2014 CT->TypeBits.CacheValidAndVisibility;
2015 T->TypeBits.CachedExplicitVisibility =
2016 CT->TypeBits.CachedExplicitVisibility;
2017 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2018 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2022 // Compute the cached properties and then set the cache.
2023 CachedProperties Result = computeCachedProperties(T);
2024 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
2025 T->TypeBits.CachedExplicitVisibility = Result.isVisibilityExplicit();
2026 assert(T->TypeBits.isCacheValid() &&
2027 T->TypeBits.getVisibility() == Result.getVisibility());
2028 T->TypeBits.CachedLinkage = Result.getLinkage();
2029 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2034 // Instantiate the friend template at a private class. In a
2035 // reasonable implementation, these symbols will be internal.
2036 // It is terrible that this is the best way to accomplish this.
2037 namespace { class Private {}; }
2038 typedef TypePropertyCache<Private> Cache;
2040 static CachedProperties computeCachedProperties(const Type *T) {
2041 switch (T->getTypeClass()) {
2042 #define TYPE(Class,Base)
2043 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2044 #include "clang/AST/TypeNodes.def"
2045 llvm_unreachable("didn't expect a non-canonical type here");
2047 #define TYPE(Class,Base)
2048 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2049 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2050 #include "clang/AST/TypeNodes.def"
2051 // Treat instantiation-dependent types as external.
2052 assert(T->isInstantiationDependentType());
2053 return CachedProperties(NamedDecl::LinkageInfo(), false);
2056 // C++ [basic.link]p8:
2057 // A type is said to have linkage if and only if:
2058 // - it is a fundamental type (3.9.1); or
2059 return CachedProperties(NamedDecl::LinkageInfo(), false);
2063 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2065 // C++ [basic.link]p8:
2066 // - it is a class or enumeration type that is named (or has a name
2067 // for linkage purposes (7.1.3)) and the name has linkage; or
2068 // - it is a specialization of a class template (14); or
2069 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2070 bool IsLocalOrUnnamed =
2071 Tag->getDeclContext()->isFunctionOrMethod() ||
2072 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2073 return CachedProperties(LV, IsLocalOrUnnamed);
2076 // C++ [basic.link]p8:
2077 // - it is a compound type (3.9.2) other than a class or enumeration,
2078 // compounded exclusively from types that have linkage; or
2080 return Cache::get(cast<ComplexType>(T)->getElementType());
2082 return Cache::get(cast<PointerType>(T)->getPointeeType());
2083 case Type::BlockPointer:
2084 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2085 case Type::LValueReference:
2086 case Type::RValueReference:
2087 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2088 case Type::MemberPointer: {
2089 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2090 return merge(Cache::get(MPT->getClass()),
2091 Cache::get(MPT->getPointeeType()));
2093 case Type::ConstantArray:
2094 case Type::IncompleteArray:
2095 case Type::VariableArray:
2096 return Cache::get(cast<ArrayType>(T)->getElementType());
2098 case Type::ExtVector:
2099 return Cache::get(cast<VectorType>(T)->getElementType());
2100 case Type::FunctionNoProto:
2101 return Cache::get(cast<FunctionType>(T)->getResultType());
2102 case Type::FunctionProto: {
2103 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2104 CachedProperties result = Cache::get(FPT->getResultType());
2105 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2106 ae = FPT->arg_type_end(); ai != ae; ++ai)
2107 result = merge(result, Cache::get(*ai));
2110 case Type::ObjCInterface: {
2111 NamedDecl::LinkageInfo LV =
2112 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2113 return CachedProperties(LV, false);
2115 case Type::ObjCObject:
2116 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2117 case Type::ObjCObjectPointer:
2118 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2120 return Cache::get(cast<AtomicType>(T)->getValueType());
2123 llvm_unreachable("unhandled type class");
2126 /// \brief Determine the linkage of this type.
2127 Linkage Type::getLinkage() const {
2128 Cache::ensure(this);
2129 return TypeBits.getLinkage();
2132 /// \brief Determine the linkage of this type.
2133 Visibility Type::getVisibility() const {
2134 Cache::ensure(this);
2135 return TypeBits.getVisibility();
2138 bool Type::isVisibilityExplicit() const {
2139 Cache::ensure(this);
2140 return TypeBits.isVisibilityExplicit();
2143 bool Type::hasUnnamedOrLocalType() const {
2144 Cache::ensure(this);
2145 return TypeBits.hasLocalOrUnnamedType();
2148 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2149 Cache::ensure(this);
2150 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2153 void Type::ClearLinkageCache() {
2154 TypeBits.CacheValidAndVisibility = 0;
2155 if (QualType(this, 0) != CanonicalType)
2156 CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2159 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2160 if (isObjCARCImplicitlyUnretainedType())
2161 return Qualifiers::OCL_ExplicitNone;
2162 return Qualifiers::OCL_Strong;
2165 bool Type::isObjCARCImplicitlyUnretainedType() const {
2166 assert(isObjCLifetimeType() &&
2167 "cannot query implicit lifetime for non-inferrable type");
2169 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2171 // Walk down to the base type. We don't care about qualifiers for this.
2172 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2173 canon = array->getElementType().getTypePtr();
2175 if (const ObjCObjectPointerType *opt
2176 = dyn_cast<ObjCObjectPointerType>(canon)) {
2177 // Class and Class<Protocol> don't require retension.
2178 if (opt->getObjectType()->isObjCClass())
2185 bool Type::isObjCNSObjectType() const {
2186 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2187 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2190 bool Type::isObjCRetainableType() const {
2191 return isObjCObjectPointerType() ||
2192 isBlockPointerType() ||
2193 isObjCNSObjectType();
2195 bool Type::isObjCIndirectLifetimeType() const {
2196 if (isObjCLifetimeType())
2198 if (const PointerType *OPT = getAs<PointerType>())
2199 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2200 if (const ReferenceType *Ref = getAs<ReferenceType>())
2201 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2202 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2203 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2207 /// Returns true if objects of this type have lifetime semantics under
2209 bool Type::isObjCLifetimeType() const {
2210 const Type *type = this;
2211 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2212 type = array->getElementType().getTypePtr();
2213 return type->isObjCRetainableType();
2216 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2217 /// which is either an Objective-C object pointer type or an
2218 bool Type::isObjCARCBridgableType() const {
2219 return isObjCObjectPointerType() || isBlockPointerType();
2222 /// \brief Determine whether the given type T is a "bridgeable" C type.
2223 bool Type::isCARCBridgableType() const {
2224 const PointerType *Pointer = getAs<PointerType>();
2228 QualType Pointee = Pointer->getPointeeType();
2229 return Pointee->isVoidType() || Pointee->isRecordType();
2232 bool Type::hasSizedVLAType() const {
2233 if (!isVariablyModifiedType()) return false;
2235 if (const PointerType *ptr = getAs<PointerType>())
2236 return ptr->getPointeeType()->hasSizedVLAType();
2237 if (const ReferenceType *ref = getAs<ReferenceType>())
2238 return ref->getPointeeType()->hasSizedVLAType();
2239 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2240 if (isa<VariableArrayType>(arr) &&
2241 cast<VariableArrayType>(arr)->getSizeExpr())
2244 return arr->getElementType()->hasSizedVLAType();
2250 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2251 switch (type.getObjCLifetime()) {
2252 case Qualifiers::OCL_None:
2253 case Qualifiers::OCL_ExplicitNone:
2254 case Qualifiers::OCL_Autoreleasing:
2257 case Qualifiers::OCL_Strong:
2258 return DK_objc_strong_lifetime;
2259 case Qualifiers::OCL_Weak:
2260 return DK_objc_weak_lifetime;
2263 /// Currently, the only destruction kind we recognize is C++ objects
2264 /// with non-trivial destructors.
2265 const CXXRecordDecl *record =
2266 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2267 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2268 return DK_cxx_destructor;
2273 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
2274 switch (getObjCLifetime()) {
2275 case Qualifiers::OCL_None:
2278 case Qualifiers::OCL_ExplicitNone:
2281 case Qualifiers::OCL_Autoreleasing:
2282 case Qualifiers::OCL_Strong:
2283 case Qualifiers::OCL_Weak:
2284 return !Context.getLangOpts().ObjCAutoRefCount;
2287 if (const CXXRecordDecl *Record
2288 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2289 return Copying ? Record->hasTrivialCopyAssignment() :
2290 Record->hasTrivialMoveAssignment();