Type.cpp revision 4d9d157afb35742bc6348defbe45bc6de780ec77
1//===--- Type.cpp - Type representation and manipulation ------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements type-related functionality. 11// 12//===----------------------------------------------------------------------===// 13 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" 27#include <algorithm> 28using namespace clang; 29 30bool 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())); 43} 44 45const IdentifierInfo* QualType::getBaseTypeIdentifier() const { 46 const Type* ty = getTypePtr(); 47 NamedDecl *ND = NULL; 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(); 59 60 if (ND) 61 return ND->getIdentifier(); 62 return NULL; 63} 64 65bool QualType::isConstant(QualType T, ASTContext &Ctx) { 66 if (T.isConstQualified()) 67 return true; 68 69 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 70 return AT->getElementType().isConstant(Ctx); 71 72 return false; 73} 74 75unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context, 76 QualType ElementType, 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); 82 83 uint64_t ElementSize 84 = Context.getTypeSizeInChars(ElementType).getQuantity(); 85 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); 86 TotalSize *= SizeExtended; 87 88 return TotalSize.getActiveBits(); 89} 90 91unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) { 92 unsigned Bits = Context.getTypeSize(Context.getSizeType()); 93 94 // GCC appears to only allow 63 bits worth of address space when compiling 95 // for 64-bit, so we do the same. 96 if (Bits == 64) 97 --Bits; 98 99 return Bits; 100} 101 102DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 103 QualType et, QualType can, 104 Expr *e, ArraySizeModifier sm, 105 unsigned tq, 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) 111{ 112} 113 114void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, 115 const ASTContext &Context, 116 QualType ET, 117 ArraySizeModifier SizeMod, 118 unsigned TypeQuals, 119 Expr *E) { 120 ID.AddPointer(ET.getAsOpaquePtr()); 121 ID.AddInteger(SizeMod); 122 ID.AddInteger(TypeQuals); 123 E->Profile(ID, Context, true); 124} 125 126DependentSizedExtVectorType::DependentSizedExtVectorType(const 127 ASTContext &Context, 128 QualType ElementType, 129 QualType can, 130 Expr *SizeExpr, 131 SourceLocation loc) 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), 138 loc(loc) 139{ 140} 141 142void 143DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, 144 const ASTContext &Context, 145 QualType ElementType, Expr *SizeExpr) { 146 ID.AddPointer(ElementType.getAsOpaquePtr()); 147 SizeExpr->Profile(ID, Context, true); 148} 149 150VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType, 151 VectorKind vecKind) 152 : Type(Vector, canonType, vecType->isDependentType(), 153 vecType->isInstantiationDependentType(), 154 vecType->isVariablyModifiedType(), 155 vecType->containsUnexpandedParameterPack()), 156 ElementType(vecType) 157{ 158 VectorTypeBits.VecKind = vecKind; 159 VectorTypeBits.NumElements = nElements; 160} 161 162VectorType::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()), 168 ElementType(vecType) 169{ 170 VectorTypeBits.VecKind = vecKind; 171 VectorTypeBits.NumElements = nElements; 172} 173 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. 177const 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(); 181 182 // If the canonical form of this type isn't the right kind, reject it. 183 if (!isa<ArrayType>(CanonicalType)) 184 return 0; 185 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(); 190} 191 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 197/// concrete. 198QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 199 SplitQualType split = getSplitDesugaredType(T); 200 return Context.getQualifiedType(split.first, split.second); 201} 202 203QualType QualType::getSingleStepDesugaredType(const ASTContext &Context) const { 204 QualifierCollector Qs; 205 206 const Type *CurTy = Qs.strip(*this); 207 switch (CurTy->getTypeClass()) { 208#define ABSTRACT_TYPE(Class, Parent) 209#define TYPE(Class, Parent) \ 210 case Type::Class: { \ 211 const Class##Type *Ty = cast<Class##Type>(CurTy); \ 212 if (!Ty->isSugared()) \ 213 return *this; \ 214 return Context.getQualifiedType(Ty->desugar(), Qs); \ 215 break; \ 216 } 217#include "clang/AST/TypeNodes.def" 218 } 219 220 return *this; 221} 222 223SplitQualType QualType::getSplitDesugaredType(QualType T) { 224 QualifierCollector Qs; 225 226 QualType Cur = T; 227 while (true) { 228 const Type *CurTy = Qs.strip(Cur); 229 switch (CurTy->getTypeClass()) { 230#define ABSTRACT_TYPE(Class, Parent) 231#define TYPE(Class, Parent) \ 232 case Type::Class: { \ 233 const Class##Type *Ty = cast<Class##Type>(CurTy); \ 234 if (!Ty->isSugared()) \ 235 return SplitQualType(Ty, Qs); \ 236 Cur = Ty->desugar(); \ 237 break; \ 238 } 239#include "clang/AST/TypeNodes.def" 240 } 241 } 242} 243 244SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) { 245 SplitQualType split = type.split(); 246 247 // All the qualifiers we've seen so far. 248 Qualifiers quals = split.second; 249 250 // The last type node we saw with any nodes inside it. 251 const Type *lastTypeWithQuals = split.first; 252 253 while (true) { 254 QualType next; 255 256 // Do a single-step desugar, aborting the loop if the type isn't 257 // sugared. 258 switch (split.first->getTypeClass()) { 259#define ABSTRACT_TYPE(Class, Parent) 260#define TYPE(Class, Parent) \ 261 case Type::Class: { \ 262 const Class##Type *ty = cast<Class##Type>(split.first); \ 263 if (!ty->isSugared()) goto done; \ 264 next = ty->desugar(); \ 265 break; \ 266 } 267#include "clang/AST/TypeNodes.def" 268 } 269 270 // Otherwise, split the underlying type. If that yields qualifiers, 271 // update the information. 272 split = next.split(); 273 if (!split.second.empty()) { 274 lastTypeWithQuals = split.first; 275 quals.addConsistentQualifiers(split.second); 276 } 277 } 278 279 done: 280 return SplitQualType(lastTypeWithQuals, quals); 281} 282 283QualType QualType::IgnoreParens(QualType T) { 284 // FIXME: this seems inherently un-qualifiers-safe. 285 while (const ParenType *PT = T->getAs<ParenType>()) 286 T = PT->getInnerType(); 287 return T; 288} 289 290/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic 291/// sugar off the given type. This should produce an object of the 292/// same dynamic type as the canonical type. 293const Type *Type::getUnqualifiedDesugaredType() const { 294 const Type *Cur = this; 295 296 while (true) { 297 switch (Cur->getTypeClass()) { 298#define ABSTRACT_TYPE(Class, Parent) 299#define TYPE(Class, Parent) \ 300 case Class: { \ 301 const Class##Type *Ty = cast<Class##Type>(Cur); \ 302 if (!Ty->isSugared()) return Cur; \ 303 Cur = Ty->desugar().getTypePtr(); \ 304 break; \ 305 } 306#include "clang/AST/TypeNodes.def" 307 } 308 } 309} 310 311/// isVoidType - Helper method to determine if this is the 'void' type. 312bool Type::isVoidType() const { 313 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 314 return BT->getKind() == BuiltinType::Void; 315 return false; 316} 317 318bool Type::isDerivedType() const { 319 switch (CanonicalType->getTypeClass()) { 320 case Pointer: 321 case VariableArray: 322 case ConstantArray: 323 case IncompleteArray: 324 case FunctionProto: 325 case FunctionNoProto: 326 case LValueReference: 327 case RValueReference: 328 case Record: 329 return true; 330 default: 331 return false; 332 } 333} 334bool Type::isClassType() const { 335 if (const RecordType *RT = getAs<RecordType>()) 336 return RT->getDecl()->isClass(); 337 return false; 338} 339bool Type::isStructureType() const { 340 if (const RecordType *RT = getAs<RecordType>()) 341 return RT->getDecl()->isStruct(); 342 return false; 343} 344bool Type::isStructureOrClassType() const { 345 if (const RecordType *RT = getAs<RecordType>()) 346 return RT->getDecl()->isStruct() || RT->getDecl()->isClass(); 347 return false; 348} 349bool Type::isVoidPointerType() const { 350 if (const PointerType *PT = getAs<PointerType>()) 351 return PT->getPointeeType()->isVoidType(); 352 return false; 353} 354 355bool Type::isUnionType() const { 356 if (const RecordType *RT = getAs<RecordType>()) 357 return RT->getDecl()->isUnion(); 358 return false; 359} 360 361bool Type::isComplexType() const { 362 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 363 return CT->getElementType()->isFloatingType(); 364 return false; 365} 366 367bool Type::isComplexIntegerType() const { 368 // Check for GCC complex integer extension. 369 return getAsComplexIntegerType(); 370} 371 372const ComplexType *Type::getAsComplexIntegerType() const { 373 if (const ComplexType *Complex = getAs<ComplexType>()) 374 if (Complex->getElementType()->isIntegerType()) 375 return Complex; 376 return 0; 377} 378 379QualType Type::getPointeeType() const { 380 if (const PointerType *PT = getAs<PointerType>()) 381 return PT->getPointeeType(); 382 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) 383 return OPT->getPointeeType(); 384 if (const BlockPointerType *BPT = getAs<BlockPointerType>()) 385 return BPT->getPointeeType(); 386 if (const ReferenceType *RT = getAs<ReferenceType>()) 387 return RT->getPointeeType(); 388 return QualType(); 389} 390 391const RecordType *Type::getAsStructureType() const { 392 // If this is directly a structure type, return it. 393 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 394 if (RT->getDecl()->isStruct()) 395 return RT; 396 } 397 398 // If the canonical form of this type isn't the right kind, reject it. 399 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 400 if (!RT->getDecl()->isStruct()) 401 return 0; 402 403 // If this is a typedef for a structure type, strip the typedef off without 404 // losing all typedef information. 405 return cast<RecordType>(getUnqualifiedDesugaredType()); 406 } 407 return 0; 408} 409 410const RecordType *Type::getAsUnionType() const { 411 // If this is directly a union type, return it. 412 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 413 if (RT->getDecl()->isUnion()) 414 return RT; 415 } 416 417 // If the canonical form of this type isn't the right kind, reject it. 418 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 419 if (!RT->getDecl()->isUnion()) 420 return 0; 421 422 // If this is a typedef for a union type, strip the typedef off without 423 // losing all typedef information. 424 return cast<RecordType>(getUnqualifiedDesugaredType()); 425 } 426 427 return 0; 428} 429 430ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, 431 ObjCProtocolDecl * const *Protocols, 432 unsigned NumProtocols) 433 : Type(ObjCObject, Canonical, false, false, false, false), 434 BaseType(Base) 435{ 436 ObjCObjectTypeBits.NumProtocols = NumProtocols; 437 assert(getNumProtocols() == NumProtocols && 438 "bitfield overflow in protocol count"); 439 if (NumProtocols) 440 memcpy(getProtocolStorage(), Protocols, 441 NumProtocols * sizeof(ObjCProtocolDecl*)); 442} 443 444const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const { 445 // There is no sugar for ObjCObjectType's, just return the canonical 446 // type pointer if it is the right class. There is no typedef information to 447 // return and these cannot be Address-space qualified. 448 if (const ObjCObjectType *T = getAs<ObjCObjectType>()) 449 if (T->getNumProtocols() && T->getInterface()) 450 return T; 451 return 0; 452} 453 454bool Type::isObjCQualifiedInterfaceType() const { 455 return getAsObjCQualifiedInterfaceType() != 0; 456} 457 458const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const { 459 // There is no sugar for ObjCQualifiedIdType's, just return the canonical 460 // type pointer if it is the right class. 461 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 462 if (OPT->isObjCQualifiedIdType()) 463 return OPT; 464 } 465 return 0; 466} 467 468const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const { 469 // There is no sugar for ObjCQualifiedClassType's, just return the canonical 470 // type pointer if it is the right class. 471 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 472 if (OPT->isObjCQualifiedClassType()) 473 return OPT; 474 } 475 return 0; 476} 477 478const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 479 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 480 if (OPT->getInterfaceType()) 481 return OPT; 482 } 483 return 0; 484} 485 486const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const { 487 if (const PointerType *PT = getAs<PointerType>()) 488 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) 489 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 490 return 0; 491} 492 493CXXRecordDecl *Type::getAsCXXRecordDecl() const { 494 if (const RecordType *RT = getAs<RecordType>()) 495 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 496 else if (const InjectedClassNameType *Injected 497 = getAs<InjectedClassNameType>()) 498 return Injected->getDecl(); 499 500 return 0; 501} 502 503namespace { 504 class GetContainedAutoVisitor : 505 public TypeVisitor<GetContainedAutoVisitor, AutoType*> { 506 public: 507 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit; 508 AutoType *Visit(QualType T) { 509 if (T.isNull()) 510 return 0; 511 return Visit(T.getTypePtr()); 512 } 513 514 // The 'auto' type itself. 515 AutoType *VisitAutoType(const AutoType *AT) { 516 return const_cast<AutoType*>(AT); 517 } 518 519 // Only these types can contain the desired 'auto' type. 520 AutoType *VisitPointerType(const PointerType *T) { 521 return Visit(T->getPointeeType()); 522 } 523 AutoType *VisitBlockPointerType(const BlockPointerType *T) { 524 return Visit(T->getPointeeType()); 525 } 526 AutoType *VisitReferenceType(const ReferenceType *T) { 527 return Visit(T->getPointeeTypeAsWritten()); 528 } 529 AutoType *VisitMemberPointerType(const MemberPointerType *T) { 530 return Visit(T->getPointeeType()); 531 } 532 AutoType *VisitArrayType(const ArrayType *T) { 533 return Visit(T->getElementType()); 534 } 535 AutoType *VisitDependentSizedExtVectorType( 536 const DependentSizedExtVectorType *T) { 537 return Visit(T->getElementType()); 538 } 539 AutoType *VisitVectorType(const VectorType *T) { 540 return Visit(T->getElementType()); 541 } 542 AutoType *VisitFunctionType(const FunctionType *T) { 543 return Visit(T->getResultType()); 544 } 545 AutoType *VisitParenType(const ParenType *T) { 546 return Visit(T->getInnerType()); 547 } 548 AutoType *VisitAttributedType(const AttributedType *T) { 549 return Visit(T->getModifiedType()); 550 } 551 }; 552} 553 554AutoType *Type::getContainedAutoType() const { 555 return GetContainedAutoVisitor().Visit(this); 556} 557 558bool Type::isIntegerType() const { 559 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 560 return BT->getKind() >= BuiltinType::Bool && 561 BT->getKind() <= BuiltinType::Int128; 562 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 563 // Incomplete enum types are not treated as integer types. 564 // FIXME: In C++, enum types are never integer types. 565 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 566 return false; 567} 568 569bool Type::hasIntegerRepresentation() const { 570 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 571 return VT->getElementType()->isIntegerType(); 572 else 573 return isIntegerType(); 574} 575 576/// \brief Determine whether this type is an integral type. 577/// 578/// This routine determines whether the given type is an integral type per 579/// C++ [basic.fundamental]p7. Although the C standard does not define the 580/// term "integral type", it has a similar term "integer type", and in C++ 581/// the two terms are equivalent. However, C's "integer type" includes 582/// enumeration types, while C++'s "integer type" does not. The \c ASTContext 583/// parameter is used to determine whether we should be following the C or 584/// C++ rules when determining whether this type is an integral/integer type. 585/// 586/// For cases where C permits "an integer type" and C++ permits "an integral 587/// type", use this routine. 588/// 589/// For cases where C permits "an integer type" and C++ permits "an integral 590/// or enumeration type", use \c isIntegralOrEnumerationType() instead. 591/// 592/// \param Ctx The context in which this type occurs. 593/// 594/// \returns true if the type is considered an integral type, false otherwise. 595bool Type::isIntegralType(ASTContext &Ctx) const { 596 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 597 return BT->getKind() >= BuiltinType::Bool && 598 BT->getKind() <= BuiltinType::Int128; 599 600 if (!Ctx.getLangOptions().CPlusPlus) 601 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 602 return ET->getDecl()->isComplete(); // Complete enum types are integral in C. 603 604 return false; 605} 606 607bool Type::isIntegralOrEnumerationType() const { 608 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 609 return BT->getKind() >= BuiltinType::Bool && 610 BT->getKind() <= BuiltinType::Int128; 611 612 // Check for a complete enum type; incomplete enum types are not properly an 613 // enumeration type in the sense required here. 614 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 615 return ET->getDecl()->isComplete(); 616 617 return false; 618} 619 620bool Type::isIntegralOrUnscopedEnumerationType() const { 621 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 622 return BT->getKind() >= BuiltinType::Bool && 623 BT->getKind() <= BuiltinType::Int128; 624 625 // Check for a complete enum type; incomplete enum types are not properly an 626 // enumeration type in the sense required here. 627 // C++0x: However, if the underlying type of the enum is fixed, it is 628 // considered complete. 629 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 630 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 631 632 return false; 633} 634 635 636bool Type::isBooleanType() const { 637 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 638 return BT->getKind() == BuiltinType::Bool; 639 return false; 640} 641 642bool Type::isCharType() const { 643 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 644 return BT->getKind() == BuiltinType::Char_U || 645 BT->getKind() == BuiltinType::UChar || 646 BT->getKind() == BuiltinType::Char_S || 647 BT->getKind() == BuiltinType::SChar; 648 return false; 649} 650 651bool Type::isWideCharType() const { 652 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 653 return BT->getKind() == BuiltinType::WChar_S || 654 BT->getKind() == BuiltinType::WChar_U; 655 return false; 656} 657 658bool Type::isChar16Type() const { 659 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 660 return BT->getKind() == BuiltinType::Char16; 661 return false; 662} 663 664bool Type::isChar32Type() const { 665 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 666 return BT->getKind() == BuiltinType::Char32; 667 return false; 668} 669 670/// \brief Determine whether this type is any of the built-in character 671/// types. 672bool Type::isAnyCharacterType() const { 673 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType); 674 if (BT == 0) return false; 675 switch (BT->getKind()) { 676 default: return false; 677 case BuiltinType::Char_U: 678 case BuiltinType::UChar: 679 case BuiltinType::WChar_U: 680 case BuiltinType::Char16: 681 case BuiltinType::Char32: 682 case BuiltinType::Char_S: 683 case BuiltinType::SChar: 684 case BuiltinType::WChar_S: 685 return true; 686 } 687} 688 689/// isSignedIntegerType - Return true if this is an integer type that is 690/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 691/// an enum decl which has a signed representation 692bool Type::isSignedIntegerType() const { 693 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 694 return BT->getKind() >= BuiltinType::Char_S && 695 BT->getKind() <= BuiltinType::Int128; 696 } 697 698 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 699 // Incomplete enum types are not treated as integer types. 700 // FIXME: In C++, enum types are never integer types. 701 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 702 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 703 } 704 705 return false; 706} 707 708bool Type::isSignedIntegerOrEnumerationType() const { 709 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 710 return BT->getKind() >= BuiltinType::Char_S && 711 BT->getKind() <= BuiltinType::Int128; 712 } 713 714 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 715 if (ET->getDecl()->isComplete()) 716 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 717 } 718 719 return false; 720} 721 722bool Type::hasSignedIntegerRepresentation() const { 723 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 724 return VT->getElementType()->isSignedIntegerType(); 725 else 726 return isSignedIntegerType(); 727} 728 729/// isUnsignedIntegerType - Return true if this is an integer type that is 730/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum 731/// decl which has an unsigned representation 732bool Type::isUnsignedIntegerType() const { 733 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 734 return BT->getKind() >= BuiltinType::Bool && 735 BT->getKind() <= BuiltinType::UInt128; 736 } 737 738 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 739 // Incomplete enum types are not treated as integer types. 740 // FIXME: In C++, enum types are never integer types. 741 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 742 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 743 } 744 745 return false; 746} 747 748bool Type::isUnsignedIntegerOrEnumerationType() const { 749 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 750 return BT->getKind() >= BuiltinType::Bool && 751 BT->getKind() <= BuiltinType::UInt128; 752 } 753 754 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 755 if (ET->getDecl()->isComplete()) 756 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 757 } 758 759 return false; 760} 761 762bool Type::hasUnsignedIntegerRepresentation() const { 763 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 764 return VT->getElementType()->isUnsignedIntegerType(); 765 else 766 return isUnsignedIntegerType(); 767} 768 769bool Type::isFloatingType() const { 770 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 771 return BT->getKind() >= BuiltinType::Float && 772 BT->getKind() <= BuiltinType::LongDouble; 773 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 774 return CT->getElementType()->isFloatingType(); 775 return false; 776} 777 778bool Type::hasFloatingRepresentation() const { 779 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 780 return VT->getElementType()->isFloatingType(); 781 else 782 return isFloatingType(); 783} 784 785bool Type::isRealFloatingType() const { 786 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 787 return BT->isFloatingPoint(); 788 return false; 789} 790 791bool Type::isRealType() const { 792 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 793 return BT->getKind() >= BuiltinType::Bool && 794 BT->getKind() <= BuiltinType::LongDouble; 795 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 796 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 797 return false; 798} 799 800bool Type::isArithmeticType() const { 801 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 802 return BT->getKind() >= BuiltinType::Bool && 803 BT->getKind() <= BuiltinType::LongDouble; 804 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 805 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). 806 // If a body isn't seen by the time we get here, return false. 807 // 808 // C++0x: Enumerations are not arithmetic types. For now, just return 809 // false for scoped enumerations since that will disable any 810 // unwanted implicit conversions. 811 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete(); 812 return isa<ComplexType>(CanonicalType); 813} 814 815bool Type::isScalarType() const { 816 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 817 return BT->getKind() > BuiltinType::Void && 818 BT->getKind() <= BuiltinType::NullPtr; 819 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 820 // Enums are scalar types, but only if they are defined. Incomplete enums 821 // are not treated as scalar types. 822 return ET->getDecl()->isComplete(); 823 return isa<PointerType>(CanonicalType) || 824 isa<BlockPointerType>(CanonicalType) || 825 isa<MemberPointerType>(CanonicalType) || 826 isa<ComplexType>(CanonicalType) || 827 isa<ObjCObjectPointerType>(CanonicalType); 828} 829 830Type::ScalarTypeKind Type::getScalarTypeKind() const { 831 assert(isScalarType()); 832 833 const Type *T = CanonicalType.getTypePtr(); 834 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) { 835 if (BT->getKind() == BuiltinType::Bool) return STK_Bool; 836 if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer; 837 if (BT->isInteger()) return STK_Integral; 838 if (BT->isFloatingPoint()) return STK_Floating; 839 llvm_unreachable("unknown scalar builtin type"); 840 } else if (isa<PointerType>(T) || 841 isa<BlockPointerType>(T) || 842 isa<ObjCObjectPointerType>(T)) { 843 return STK_Pointer; 844 } else if (isa<MemberPointerType>(T)) { 845 return STK_MemberPointer; 846 } else if (isa<EnumType>(T)) { 847 assert(cast<EnumType>(T)->getDecl()->isComplete()); 848 return STK_Integral; 849 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) { 850 if (CT->getElementType()->isRealFloatingType()) 851 return STK_FloatingComplex; 852 return STK_IntegralComplex; 853 } 854 855 llvm_unreachable("unknown scalar type"); 856 return STK_Pointer; 857} 858 859/// \brief Determines whether the type is a C++ aggregate type or C 860/// aggregate or union type. 861/// 862/// An aggregate type is an array or a class type (struct, union, or 863/// class) that has no user-declared constructors, no private or 864/// protected non-static data members, no base classes, and no virtual 865/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type 866/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also 867/// includes union types. 868bool Type::isAggregateType() const { 869 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) { 870 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) 871 return ClassDecl->isAggregate(); 872 873 return true; 874 } 875 876 return isa<ArrayType>(CanonicalType); 877} 878 879/// isConstantSizeType - Return true if this is not a variable sized type, 880/// according to the rules of C99 6.7.5p3. It is not legal to call this on 881/// incomplete types or dependent types. 882bool Type::isConstantSizeType() const { 883 assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); 884 assert(!isDependentType() && "This doesn't make sense for dependent types"); 885 // The VAT must have a size, as it is known to be complete. 886 return !isa<VariableArrayType>(CanonicalType); 887} 888 889/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) 890/// - a type that can describe objects, but which lacks information needed to 891/// determine its size. 892bool Type::isIncompleteType() const { 893 switch (CanonicalType->getTypeClass()) { 894 default: return false; 895 case Builtin: 896 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never 897 // be completed. 898 return isVoidType(); 899 case Enum: 900 // An enumeration with fixed underlying type is complete (C++0x 7.2p3). 901 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed()) 902 return false; 903 // Fall through. 904 case Record: 905 // A tagged type (struct/union/enum/class) is incomplete if the decl is a 906 // forward declaration, but not a full definition (C99 6.2.5p22). 907 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition(); 908 case ConstantArray: 909 // An array is incomplete if its element type is incomplete 910 // (C++ [dcl.array]p1). 911 // We don't handle variable arrays (they're not allowed in C++) or 912 // dependent-sized arrays (dependent types are never treated as incomplete). 913 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType(); 914 case IncompleteArray: 915 // An array of unknown size is an incomplete type (C99 6.2.5p22). 916 return true; 917 case ObjCObject: 918 return cast<ObjCObjectType>(CanonicalType)->getBaseType() 919 ->isIncompleteType(); 920 case ObjCInterface: 921 // ObjC interfaces are incomplete if they are @class, not @interface. 922 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl(); 923 } 924} 925 926bool QualType::isPODType(ASTContext &Context) const { 927 // The compiler shouldn't query this for incomplete types, but the user might. 928 // We return false for that case. Except for incomplete arrays of PODs, which 929 // are PODs according to the standard. 930 if (isNull()) 931 return 0; 932 933 if ((*this)->isIncompleteArrayType()) 934 return Context.getBaseElementType(*this).isPODType(Context); 935 936 if ((*this)->isIncompleteType()) 937 return false; 938 939 if (Context.getLangOptions().ObjCAutoRefCount) { 940 switch (getObjCLifetime()) { 941 case Qualifiers::OCL_ExplicitNone: 942 return true; 943 944 case Qualifiers::OCL_Strong: 945 case Qualifiers::OCL_Weak: 946 case Qualifiers::OCL_Autoreleasing: 947 return false; 948 949 case Qualifiers::OCL_None: 950 break; 951 } 952 } 953 954 QualType CanonicalType = getTypePtr()->CanonicalType; 955 switch (CanonicalType->getTypeClass()) { 956 // Everything not explicitly mentioned is not POD. 957 default: return false; 958 case Type::VariableArray: 959 case Type::ConstantArray: 960 // IncompleteArray is handled above. 961 return Context.getBaseElementType(*this).isPODType(Context); 962 963 case Type::ObjCObjectPointer: 964 case Type::BlockPointer: 965 case Type::Builtin: 966 case Type::Complex: 967 case Type::Pointer: 968 case Type::MemberPointer: 969 case Type::Vector: 970 case Type::ExtVector: 971 return true; 972 973 case Type::Enum: 974 return true; 975 976 case Type::Record: 977 if (CXXRecordDecl *ClassDecl 978 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 979 return ClassDecl->isPOD(); 980 981 // C struct/union is POD. 982 return true; 983 } 984} 985 986bool QualType::isTrivialType(ASTContext &Context) const { 987 // The compiler shouldn't query this for incomplete types, but the user might. 988 // We return false for that case. Except for incomplete arrays of PODs, which 989 // are PODs according to the standard. 990 if (isNull()) 991 return 0; 992 993 if ((*this)->isArrayType()) 994 return Context.getBaseElementType(*this).isTrivialType(Context); 995 996 // Return false for incomplete types after skipping any incomplete array 997 // types which are expressly allowed by the standard and thus our API. 998 if ((*this)->isIncompleteType()) 999 return false; 1000 1001 if (Context.getLangOptions().ObjCAutoRefCount) { 1002 switch (getObjCLifetime()) { 1003 case Qualifiers::OCL_ExplicitNone: 1004 return true; 1005 1006 case Qualifiers::OCL_Strong: 1007 case Qualifiers::OCL_Weak: 1008 case Qualifiers::OCL_Autoreleasing: 1009 return false; 1010 1011 case Qualifiers::OCL_None: 1012 if ((*this)->isObjCLifetimeType()) 1013 return false; 1014 break; 1015 } 1016 } 1017 1018 QualType CanonicalType = getTypePtr()->CanonicalType; 1019 if (CanonicalType->isDependentType()) 1020 return false; 1021 1022 // C++0x [basic.types]p9: 1023 // Scalar types, trivial class types, arrays of such types, and 1024 // cv-qualified versions of these types are collectively called trivial 1025 // types. 1026 1027 // As an extension, Clang treats vector types as Scalar types. 1028 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 1029 return true; 1030 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) { 1031 if (const CXXRecordDecl *ClassDecl = 1032 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1033 // C++0x [class]p5: 1034 // A trivial class is a class that has a trivial default constructor 1035 if (!ClassDecl->hasTrivialDefaultConstructor()) return false; 1036 // and is trivially copyable. 1037 if (!ClassDecl->isTriviallyCopyable()) return false; 1038 } 1039 1040 return true; 1041 } 1042 1043 // No other types can match. 1044 return false; 1045} 1046 1047bool QualType::isTriviallyCopyableType(ASTContext &Context) const { 1048 if ((*this)->isArrayType()) 1049 return Context.getBaseElementType(*this).isTrivialType(Context); 1050 1051 if (Context.getLangOptions().ObjCAutoRefCount) { 1052 switch (getObjCLifetime()) { 1053 case Qualifiers::OCL_ExplicitNone: 1054 return true; 1055 1056 case Qualifiers::OCL_Strong: 1057 case Qualifiers::OCL_Weak: 1058 case Qualifiers::OCL_Autoreleasing: 1059 return false; 1060 1061 case Qualifiers::OCL_None: 1062 if ((*this)->isObjCLifetimeType()) 1063 return false; 1064 break; 1065 } 1066 } 1067 1068 // C++0x [basic.types]p9 1069 // Scalar types, trivially copyable class types, arrays of such types, and 1070 // cv-qualified versions of these types are collectively called trivial 1071 // types. 1072 1073 QualType CanonicalType = getCanonicalType(); 1074 if (CanonicalType->isDependentType()) 1075 return false; 1076 1077 // Return false for incomplete types after skipping any incomplete array types 1078 // which are expressly allowed by the standard and thus our API. 1079 if (CanonicalType->isIncompleteType()) 1080 return false; 1081 1082 // As an extension, Clang treats vector types as Scalar types. 1083 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 1084 return true; 1085 1086 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) { 1087 if (const CXXRecordDecl *ClassDecl = 1088 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1089 if (!ClassDecl->isTriviallyCopyable()) return false; 1090 } 1091 1092 return true; 1093 } 1094 1095 // No other types can match. 1096 return false; 1097} 1098 1099 1100 1101bool Type::isLiteralType() const { 1102 if (isDependentType()) 1103 return false; 1104 1105 // C++0x [basic.types]p10: 1106 // A type is a literal type if it is: 1107 // [...] 1108 // -- an array of literal type 1109 // Extension: variable arrays cannot be literal types, since they're 1110 // runtime-sized. 1111 if (isVariableArrayType()) 1112 return false; 1113 const Type *BaseTy = getBaseElementTypeUnsafe(); 1114 assert(BaseTy && "NULL element type"); 1115 1116 // Return false for incomplete types after skipping any incomplete array 1117 // types; those are expressly allowed by the standard and thus our API. 1118 if (BaseTy->isIncompleteType()) 1119 return false; 1120 1121 // Objective-C lifetime types are not literal types. 1122 if (BaseTy->isObjCRetainableType()) 1123 return false; 1124 1125 // C++0x [basic.types]p10: 1126 // A type is a literal type if it is: 1127 // -- a scalar type; or 1128 // As an extension, Clang treats vector types as Scalar types. 1129 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 1130 // -- a reference type; or 1131 if (BaseTy->isReferenceType()) return true; 1132 // -- a class type that has all of the following properties: 1133 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 1134 if (const CXXRecordDecl *ClassDecl = 1135 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1136 // -- a trivial destructor, 1137 if (!ClassDecl->hasTrivialDestructor()) return false; 1138 // -- every constructor call and full-expression in the 1139 // brace-or-equal-initializers for non-static data members (if any) 1140 // is a constant expression, 1141 // FIXME: C++0x: Clang doesn't yet support non-static data member 1142 // declarations with initializers, or constexprs. 1143 // -- it is an aggregate type or has at least one constexpr 1144 // constructor or constructor template that is not a copy or move 1145 // constructor, and 1146 if (!ClassDecl->isAggregate() && 1147 !ClassDecl->hasConstExprNonCopyMoveConstructor()) 1148 return false; 1149 // -- all non-static data members and base classes of literal types 1150 if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false; 1151 } 1152 1153 return true; 1154 } 1155 return false; 1156} 1157 1158bool Type::isStandardLayoutType() const { 1159 if (isDependentType()) 1160 return false; 1161 1162 // C++0x [basic.types]p9: 1163 // Scalar types, standard-layout class types, arrays of such types, and 1164 // cv-qualified versions of these types are collectively called 1165 // standard-layout types. 1166 const Type *BaseTy = getBaseElementTypeUnsafe(); 1167 assert(BaseTy && "NULL element type"); 1168 1169 // Return false for incomplete types after skipping any incomplete array 1170 // types which are expressly allowed by the standard and thus our API. 1171 if (BaseTy->isIncompleteType()) 1172 return false; 1173 1174 // As an extension, Clang treats vector types as Scalar types. 1175 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 1176 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 1177 if (const CXXRecordDecl *ClassDecl = 1178 dyn_cast<CXXRecordDecl>(RT->getDecl())) 1179 if (!ClassDecl->isStandardLayout()) 1180 return false; 1181 1182 // Default to 'true' for non-C++ class types. 1183 // FIXME: This is a bit dubious, but plain C structs should trivially meet 1184 // all the requirements of standard layout classes. 1185 return true; 1186 } 1187 1188 // No other types can match. 1189 return false; 1190} 1191 1192// This is effectively the intersection of isTrivialType and 1193// isStandardLayoutType. We implement it dircetly to avoid redundant 1194// conversions from a type to a CXXRecordDecl. 1195bool QualType::isCXX11PODType(ASTContext &Context) const { 1196 const Type *ty = getTypePtr(); 1197 if (ty->isDependentType()) 1198 return false; 1199 1200 if (Context.getLangOptions().ObjCAutoRefCount) { 1201 switch (getObjCLifetime()) { 1202 case Qualifiers::OCL_ExplicitNone: 1203 return true; 1204 1205 case Qualifiers::OCL_Strong: 1206 case Qualifiers::OCL_Weak: 1207 case Qualifiers::OCL_Autoreleasing: 1208 return false; 1209 1210 case Qualifiers::OCL_None: 1211 if (ty->isObjCLifetimeType()) 1212 return false; 1213 break; 1214 } 1215 } 1216 1217 // C++11 [basic.types]p9: 1218 // Scalar types, POD classes, arrays of such types, and cv-qualified 1219 // versions of these types are collectively called trivial types. 1220 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 1221 assert(BaseTy && "NULL element type"); 1222 1223 // Return false for incomplete types after skipping any incomplete array 1224 // types which are expressly allowed by the standard and thus our API. 1225 if (BaseTy->isIncompleteType()) 1226 return false; 1227 1228 // As an extension, Clang treats vector types as Scalar types. 1229 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 1230 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 1231 if (const CXXRecordDecl *ClassDecl = 1232 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 1233 // C++11 [class]p10: 1234 // A POD struct is a non-union class that is both a trivial class [...] 1235 if (!ClassDecl->isTrivial()) return false; 1236 1237 // C++11 [class]p10: 1238 // A POD struct is a non-union class that is both a trivial class and 1239 // a standard-layout class [...] 1240 if (!ClassDecl->isStandardLayout()) return false; 1241 1242 // C++11 [class]p10: 1243 // A POD struct is a non-union class that is both a trivial class and 1244 // a standard-layout class, and has no non-static data members of type 1245 // non-POD struct, non-POD union (or array of such types). [...] 1246 // 1247 // We don't directly query the recursive aspect as the requiremets for 1248 // both standard-layout classes and trivial classes apply recursively 1249 // already. 1250 } 1251 1252 return true; 1253 } 1254 1255 // No other types can match. 1256 return false; 1257} 1258 1259bool Type::isPromotableIntegerType() const { 1260 if (const BuiltinType *BT = getAs<BuiltinType>()) 1261 switch (BT->getKind()) { 1262 case BuiltinType::Bool: 1263 case BuiltinType::Char_S: 1264 case BuiltinType::Char_U: 1265 case BuiltinType::SChar: 1266 case BuiltinType::UChar: 1267 case BuiltinType::Short: 1268 case BuiltinType::UShort: 1269 return true; 1270 default: 1271 return false; 1272 } 1273 1274 // Enumerated types are promotable to their compatible integer types 1275 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 1276 if (const EnumType *ET = getAs<EnumType>()){ 1277 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 1278 || ET->getDecl()->isScoped()) 1279 return false; 1280 1281 const BuiltinType *BT 1282 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>(); 1283 return BT->getKind() == BuiltinType::Int 1284 || BT->getKind() == BuiltinType::UInt; 1285 } 1286 1287 return false; 1288} 1289 1290bool Type::isNullPtrType() const { 1291 if (const BuiltinType *BT = getAs<BuiltinType>()) 1292 return BT->getKind() == BuiltinType::NullPtr; 1293 return false; 1294} 1295 1296bool Type::isSpecifierType() const { 1297 // Note that this intentionally does not use the canonical type. 1298 switch (getTypeClass()) { 1299 case Builtin: 1300 case Record: 1301 case Enum: 1302 case Typedef: 1303 case Complex: 1304 case TypeOfExpr: 1305 case TypeOf: 1306 case TemplateTypeParm: 1307 case SubstTemplateTypeParm: 1308 case TemplateSpecialization: 1309 case Elaborated: 1310 case DependentName: 1311 case DependentTemplateSpecialization: 1312 case ObjCInterface: 1313 case ObjCObject: 1314 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 1315 return true; 1316 default: 1317 return false; 1318 } 1319} 1320 1321ElaboratedTypeKeyword 1322TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 1323 switch (TypeSpec) { 1324 default: return ETK_None; 1325 case TST_typename: return ETK_Typename; 1326 case TST_class: return ETK_Class; 1327 case TST_struct: return ETK_Struct; 1328 case TST_union: return ETK_Union; 1329 case TST_enum: return ETK_Enum; 1330 } 1331} 1332 1333TagTypeKind 1334TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 1335 switch(TypeSpec) { 1336 case TST_class: return TTK_Class; 1337 case TST_struct: return TTK_Struct; 1338 case TST_union: return TTK_Union; 1339 case TST_enum: return TTK_Enum; 1340 } 1341 1342 llvm_unreachable("Type specifier is not a tag type kind."); 1343 return TTK_Union; 1344} 1345 1346ElaboratedTypeKeyword 1347TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 1348 switch (Kind) { 1349 case TTK_Class: return ETK_Class; 1350 case TTK_Struct: return ETK_Struct; 1351 case TTK_Union: return ETK_Union; 1352 case TTK_Enum: return ETK_Enum; 1353 } 1354 llvm_unreachable("Unknown tag type kind."); 1355} 1356 1357TagTypeKind 1358TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 1359 switch (Keyword) { 1360 case ETK_Class: return TTK_Class; 1361 case ETK_Struct: return TTK_Struct; 1362 case ETK_Union: return TTK_Union; 1363 case ETK_Enum: return TTK_Enum; 1364 case ETK_None: // Fall through. 1365 case ETK_Typename: 1366 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 1367 } 1368 llvm_unreachable("Unknown elaborated type keyword."); 1369} 1370 1371bool 1372TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 1373 switch (Keyword) { 1374 case ETK_None: 1375 case ETK_Typename: 1376 return false; 1377 case ETK_Class: 1378 case ETK_Struct: 1379 case ETK_Union: 1380 case ETK_Enum: 1381 return true; 1382 } 1383 llvm_unreachable("Unknown elaborated type keyword."); 1384} 1385 1386const char* 1387TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 1388 switch (Keyword) { 1389 case ETK_None: return ""; 1390 case ETK_Typename: return "typename"; 1391 case ETK_Class: return "class"; 1392 case ETK_Struct: return "struct"; 1393 case ETK_Union: return "union"; 1394 case ETK_Enum: return "enum"; 1395 } 1396 1397 llvm_unreachable("Unknown elaborated type keyword."); 1398 return ""; 1399} 1400 1401DependentTemplateSpecializationType::DependentTemplateSpecializationType( 1402 ElaboratedTypeKeyword Keyword, 1403 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 1404 unsigned NumArgs, const TemplateArgument *Args, 1405 QualType Canon) 1406 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true, 1407 /*VariablyModified=*/false, 1408 NNS && NNS->containsUnexpandedParameterPack()), 1409 NNS(NNS), Name(Name), NumArgs(NumArgs) { 1410 assert((!NNS || NNS->isDependent()) && 1411 "DependentTemplateSpecializatonType requires dependent qualifier"); 1412 for (unsigned I = 0; I != NumArgs; ++I) { 1413 if (Args[I].containsUnexpandedParameterPack()) 1414 setContainsUnexpandedParameterPack(); 1415 1416 new (&getArgBuffer()[I]) TemplateArgument(Args[I]); 1417 } 1418} 1419 1420void 1421DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1422 const ASTContext &Context, 1423 ElaboratedTypeKeyword Keyword, 1424 NestedNameSpecifier *Qualifier, 1425 const IdentifierInfo *Name, 1426 unsigned NumArgs, 1427 const TemplateArgument *Args) { 1428 ID.AddInteger(Keyword); 1429 ID.AddPointer(Qualifier); 1430 ID.AddPointer(Name); 1431 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1432 Args[Idx].Profile(ID, Context); 1433} 1434 1435bool Type::isElaboratedTypeSpecifier() const { 1436 ElaboratedTypeKeyword Keyword; 1437 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this)) 1438 Keyword = Elab->getKeyword(); 1439 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this)) 1440 Keyword = DepName->getKeyword(); 1441 else if (const DependentTemplateSpecializationType *DepTST = 1442 dyn_cast<DependentTemplateSpecializationType>(this)) 1443 Keyword = DepTST->getKeyword(); 1444 else 1445 return false; 1446 1447 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 1448} 1449 1450const char *Type::getTypeClassName() const { 1451 switch (TypeBits.TC) { 1452#define ABSTRACT_TYPE(Derived, Base) 1453#define TYPE(Derived, Base) case Derived: return #Derived; 1454#include "clang/AST/TypeNodes.def" 1455 } 1456 1457 llvm_unreachable("Invalid type class."); 1458 return 0; 1459} 1460 1461const char *BuiltinType::getName(const LangOptions &LO) const { 1462 switch (getKind()) { 1463 case Void: return "void"; 1464 case Bool: return LO.Bool ? "bool" : "_Bool"; 1465 case Char_S: return "char"; 1466 case Char_U: return "char"; 1467 case SChar: return "signed char"; 1468 case Short: return "short"; 1469 case Int: return "int"; 1470 case Long: return "long"; 1471 case LongLong: return "long long"; 1472 case Int128: return "__int128_t"; 1473 case UChar: return "unsigned char"; 1474 case UShort: return "unsigned short"; 1475 case UInt: return "unsigned int"; 1476 case ULong: return "unsigned long"; 1477 case ULongLong: return "unsigned long long"; 1478 case UInt128: return "__uint128_t"; 1479 case Float: return "float"; 1480 case Double: return "double"; 1481 case LongDouble: return "long double"; 1482 case WChar_S: 1483 case WChar_U: return "wchar_t"; 1484 case Char16: return "char16_t"; 1485 case Char32: return "char32_t"; 1486 case NullPtr: return "nullptr_t"; 1487 case Overload: return "<overloaded function type>"; 1488 case BoundMember: return "<bound member function type>"; 1489 case Dependent: return "<dependent type>"; 1490 case UnknownAny: return "<unknown type>"; 1491 case ObjCId: return "id"; 1492 case ObjCClass: return "Class"; 1493 case ObjCSel: return "SEL"; 1494 } 1495 1496 llvm_unreachable("Invalid builtin type."); 1497 return 0; 1498} 1499 1500QualType QualType::getNonLValueExprType(ASTContext &Context) const { 1501 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>()) 1502 return RefType->getPointeeType(); 1503 1504 // C++0x [basic.lval]: 1505 // Class prvalues can have cv-qualified types; non-class prvalues always 1506 // have cv-unqualified types. 1507 // 1508 // See also C99 6.3.2.1p2. 1509 if (!Context.getLangOptions().CPlusPlus || 1510 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 1511 return getUnqualifiedType(); 1512 1513 return *this; 1514} 1515 1516StringRef FunctionType::getNameForCallConv(CallingConv CC) { 1517 switch (CC) { 1518 case CC_Default: 1519 llvm_unreachable("no name for default cc"); 1520 return ""; 1521 1522 case CC_C: return "cdecl"; 1523 case CC_X86StdCall: return "stdcall"; 1524 case CC_X86FastCall: return "fastcall"; 1525 case CC_X86ThisCall: return "thiscall"; 1526 case CC_X86Pascal: return "pascal"; 1527 case CC_AAPCS: return "aapcs"; 1528 case CC_AAPCS_VFP: return "aapcs-vfp"; 1529 } 1530 1531 llvm_unreachable("Invalid calling convention."); 1532 return ""; 1533} 1534 1535FunctionProtoType::FunctionProtoType(QualType result, const QualType *args, 1536 unsigned numArgs, QualType canonical, 1537 const ExtProtoInfo &epi) 1538 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals, 1539 epi.RefQualifier, canonical, 1540 result->isDependentType(), 1541 result->isInstantiationDependentType(), 1542 result->isVariablyModifiedType(), 1543 result->containsUnexpandedParameterPack(), 1544 epi.ExtInfo), 1545 NumArgs(numArgs), NumExceptions(epi.NumExceptions), 1546 ExceptionSpecType(epi.ExceptionSpecType), 1547 HasAnyConsumedArgs(epi.ConsumedArguments != 0) 1548{ 1549 // Fill in the trailing argument array. 1550 QualType *argSlot = reinterpret_cast<QualType*>(this+1); 1551 for (unsigned i = 0; i != numArgs; ++i) { 1552 if (args[i]->isDependentType()) 1553 setDependent(); 1554 else if (args[i]->isInstantiationDependentType()) 1555 setInstantiationDependent(); 1556 1557 if (args[i]->containsUnexpandedParameterPack()) 1558 setContainsUnexpandedParameterPack(); 1559 1560 argSlot[i] = args[i]; 1561 } 1562 1563 if (getExceptionSpecType() == EST_Dynamic) { 1564 // Fill in the exception array. 1565 QualType *exnSlot = argSlot + numArgs; 1566 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) { 1567 if (epi.Exceptions[i]->isDependentType()) 1568 setDependent(); 1569 else if (epi.Exceptions[i]->isInstantiationDependentType()) 1570 setInstantiationDependent(); 1571 1572 if (epi.Exceptions[i]->containsUnexpandedParameterPack()) 1573 setContainsUnexpandedParameterPack(); 1574 1575 exnSlot[i] = epi.Exceptions[i]; 1576 } 1577 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 1578 // Store the noexcept expression and context. 1579 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs); 1580 *noexSlot = epi.NoexceptExpr; 1581 1582 if (epi.NoexceptExpr) { 1583 if (epi.NoexceptExpr->isValueDependent() 1584 || epi.NoexceptExpr->isTypeDependent()) 1585 setDependent(); 1586 else if (epi.NoexceptExpr->isInstantiationDependent()) 1587 setInstantiationDependent(); 1588 } 1589 } 1590 1591 if (epi.ConsumedArguments) { 1592 bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer()); 1593 for (unsigned i = 0; i != numArgs; ++i) 1594 consumedArgs[i] = epi.ConsumedArguments[i]; 1595 } 1596} 1597 1598FunctionProtoType::NoexceptResult 1599FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const { 1600 ExceptionSpecificationType est = getExceptionSpecType(); 1601 if (est == EST_BasicNoexcept) 1602 return NR_Nothrow; 1603 1604 if (est != EST_ComputedNoexcept) 1605 return NR_NoNoexcept; 1606 1607 Expr *noexceptExpr = getNoexceptExpr(); 1608 if (!noexceptExpr) 1609 return NR_BadNoexcept; 1610 if (noexceptExpr->isValueDependent()) 1611 return NR_Dependent; 1612 1613 llvm::APSInt value; 1614 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0, 1615 /*evaluated*/false); 1616 (void)isICE; 1617 assert(isICE && "AST should not contain bad noexcept expressions."); 1618 1619 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 1620} 1621 1622bool FunctionProtoType::isTemplateVariadic() const { 1623 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx) 1624 if (isa<PackExpansionType>(getArgType(ArgIdx - 1))) 1625 return true; 1626 1627 return false; 1628} 1629 1630void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 1631 const QualType *ArgTys, unsigned NumArgs, 1632 const ExtProtoInfo &epi, 1633 const ASTContext &Context) { 1634 1635 // We have to be careful not to get ambiguous profile encodings. 1636 // Note that valid type pointers are never ambiguous with anything else. 1637 // 1638 // The encoding grammar begins: 1639 // type type* bool int bool 1640 // If that final bool is true, then there is a section for the EH spec: 1641 // bool type* 1642 // This is followed by an optional "consumed argument" section of the 1643 // same length as the first type sequence: 1644 // bool* 1645 // Finally, we have the ext info: 1646 // int 1647 // 1648 // There is no ambiguity between the consumed arguments and an empty EH 1649 // spec because of the leading 'bool' which unambiguously indicates 1650 // whether the following bool is the EH spec or part of the arguments. 1651 1652 ID.AddPointer(Result.getAsOpaquePtr()); 1653 for (unsigned i = 0; i != NumArgs; ++i) 1654 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 1655 // This method is relatively performance sensitive, so as a performance 1656 // shortcut, use one AddInteger call instead of four for the next four 1657 // fields. 1658 assert(!(unsigned(epi.Variadic) & ~1) && 1659 !(unsigned(epi.TypeQuals) & ~255) && 1660 !(unsigned(epi.RefQualifier) & ~3) && 1661 !(unsigned(epi.ExceptionSpecType) & ~7) && 1662 "Values larger than expected."); 1663 ID.AddInteger(unsigned(epi.Variadic) + 1664 (epi.TypeQuals << 1) + 1665 (epi.RefQualifier << 9) + 1666 (epi.ExceptionSpecType << 11)); 1667 if (epi.ExceptionSpecType == EST_Dynamic) { 1668 for (unsigned i = 0; i != epi.NumExceptions; ++i) 1669 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr()); 1670 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){ 1671 epi.NoexceptExpr->Profile(ID, Context, false); 1672 } 1673 if (epi.ConsumedArguments) { 1674 for (unsigned i = 0; i != NumArgs; ++i) 1675 ID.AddBoolean(epi.ConsumedArguments[i]); 1676 } 1677 epi.ExtInfo.Profile(ID); 1678} 1679 1680void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 1681 const ASTContext &Ctx) { 1682 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(), 1683 Ctx); 1684} 1685 1686QualType TypedefType::desugar() const { 1687 return getDecl()->getUnderlyingType(); 1688} 1689 1690TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 1691 : Type(TypeOfExpr, can, E->isTypeDependent(), 1692 E->isInstantiationDependent(), 1693 E->getType()->isVariablyModifiedType(), 1694 E->containsUnexpandedParameterPack()), 1695 TOExpr(E) { 1696} 1697 1698bool TypeOfExprType::isSugared() const { 1699 return !TOExpr->isTypeDependent(); 1700} 1701 1702QualType TypeOfExprType::desugar() const { 1703 if (isSugared()) 1704 return getUnderlyingExpr()->getType(); 1705 1706 return QualType(this, 0); 1707} 1708 1709void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 1710 const ASTContext &Context, Expr *E) { 1711 E->Profile(ID, Context, true); 1712} 1713 1714DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 1715 : Type(Decltype, can, E->isTypeDependent(), 1716 E->isInstantiationDependent(), 1717 E->getType()->isVariablyModifiedType(), 1718 E->containsUnexpandedParameterPack()), 1719 E(E), 1720 UnderlyingType(underlyingType) { 1721} 1722 1723bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 1724 1725QualType DecltypeType::desugar() const { 1726 if (isSugared()) 1727 return getUnderlyingType(); 1728 1729 return QualType(this, 0); 1730} 1731 1732DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 1733 : DecltypeType(E, Context.DependentTy), Context(Context) { } 1734 1735void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 1736 const ASTContext &Context, Expr *E) { 1737 E->Profile(ID, Context, true); 1738} 1739 1740TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 1741 : Type(TC, can, D->isDependentType(), 1742 /*InstantiationDependent=*/D->isDependentType(), 1743 /*VariablyModified=*/false, 1744 /*ContainsUnexpandedParameterPack=*/false), 1745 decl(const_cast<TagDecl*>(D)) {} 1746 1747static TagDecl *getInterestingTagDecl(TagDecl *decl) { 1748 for (TagDecl::redecl_iterator I = decl->redecls_begin(), 1749 E = decl->redecls_end(); 1750 I != E; ++I) { 1751 if (I->isDefinition() || I->isBeingDefined()) 1752 return *I; 1753 } 1754 // If there's no definition (not even in progress), return what we have. 1755 return decl; 1756} 1757 1758UnaryTransformType::UnaryTransformType(QualType BaseType, 1759 QualType UnderlyingType, 1760 UTTKind UKind, 1761 QualType CanonicalType) 1762 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(), 1763 UnderlyingType->isInstantiationDependentType(), 1764 UnderlyingType->isVariablyModifiedType(), 1765 BaseType->containsUnexpandedParameterPack()) 1766 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) 1767{} 1768 1769TagDecl *TagType::getDecl() const { 1770 return getInterestingTagDecl(decl); 1771} 1772 1773bool TagType::isBeingDefined() const { 1774 return getDecl()->isBeingDefined(); 1775} 1776 1777CXXRecordDecl *InjectedClassNameType::getDecl() const { 1778 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 1779} 1780 1781bool RecordType::classof(const TagType *TT) { 1782 return isa<RecordDecl>(TT->getDecl()); 1783} 1784 1785bool EnumType::classof(const TagType *TT) { 1786 return isa<EnumDecl>(TT->getDecl()); 1787} 1788 1789IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 1790 return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier(); 1791} 1792 1793SubstTemplateTypeParmPackType:: 1794SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 1795 QualType Canon, 1796 const TemplateArgument &ArgPack) 1797 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 1798 Replaced(Param), 1799 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 1800{ 1801} 1802 1803TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 1804 return TemplateArgument(Arguments, NumArguments); 1805} 1806 1807void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 1808 Profile(ID, getReplacedParameter(), getArgumentPack()); 1809} 1810 1811void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 1812 const TemplateTypeParmType *Replaced, 1813 const TemplateArgument &ArgPack) { 1814 ID.AddPointer(Replaced); 1815 ID.AddInteger(ArgPack.pack_size()); 1816 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 1817 PEnd = ArgPack.pack_end(); 1818 P != PEnd; ++P) 1819 ID.AddPointer(P->getAsType().getAsOpaquePtr()); 1820} 1821 1822bool TemplateSpecializationType:: 1823anyDependentTemplateArguments(const TemplateArgumentListInfo &Args, 1824 bool &InstantiationDependent) { 1825 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(), 1826 InstantiationDependent); 1827} 1828 1829bool TemplateSpecializationType:: 1830anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N, 1831 bool &InstantiationDependent) { 1832 for (unsigned i = 0; i != N; ++i) { 1833 if (Args[i].getArgument().isDependent()) { 1834 InstantiationDependent = true; 1835 return true; 1836 } 1837 1838 if (Args[i].getArgument().isInstantiationDependent()) 1839 InstantiationDependent = true; 1840 } 1841 return false; 1842} 1843 1844bool TemplateSpecializationType:: 1845anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N, 1846 bool &InstantiationDependent) { 1847 for (unsigned i = 0; i != N; ++i) { 1848 if (Args[i].isDependent()) { 1849 InstantiationDependent = true; 1850 return true; 1851 } 1852 1853 if (Args[i].isInstantiationDependent()) 1854 InstantiationDependent = true; 1855 } 1856 return false; 1857} 1858 1859TemplateSpecializationType:: 1860TemplateSpecializationType(TemplateName T, 1861 const TemplateArgument *Args, unsigned NumArgs, 1862 QualType Canon, QualType AliasedType) 1863 : Type(TemplateSpecialization, 1864 Canon.isNull()? QualType(this, 0) : Canon, 1865 Canon.isNull()? T.isDependent() : Canon->isDependentType(), 1866 Canon.isNull()? T.isDependent() 1867 : Canon->isInstantiationDependentType(), 1868 false, T.containsUnexpandedParameterPack()), 1869 Template(T), NumArgs(NumArgs) { 1870 assert(!T.getAsDependentTemplateName() && 1871 "Use DependentTemplateSpecializationType for dependent template-name"); 1872 assert((T.getKind() == TemplateName::Template || 1873 T.getKind() == TemplateName::SubstTemplateTemplateParm || 1874 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 1875 "Unexpected template name for TemplateSpecializationType"); 1876 bool InstantiationDependent; 1877 (void)InstantiationDependent; 1878 assert((!Canon.isNull() || 1879 T.isDependent() || 1880 anyDependentTemplateArguments(Args, NumArgs, 1881 InstantiationDependent)) && 1882 "No canonical type for non-dependent class template specialization"); 1883 1884 TemplateArgument *TemplateArgs 1885 = reinterpret_cast<TemplateArgument *>(this + 1); 1886 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { 1887 // Update dependent and variably-modified bits. 1888 // If the canonical type exists and is non-dependent, the template 1889 // specialization type can be non-dependent even if one of the type 1890 // arguments is. Given: 1891 // template<typename T> using U = int; 1892 // U<T> is always non-dependent, irrespective of the type T. 1893 if (Canon.isNull() && Args[Arg].isDependent()) 1894 setDependent(); 1895 else if (Args[Arg].isInstantiationDependent()) 1896 setInstantiationDependent(); 1897 1898 if (Args[Arg].getKind() == TemplateArgument::Type && 1899 Args[Arg].getAsType()->isVariablyModifiedType()) 1900 setVariablyModified(); 1901 if (Args[Arg].containsUnexpandedParameterPack()) 1902 setContainsUnexpandedParameterPack(); 1903 1904 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); 1905 } 1906 1907 // Store the aliased type if this is a type alias template specialization. 1908 bool IsTypeAlias = !AliasedType.isNull(); 1909 assert(IsTypeAlias == isTypeAlias() && 1910 "allocated wrong size for type alias"); 1911 if (IsTypeAlias) { 1912 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 1913 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 1914 } 1915} 1916 1917void 1918TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1919 TemplateName T, 1920 const TemplateArgument *Args, 1921 unsigned NumArgs, 1922 const ASTContext &Context) { 1923 T.Profile(ID); 1924 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1925 Args[Idx].Profile(ID, Context); 1926} 1927 1928bool TemplateSpecializationType::isTypeAlias() const { 1929 TemplateDecl *D = Template.getAsTemplateDecl(); 1930 return D && isa<TypeAliasTemplateDecl>(D); 1931} 1932 1933QualType 1934QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 1935 if (!hasNonFastQualifiers()) 1936 return QT.withFastQualifiers(getFastQualifiers()); 1937 1938 return Context.getQualifiedType(QT, *this); 1939} 1940 1941QualType 1942QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 1943 if (!hasNonFastQualifiers()) 1944 return QualType(T, getFastQualifiers()); 1945 1946 return Context.getQualifiedType(T, *this); 1947} 1948 1949void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 1950 QualType BaseType, 1951 ObjCProtocolDecl * const *Protocols, 1952 unsigned NumProtocols) { 1953 ID.AddPointer(BaseType.getAsOpaquePtr()); 1954 for (unsigned i = 0; i != NumProtocols; i++) 1955 ID.AddPointer(Protocols[i]); 1956} 1957 1958void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 1959 Profile(ID, getBaseType(), qual_begin(), getNumProtocols()); 1960} 1961 1962namespace { 1963 1964/// \brief The cached properties of a type. 1965class CachedProperties { 1966 char linkage; 1967 char visibility; 1968 bool local; 1969 1970public: 1971 CachedProperties(Linkage linkage, Visibility visibility, bool local) 1972 : linkage(linkage), visibility(visibility), local(local) {} 1973 1974 Linkage getLinkage() const { return (Linkage) linkage; } 1975 Visibility getVisibility() const { return (Visibility) visibility; } 1976 bool hasLocalOrUnnamedType() const { return local; } 1977 1978 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 1979 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()), 1980 minVisibility(L.getVisibility(), R.getVisibility()), 1981 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 1982 } 1983}; 1984} 1985 1986static CachedProperties computeCachedProperties(const Type *T); 1987 1988namespace clang { 1989/// The type-property cache. This is templated so as to be 1990/// instantiated at an internal type to prevent unnecessary symbol 1991/// leakage. 1992template <class Private> class TypePropertyCache { 1993public: 1994 static CachedProperties get(QualType T) { 1995 return get(T.getTypePtr()); 1996 } 1997 1998 static CachedProperties get(const Type *T) { 1999 ensure(T); 2000 return CachedProperties(T->TypeBits.getLinkage(), 2001 T->TypeBits.getVisibility(), 2002 T->TypeBits.hasLocalOrUnnamedType()); 2003 } 2004 2005 static void ensure(const Type *T) { 2006 // If the cache is valid, we're okay. 2007 if (T->TypeBits.isCacheValid()) return; 2008 2009 // If this type is non-canonical, ask its canonical type for the 2010 // relevant information. 2011 if (!T->isCanonicalUnqualified()) { 2012 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 2013 ensure(CT); 2014 T->TypeBits.CacheValidAndVisibility = 2015 CT->TypeBits.CacheValidAndVisibility; 2016 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 2017 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 2018 return; 2019 } 2020 2021 // Compute the cached properties and then set the cache. 2022 CachedProperties Result = computeCachedProperties(T); 2023 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U; 2024 assert(T->TypeBits.isCacheValid() && 2025 T->TypeBits.getVisibility() == Result.getVisibility()); 2026 T->TypeBits.CachedLinkage = Result.getLinkage(); 2027 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 2028 } 2029}; 2030} 2031 2032// Instantiate the friend template at a private class. In a 2033// reasonable implementation, these symbols will be internal. 2034// It is terrible that this is the best way to accomplish this. 2035namespace { class Private {}; } 2036typedef TypePropertyCache<Private> Cache; 2037 2038static CachedProperties computeCachedProperties(const Type *T) { 2039 switch (T->getTypeClass()) { 2040#define TYPE(Class,Base) 2041#define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 2042#include "clang/AST/TypeNodes.def" 2043 llvm_unreachable("didn't expect a non-canonical type here"); 2044 2045#define TYPE(Class,Base) 2046#define DEPENDENT_TYPE(Class,Base) case Type::Class: 2047#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 2048#include "clang/AST/TypeNodes.def" 2049 // Treat instantiation-dependent types as external. 2050 assert(T->isInstantiationDependentType()); 2051 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 2052 2053 case Type::Builtin: 2054 // C++ [basic.link]p8: 2055 // A type is said to have linkage if and only if: 2056 // - it is a fundamental type (3.9.1); or 2057 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 2058 2059 case Type::Record: 2060 case Type::Enum: { 2061 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 2062 2063 // C++ [basic.link]p8: 2064 // - it is a class or enumeration type that is named (or has a name 2065 // for linkage purposes (7.1.3)) and the name has linkage; or 2066 // - it is a specialization of a class template (14); or 2067 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility(); 2068 bool IsLocalOrUnnamed = 2069 Tag->getDeclContext()->isFunctionOrMethod() || 2070 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()); 2071 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed); 2072 } 2073 2074 // C++ [basic.link]p8: 2075 // - it is a compound type (3.9.2) other than a class or enumeration, 2076 // compounded exclusively from types that have linkage; or 2077 case Type::Complex: 2078 return Cache::get(cast<ComplexType>(T)->getElementType()); 2079 case Type::Pointer: 2080 return Cache::get(cast<PointerType>(T)->getPointeeType()); 2081 case Type::BlockPointer: 2082 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 2083 case Type::LValueReference: 2084 case Type::RValueReference: 2085 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 2086 case Type::MemberPointer: { 2087 const MemberPointerType *MPT = cast<MemberPointerType>(T); 2088 return merge(Cache::get(MPT->getClass()), 2089 Cache::get(MPT->getPointeeType())); 2090 } 2091 case Type::ConstantArray: 2092 case Type::IncompleteArray: 2093 case Type::VariableArray: 2094 return Cache::get(cast<ArrayType>(T)->getElementType()); 2095 case Type::Vector: 2096 case Type::ExtVector: 2097 return Cache::get(cast<VectorType>(T)->getElementType()); 2098 case Type::FunctionNoProto: 2099 return Cache::get(cast<FunctionType>(T)->getResultType()); 2100 case Type::FunctionProto: { 2101 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2102 CachedProperties result = Cache::get(FPT->getResultType()); 2103 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(), 2104 ae = FPT->arg_type_end(); ai != ae; ++ai) 2105 result = merge(result, Cache::get(*ai)); 2106 return result; 2107 } 2108 case Type::ObjCInterface: { 2109 NamedDecl::LinkageInfo LV = 2110 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility(); 2111 return CachedProperties(LV.linkage(), LV.visibility(), false); 2112 } 2113 case Type::ObjCObject: 2114 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 2115 case Type::ObjCObjectPointer: 2116 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 2117 } 2118 2119 llvm_unreachable("unhandled type class"); 2120 2121 // C++ [basic.link]p8: 2122 // Names not covered by these rules have no linkage. 2123 return CachedProperties(NoLinkage, DefaultVisibility, false); 2124} 2125 2126/// \brief Determine the linkage of this type. 2127Linkage Type::getLinkage() const { 2128 Cache::ensure(this); 2129 return TypeBits.getLinkage(); 2130} 2131 2132/// \brief Determine the linkage of this type. 2133Visibility Type::getVisibility() const { 2134 Cache::ensure(this); 2135 return TypeBits.getVisibility(); 2136} 2137 2138bool Type::hasUnnamedOrLocalType() const { 2139 Cache::ensure(this); 2140 return TypeBits.hasLocalOrUnnamedType(); 2141} 2142 2143std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const { 2144 Cache::ensure(this); 2145 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility()); 2146} 2147 2148void Type::ClearLinkageCache() { 2149 TypeBits.CacheValidAndVisibility = 0; 2150 if (QualType(this, 0) != CanonicalType) 2151 CanonicalType->TypeBits.CacheValidAndVisibility = 0; 2152} 2153 2154Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 2155 if (isObjCARCImplicitlyUnretainedType()) 2156 return Qualifiers::OCL_ExplicitNone; 2157 return Qualifiers::OCL_Strong; 2158} 2159 2160bool Type::isObjCARCImplicitlyUnretainedType() const { 2161 assert(isObjCLifetimeType() && 2162 "cannot query implicit lifetime for non-inferrable type"); 2163 2164 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 2165 2166 // Walk down to the base type. We don't care about qualifiers for this. 2167 while (const ArrayType *array = dyn_cast<ArrayType>(canon)) 2168 canon = array->getElementType().getTypePtr(); 2169 2170 if (const ObjCObjectPointerType *opt 2171 = dyn_cast<ObjCObjectPointerType>(canon)) { 2172 // Class and Class<Protocol> don't require retension. 2173 if (opt->getObjectType()->isObjCClass()) 2174 return true; 2175 } 2176 2177 return false; 2178} 2179 2180bool Type::isObjCNSObjectType() const { 2181 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this)) 2182 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 2183 return false; 2184} 2185bool Type::isObjCRetainableType() const { 2186 return isObjCObjectPointerType() || 2187 isBlockPointerType() || 2188 isObjCNSObjectType(); 2189} 2190bool Type::isObjCIndirectLifetimeType() const { 2191 if (isObjCLifetimeType()) 2192 return true; 2193 if (const PointerType *OPT = getAs<PointerType>()) 2194 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 2195 if (const ReferenceType *Ref = getAs<ReferenceType>()) 2196 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 2197 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>()) 2198 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 2199 return false; 2200} 2201 2202/// Returns true if objects of this type have lifetime semantics under 2203/// ARC. 2204bool Type::isObjCLifetimeType() const { 2205 const Type *type = this; 2206 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 2207 type = array->getElementType().getTypePtr(); 2208 return type->isObjCRetainableType(); 2209} 2210 2211/// \brief Determine whether the given type T is a "bridgable" Objective-C type, 2212/// which is either an Objective-C object pointer type or an 2213bool Type::isObjCARCBridgableType() const { 2214 return isObjCObjectPointerType() || isBlockPointerType(); 2215} 2216 2217/// \brief Determine whether the given type T is a "bridgeable" C type. 2218bool Type::isCARCBridgableType() const { 2219 const PointerType *Pointer = getAs<PointerType>(); 2220 if (!Pointer) 2221 return false; 2222 2223 QualType Pointee = Pointer->getPointeeType(); 2224 return Pointee->isVoidType() || Pointee->isRecordType(); 2225} 2226 2227bool Type::hasSizedVLAType() const { 2228 if (!isVariablyModifiedType()) return false; 2229 2230 if (const PointerType *ptr = getAs<PointerType>()) 2231 return ptr->getPointeeType()->hasSizedVLAType(); 2232 if (const ReferenceType *ref = getAs<ReferenceType>()) 2233 return ref->getPointeeType()->hasSizedVLAType(); 2234 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 2235 if (isa<VariableArrayType>(arr) && 2236 cast<VariableArrayType>(arr)->getSizeExpr()) 2237 return true; 2238 2239 return arr->getElementType()->hasSizedVLAType(); 2240 } 2241 2242 return false; 2243} 2244 2245QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 2246 switch (type.getObjCLifetime()) { 2247 case Qualifiers::OCL_None: 2248 case Qualifiers::OCL_ExplicitNone: 2249 case Qualifiers::OCL_Autoreleasing: 2250 break; 2251 2252 case Qualifiers::OCL_Strong: 2253 return DK_objc_strong_lifetime; 2254 case Qualifiers::OCL_Weak: 2255 return DK_objc_weak_lifetime; 2256 } 2257 2258 /// Currently, the only destruction kind we recognize is C++ objects 2259 /// with non-trivial destructors. 2260 const CXXRecordDecl *record = 2261 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2262 if (record && record->hasDefinition() && !record->hasTrivialDestructor()) 2263 return DK_cxx_destructor; 2264 2265 return DK_none; 2266} 2267 2268bool QualType::hasTrivialCopyAssignment(ASTContext &Context) const { 2269 switch (getObjCLifetime()) { 2270 case Qualifiers::OCL_None: 2271 break; 2272 2273 case Qualifiers::OCL_ExplicitNone: 2274 return true; 2275 2276 case Qualifiers::OCL_Autoreleasing: 2277 case Qualifiers::OCL_Strong: 2278 case Qualifiers::OCL_Weak: 2279 return !Context.getLangOptions().ObjCAutoRefCount; 2280 } 2281 2282 if (const CXXRecordDecl *Record 2283 = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) 2284 return Record->hasTrivialCopyAssignment(); 2285 2286 return true; 2287} 2288