Type.cpp revision b7e9589bce9852b4db9575f55ac9137572147eb5
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 QualType::isConstant(QualType T, ASTContext &Ctx) { 31 if (T.isConstQualified()) 32 return true; 33 34 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 35 return AT->getElementType().isConstant(Ctx); 36 37 return false; 38} 39 40unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context, 41 QualType ElementType, 42 const llvm::APInt &NumElements) { 43 llvm::APSInt SizeExtended(NumElements, true); 44 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType()); 45 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits, 46 SizeExtended.getBitWidth()) * 2); 47 48 uint64_t ElementSize 49 = Context.getTypeSizeInChars(ElementType).getQuantity(); 50 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); 51 TotalSize *= SizeExtended; 52 53 return TotalSize.getActiveBits(); 54} 55 56unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) { 57 unsigned Bits = Context.getTypeSize(Context.getSizeType()); 58 59 // GCC appears to only allow 63 bits worth of address space when compiling 60 // for 64-bit, so we do the same. 61 if (Bits == 64) 62 --Bits; 63 64 return Bits; 65} 66 67DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 68 QualType et, QualType can, 69 Expr *e, ArraySizeModifier sm, 70 unsigned tq, 71 SourceRange brackets) 72 : ArrayType(DependentSizedArray, et, can, sm, tq, 73 (et->containsUnexpandedParameterPack() || 74 (e && e->containsUnexpandedParameterPack()))), 75 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) 76{ 77} 78 79void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, 80 const ASTContext &Context, 81 QualType ET, 82 ArraySizeModifier SizeMod, 83 unsigned TypeQuals, 84 Expr *E) { 85 ID.AddPointer(ET.getAsOpaquePtr()); 86 ID.AddInteger(SizeMod); 87 ID.AddInteger(TypeQuals); 88 E->Profile(ID, Context, true); 89} 90 91DependentSizedExtVectorType::DependentSizedExtVectorType(const 92 ASTContext &Context, 93 QualType ElementType, 94 QualType can, 95 Expr *SizeExpr, 96 SourceLocation loc) 97 : Type(DependentSizedExtVector, can, /*Dependent=*/true, 98 ElementType->isVariablyModifiedType(), 99 (ElementType->containsUnexpandedParameterPack() || 100 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))), 101 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), 102 loc(loc) 103{ 104} 105 106void 107DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, 108 const ASTContext &Context, 109 QualType ElementType, Expr *SizeExpr) { 110 ID.AddPointer(ElementType.getAsOpaquePtr()); 111 SizeExpr->Profile(ID, Context, true); 112} 113 114VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType, 115 VectorKind vecKind) 116 : Type(Vector, canonType, vecType->isDependentType(), 117 vecType->isVariablyModifiedType(), 118 vecType->containsUnexpandedParameterPack()), 119 ElementType(vecType) 120{ 121 VectorTypeBits.VecKind = vecKind; 122 VectorTypeBits.NumElements = nElements; 123} 124 125VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, 126 QualType canonType, VectorKind vecKind) 127 : Type(tc, canonType, vecType->isDependentType(), 128 vecType->isVariablyModifiedType(), 129 vecType->containsUnexpandedParameterPack()), 130 ElementType(vecType) 131{ 132 VectorTypeBits.VecKind = vecKind; 133 VectorTypeBits.NumElements = nElements; 134} 135 136/// getArrayElementTypeNoTypeQual - If this is an array type, return the 137/// element type of the array, potentially with type qualifiers missing. 138/// This method should never be used when type qualifiers are meaningful. 139const Type *Type::getArrayElementTypeNoTypeQual() const { 140 // If this is directly an array type, return it. 141 if (const ArrayType *ATy = dyn_cast<ArrayType>(this)) 142 return ATy->getElementType().getTypePtr(); 143 144 // If the canonical form of this type isn't the right kind, reject it. 145 if (!isa<ArrayType>(CanonicalType)) 146 return 0; 147 148 // If this is a typedef for an array type, strip the typedef off without 149 // losing all typedef information. 150 return cast<ArrayType>(getUnqualifiedDesugaredType()) 151 ->getElementType().getTypePtr(); 152} 153 154/// getDesugaredType - Return the specified type with any "sugar" removed from 155/// the type. This takes off typedefs, typeof's etc. If the outer level of 156/// the type is already concrete, it returns it unmodified. This is similar 157/// to getting the canonical type, but it doesn't remove *all* typedefs. For 158/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 159/// concrete. 160QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 161 SplitQualType split = getSplitDesugaredType(T); 162 return Context.getQualifiedType(split.first, split.second); 163} 164 165SplitQualType QualType::getSplitDesugaredType(QualType T) { 166 QualifierCollector Qs; 167 168 QualType Cur = T; 169 while (true) { 170 const Type *CurTy = Qs.strip(Cur); 171 switch (CurTy->getTypeClass()) { 172#define ABSTRACT_TYPE(Class, Parent) 173#define TYPE(Class, Parent) \ 174 case Type::Class: { \ 175 const Class##Type *Ty = cast<Class##Type>(CurTy); \ 176 if (!Ty->isSugared()) \ 177 return SplitQualType(Ty, Qs); \ 178 Cur = Ty->desugar(); \ 179 break; \ 180 } 181#include "clang/AST/TypeNodes.def" 182 } 183 } 184} 185 186SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) { 187 SplitQualType split = type.split(); 188 189 // All the qualifiers we've seen so far. 190 Qualifiers quals = split.second; 191 192 // The last type node we saw with any nodes inside it. 193 const Type *lastTypeWithQuals = split.first; 194 195 while (true) { 196 QualType next; 197 198 // Do a single-step desugar, aborting the loop if the type isn't 199 // sugared. 200 switch (split.first->getTypeClass()) { 201#define ABSTRACT_TYPE(Class, Parent) 202#define TYPE(Class, Parent) \ 203 case Type::Class: { \ 204 const Class##Type *ty = cast<Class##Type>(split.first); \ 205 if (!ty->isSugared()) goto done; \ 206 next = ty->desugar(); \ 207 break; \ 208 } 209#include "clang/AST/TypeNodes.def" 210 } 211 212 // Otherwise, split the underlying type. If that yields qualifiers, 213 // update the information. 214 split = next.split(); 215 if (!split.second.empty()) { 216 lastTypeWithQuals = split.first; 217 quals.addConsistentQualifiers(split.second); 218 } 219 } 220 221 done: 222 return SplitQualType(lastTypeWithQuals, quals); 223} 224 225QualType QualType::IgnoreParens(QualType T) { 226 // FIXME: this seems inherently un-qualifiers-safe. 227 while (const ParenType *PT = T->getAs<ParenType>()) 228 T = PT->getInnerType(); 229 return T; 230} 231 232/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic 233/// sugar off the given type. This should produce an object of the 234/// same dynamic type as the canonical type. 235const Type *Type::getUnqualifiedDesugaredType() const { 236 const Type *Cur = this; 237 238 while (true) { 239 switch (Cur->getTypeClass()) { 240#define ABSTRACT_TYPE(Class, Parent) 241#define TYPE(Class, Parent) \ 242 case Class: { \ 243 const Class##Type *Ty = cast<Class##Type>(Cur); \ 244 if (!Ty->isSugared()) return Cur; \ 245 Cur = Ty->desugar().getTypePtr(); \ 246 break; \ 247 } 248#include "clang/AST/TypeNodes.def" 249 } 250 } 251} 252 253/// isVoidType - Helper method to determine if this is the 'void' type. 254bool Type::isVoidType() const { 255 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 256 return BT->getKind() == BuiltinType::Void; 257 return false; 258} 259 260bool Type::isDerivedType() const { 261 switch (CanonicalType->getTypeClass()) { 262 case Pointer: 263 case VariableArray: 264 case ConstantArray: 265 case IncompleteArray: 266 case FunctionProto: 267 case FunctionNoProto: 268 case LValueReference: 269 case RValueReference: 270 case Record: 271 return true; 272 default: 273 return false; 274 } 275} 276 277bool Type::isClassType() const { 278 if (const RecordType *RT = getAs<RecordType>()) 279 return RT->getDecl()->isClass(); 280 return false; 281} 282bool Type::isStructureType() const { 283 if (const RecordType *RT = getAs<RecordType>()) 284 return RT->getDecl()->isStruct(); 285 return false; 286} 287bool Type::isStructureOrClassType() const { 288 if (const RecordType *RT = getAs<RecordType>()) 289 return RT->getDecl()->isStruct() || RT->getDecl()->isClass(); 290 return false; 291} 292bool Type::isVoidPointerType() const { 293 if (const PointerType *PT = getAs<PointerType>()) 294 return PT->getPointeeType()->isVoidType(); 295 return false; 296} 297 298bool Type::isUnionType() const { 299 if (const RecordType *RT = getAs<RecordType>()) 300 return RT->getDecl()->isUnion(); 301 return false; 302} 303 304bool Type::isComplexType() const { 305 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 306 return CT->getElementType()->isFloatingType(); 307 return false; 308} 309 310bool Type::isComplexIntegerType() const { 311 // Check for GCC complex integer extension. 312 return getAsComplexIntegerType(); 313} 314 315const ComplexType *Type::getAsComplexIntegerType() const { 316 if (const ComplexType *Complex = getAs<ComplexType>()) 317 if (Complex->getElementType()->isIntegerType()) 318 return Complex; 319 return 0; 320} 321 322QualType Type::getPointeeType() const { 323 if (const PointerType *PT = getAs<PointerType>()) 324 return PT->getPointeeType(); 325 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) 326 return OPT->getPointeeType(); 327 if (const BlockPointerType *BPT = getAs<BlockPointerType>()) 328 return BPT->getPointeeType(); 329 if (const ReferenceType *RT = getAs<ReferenceType>()) 330 return RT->getPointeeType(); 331 return QualType(); 332} 333 334const RecordType *Type::getAsStructureType() const { 335 // If this is directly a structure type, return it. 336 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 337 if (RT->getDecl()->isStruct()) 338 return RT; 339 } 340 341 // If the canonical form of this type isn't the right kind, reject it. 342 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 343 if (!RT->getDecl()->isStruct()) 344 return 0; 345 346 // If this is a typedef for a structure type, strip the typedef off without 347 // losing all typedef information. 348 return cast<RecordType>(getUnqualifiedDesugaredType()); 349 } 350 return 0; 351} 352 353const RecordType *Type::getAsUnionType() const { 354 // If this is directly a union type, return it. 355 if (const RecordType *RT = dyn_cast<RecordType>(this)) { 356 if (RT->getDecl()->isUnion()) 357 return RT; 358 } 359 360 // If the canonical form of this type isn't the right kind, reject it. 361 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) { 362 if (!RT->getDecl()->isUnion()) 363 return 0; 364 365 // If this is a typedef for a union type, strip the typedef off without 366 // losing all typedef information. 367 return cast<RecordType>(getUnqualifiedDesugaredType()); 368 } 369 370 return 0; 371} 372 373ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, 374 ObjCProtocolDecl * const *Protocols, 375 unsigned NumProtocols) 376 : Type(ObjCObject, Canonical, false, false, false), 377 BaseType(Base) 378{ 379 ObjCObjectTypeBits.NumProtocols = NumProtocols; 380 assert(getNumProtocols() == NumProtocols && 381 "bitfield overflow in protocol count"); 382 if (NumProtocols) 383 memcpy(getProtocolStorage(), Protocols, 384 NumProtocols * sizeof(ObjCProtocolDecl*)); 385} 386 387const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const { 388 // There is no sugar for ObjCObjectType's, just return the canonical 389 // type pointer if it is the right class. There is no typedef information to 390 // return and these cannot be Address-space qualified. 391 if (const ObjCObjectType *T = getAs<ObjCObjectType>()) 392 if (T->getNumProtocols() && T->getInterface()) 393 return T; 394 return 0; 395} 396 397bool Type::isObjCQualifiedInterfaceType() const { 398 return getAsObjCQualifiedInterfaceType() != 0; 399} 400 401const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const { 402 // There is no sugar for ObjCQualifiedIdType's, just return the canonical 403 // type pointer if it is the right class. 404 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 405 if (OPT->isObjCQualifiedIdType()) 406 return OPT; 407 } 408 return 0; 409} 410 411const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const { 412 // There is no sugar for ObjCQualifiedClassType's, just return the canonical 413 // type pointer if it is the right class. 414 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 415 if (OPT->isObjCQualifiedClassType()) 416 return OPT; 417 } 418 return 0; 419} 420 421const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 422 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) { 423 if (OPT->getInterfaceType()) 424 return OPT; 425 } 426 return 0; 427} 428 429const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const { 430 if (const PointerType *PT = getAs<PointerType>()) 431 if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>()) 432 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 433 return 0; 434} 435 436CXXRecordDecl *Type::getAsCXXRecordDecl() const { 437 if (const RecordType *RT = getAs<RecordType>()) 438 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 439 else if (const InjectedClassNameType *Injected 440 = getAs<InjectedClassNameType>()) 441 return Injected->getDecl(); 442 443 return 0; 444} 445 446namespace { 447 class GetContainedAutoVisitor : 448 public TypeVisitor<GetContainedAutoVisitor, AutoType*> { 449 public: 450 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit; 451 AutoType *Visit(QualType T) { 452 if (T.isNull()) 453 return 0; 454 return Visit(T.getTypePtr()); 455 } 456 457 // The 'auto' type itself. 458 AutoType *VisitAutoType(const AutoType *AT) { 459 return const_cast<AutoType*>(AT); 460 } 461 462 // Only these types can contain the desired 'auto' type. 463 AutoType *VisitPointerType(const PointerType *T) { 464 return Visit(T->getPointeeType()); 465 } 466 AutoType *VisitBlockPointerType(const BlockPointerType *T) { 467 return Visit(T->getPointeeType()); 468 } 469 AutoType *VisitReferenceType(const ReferenceType *T) { 470 return Visit(T->getPointeeTypeAsWritten()); 471 } 472 AutoType *VisitMemberPointerType(const MemberPointerType *T) { 473 return Visit(T->getPointeeType()); 474 } 475 AutoType *VisitArrayType(const ArrayType *T) { 476 return Visit(T->getElementType()); 477 } 478 AutoType *VisitDependentSizedExtVectorType( 479 const DependentSizedExtVectorType *T) { 480 return Visit(T->getElementType()); 481 } 482 AutoType *VisitVectorType(const VectorType *T) { 483 return Visit(T->getElementType()); 484 } 485 AutoType *VisitFunctionType(const FunctionType *T) { 486 return Visit(T->getResultType()); 487 } 488 AutoType *VisitParenType(const ParenType *T) { 489 return Visit(T->getInnerType()); 490 } 491 AutoType *VisitAttributedType(const AttributedType *T) { 492 return Visit(T->getModifiedType()); 493 } 494 }; 495} 496 497AutoType *Type::getContainedAutoType() const { 498 return GetContainedAutoVisitor().Visit(this); 499} 500 501bool Type::isIntegerType() const { 502 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 503 return BT->getKind() >= BuiltinType::Bool && 504 BT->getKind() <= BuiltinType::Int128; 505 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 506 // Incomplete enum types are not treated as integer types. 507 // FIXME: In C++, enum types are never integer types. 508 return ET->getDecl()->isComplete(); 509 return false; 510} 511 512bool Type::hasIntegerRepresentation() const { 513 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 514 return VT->getElementType()->isIntegerType(); 515 else 516 return isIntegerType(); 517} 518 519/// \brief Determine whether this type is an integral type. 520/// 521/// This routine determines whether the given type is an integral type per 522/// C++ [basic.fundamental]p7. Although the C standard does not define the 523/// term "integral type", it has a similar term "integer type", and in C++ 524/// the two terms are equivalent. However, C's "integer type" includes 525/// enumeration types, while C++'s "integer type" does not. The \c ASTContext 526/// parameter is used to determine whether we should be following the C or 527/// C++ rules when determining whether this type is an integral/integer type. 528/// 529/// For cases where C permits "an integer type" and C++ permits "an integral 530/// type", use this routine. 531/// 532/// For cases where C permits "an integer type" and C++ permits "an integral 533/// or enumeration type", use \c isIntegralOrEnumerationType() instead. 534/// 535/// \param Ctx The context in which this type occurs. 536/// 537/// \returns true if the type is considered an integral type, false otherwise. 538bool Type::isIntegralType(ASTContext &Ctx) const { 539 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 540 return BT->getKind() >= BuiltinType::Bool && 541 BT->getKind() <= BuiltinType::Int128; 542 543 if (!Ctx.getLangOptions().CPlusPlus) 544 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 545 return ET->getDecl()->isComplete(); // Complete enum types are integral in C. 546 547 return false; 548} 549 550bool Type::isIntegralOrEnumerationType() const { 551 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 552 return BT->getKind() >= BuiltinType::Bool && 553 BT->getKind() <= BuiltinType::Int128; 554 555 // Check for a complete enum type; incomplete enum types are not properly an 556 // enumeration type in the sense required here. 557 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 558 return ET->getDecl()->isComplete(); 559 560 return false; 561} 562 563bool Type::isIntegralOrUnscopedEnumerationType() const { 564 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 565 return BT->getKind() >= BuiltinType::Bool && 566 BT->getKind() <= BuiltinType::Int128; 567 568 // Check for a complete enum type; incomplete enum types are not properly an 569 // enumeration type in the sense required here. 570 // C++0x: However, if the underlying type of the enum is fixed, it is 571 // considered complete. 572 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 573 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 574 575 return false; 576} 577 578 579bool Type::isBooleanType() const { 580 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 581 return BT->getKind() == BuiltinType::Bool; 582 return false; 583} 584 585bool Type::isCharType() const { 586 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 587 return BT->getKind() == BuiltinType::Char_U || 588 BT->getKind() == BuiltinType::UChar || 589 BT->getKind() == BuiltinType::Char_S || 590 BT->getKind() == BuiltinType::SChar; 591 return false; 592} 593 594bool Type::isWideCharType() const { 595 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 596 return BT->getKind() == BuiltinType::WChar_S || 597 BT->getKind() == BuiltinType::WChar_U; 598 return false; 599} 600 601/// \brief Determine whether this type is any of the built-in character 602/// types. 603bool Type::isAnyCharacterType() const { 604 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType); 605 if (BT == 0) return false; 606 switch (BT->getKind()) { 607 default: return false; 608 case BuiltinType::Char_U: 609 case BuiltinType::UChar: 610 case BuiltinType::WChar_U: 611 case BuiltinType::Char16: 612 case BuiltinType::Char32: 613 case BuiltinType::Char_S: 614 case BuiltinType::SChar: 615 case BuiltinType::WChar_S: 616 return true; 617 } 618} 619 620/// isSignedIntegerType - Return true if this is an integer type that is 621/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 622/// an enum decl which has a signed representation 623bool Type::isSignedIntegerType() const { 624 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 625 return BT->getKind() >= BuiltinType::Char_S && 626 BT->getKind() <= BuiltinType::Int128; 627 } 628 629 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 630 // Incomplete enum types are not treated as integer types. 631 // FIXME: In C++, enum types are never integer types. 632 if (ET->getDecl()->isComplete()) 633 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 634 } 635 636 return false; 637} 638 639bool Type::hasSignedIntegerRepresentation() const { 640 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 641 return VT->getElementType()->isSignedIntegerType(); 642 else 643 return isSignedIntegerType(); 644} 645 646/// isUnsignedIntegerType - Return true if this is an integer type that is 647/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum 648/// decl which has an unsigned representation 649bool Type::isUnsignedIntegerType() const { 650 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) { 651 return BT->getKind() >= BuiltinType::Bool && 652 BT->getKind() <= BuiltinType::UInt128; 653 } 654 655 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 656 // Incomplete enum types are not treated as integer types. 657 // FIXME: In C++, enum types are never integer types. 658 if (ET->getDecl()->isComplete()) 659 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 660 } 661 662 return false; 663} 664 665bool Type::hasUnsignedIntegerRepresentation() const { 666 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 667 return VT->getElementType()->isUnsignedIntegerType(); 668 else 669 return isUnsignedIntegerType(); 670} 671 672bool Type::isFloatingType() const { 673 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 674 return BT->getKind() >= BuiltinType::Float && 675 BT->getKind() <= BuiltinType::LongDouble; 676 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType)) 677 return CT->getElementType()->isFloatingType(); 678 return false; 679} 680 681bool Type::hasFloatingRepresentation() const { 682 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType)) 683 return VT->getElementType()->isFloatingType(); 684 else 685 return isFloatingType(); 686} 687 688bool Type::isRealFloatingType() const { 689 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 690 return BT->isFloatingPoint(); 691 return false; 692} 693 694bool Type::isRealType() const { 695 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 696 return BT->getKind() >= BuiltinType::Bool && 697 BT->getKind() <= BuiltinType::LongDouble; 698 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 699 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 700 return false; 701} 702 703bool Type::isArithmeticType() const { 704 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 705 return BT->getKind() >= BuiltinType::Bool && 706 BT->getKind() <= BuiltinType::LongDouble; 707 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 708 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). 709 // If a body isn't seen by the time we get here, return false. 710 // 711 // C++0x: Enumerations are not arithmetic types. For now, just return 712 // false for scoped enumerations since that will disable any 713 // unwanted implicit conversions. 714 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete(); 715 return isa<ComplexType>(CanonicalType); 716} 717 718bool Type::isScalarType() const { 719 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 720 return BT->getKind() > BuiltinType::Void && 721 BT->getKind() <= BuiltinType::NullPtr; 722 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 723 // Enums are scalar types, but only if they are defined. Incomplete enums 724 // are not treated as scalar types. 725 return ET->getDecl()->isComplete(); 726 return isa<PointerType>(CanonicalType) || 727 isa<BlockPointerType>(CanonicalType) || 728 isa<MemberPointerType>(CanonicalType) || 729 isa<ComplexType>(CanonicalType) || 730 isa<ObjCObjectPointerType>(CanonicalType); 731} 732 733Type::ScalarTypeKind Type::getScalarTypeKind() const { 734 assert(isScalarType()); 735 736 const Type *T = CanonicalType.getTypePtr(); 737 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) { 738 if (BT->getKind() == BuiltinType::Bool) return STK_Bool; 739 if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer; 740 if (BT->isInteger()) return STK_Integral; 741 if (BT->isFloatingPoint()) return STK_Floating; 742 llvm_unreachable("unknown scalar builtin type"); 743 } else if (isa<PointerType>(T) || 744 isa<BlockPointerType>(T) || 745 isa<ObjCObjectPointerType>(T)) { 746 return STK_Pointer; 747 } else if (isa<MemberPointerType>(T)) { 748 return STK_MemberPointer; 749 } else if (isa<EnumType>(T)) { 750 assert(cast<EnumType>(T)->getDecl()->isComplete()); 751 return STK_Integral; 752 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) { 753 if (CT->getElementType()->isRealFloatingType()) 754 return STK_FloatingComplex; 755 return STK_IntegralComplex; 756 } 757 758 llvm_unreachable("unknown scalar type"); 759 return STK_Pointer; 760} 761 762/// \brief Determines whether the type is a C++ aggregate type or C 763/// aggregate or union type. 764/// 765/// An aggregate type is an array or a class type (struct, union, or 766/// class) that has no user-declared constructors, no private or 767/// protected non-static data members, no base classes, and no virtual 768/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type 769/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also 770/// includes union types. 771bool Type::isAggregateType() const { 772 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) { 773 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) 774 return ClassDecl->isAggregate(); 775 776 return true; 777 } 778 779 return isa<ArrayType>(CanonicalType); 780} 781 782/// isConstantSizeType - Return true if this is not a variable sized type, 783/// according to the rules of C99 6.7.5p3. It is not legal to call this on 784/// incomplete types or dependent types. 785bool Type::isConstantSizeType() const { 786 assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); 787 assert(!isDependentType() && "This doesn't make sense for dependent types"); 788 // The VAT must have a size, as it is known to be complete. 789 return !isa<VariableArrayType>(CanonicalType); 790} 791 792/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) 793/// - a type that can describe objects, but which lacks information needed to 794/// determine its size. 795bool Type::isIncompleteType() const { 796 switch (CanonicalType->getTypeClass()) { 797 default: return false; 798 case Builtin: 799 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never 800 // be completed. 801 return isVoidType(); 802 case Enum: 803 // An enumeration with fixed underlying type is complete (C++0x 7.2p3). 804 if (cast<EnumType>(CanonicalType)->getDecl()->isFixed()) 805 return false; 806 // Fall through. 807 case Record: 808 // A tagged type (struct/union/enum/class) is incomplete if the decl is a 809 // forward declaration, but not a full definition (C99 6.2.5p22). 810 return !cast<TagType>(CanonicalType)->getDecl()->isDefinition(); 811 case ConstantArray: 812 // An array is incomplete if its element type is incomplete 813 // (C++ [dcl.array]p1). 814 // We don't handle variable arrays (they're not allowed in C++) or 815 // dependent-sized arrays (dependent types are never treated as incomplete). 816 return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType(); 817 case IncompleteArray: 818 // An array of unknown size is an incomplete type (C99 6.2.5p22). 819 return true; 820 case ObjCObject: 821 return cast<ObjCObjectType>(CanonicalType)->getBaseType() 822 ->isIncompleteType(); 823 case ObjCInterface: 824 // ObjC interfaces are incomplete if they are @class, not @interface. 825 return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl(); 826 } 827} 828 829/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10) 830bool Type::isPODType() const { 831 // The compiler shouldn't query this for incomplete types, but the user might. 832 // We return false for that case. Except for incomplete arrays of PODs, which 833 // are PODs according to the standard. 834 if (isIncompleteArrayType() && 835 cast<ArrayType>(CanonicalType)->getElementType()->isPODType()) 836 return true; 837 if (isIncompleteType()) 838 return false; 839 840 switch (CanonicalType->getTypeClass()) { 841 // Everything not explicitly mentioned is not POD. 842 default: return false; 843 case VariableArray: 844 case ConstantArray: 845 // IncompleteArray is handled above. 846 return cast<ArrayType>(CanonicalType)->getElementType()->isPODType(); 847 848 case Builtin: 849 case Complex: 850 case Pointer: 851 case MemberPointer: 852 case Vector: 853 case ExtVector: 854 case ObjCObjectPointer: 855 case BlockPointer: 856 return true; 857 858 case Enum: 859 return true; 860 861 case Record: 862 if (CXXRecordDecl *ClassDecl 863 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 864 return ClassDecl->isPOD(); 865 866 // C struct/union is POD. 867 return true; 868 } 869} 870 871bool Type::isLiteralType() const { 872 if (isIncompleteType()) 873 return false; 874 875 // C++0x [basic.types]p10: 876 // A type is a literal type if it is: 877 switch (CanonicalType->getTypeClass()) { 878 // We're whitelisting 879 default: return false; 880 881 // -- a scalar type 882 case Builtin: 883 case Complex: 884 case Pointer: 885 case MemberPointer: 886 case Vector: 887 case ExtVector: 888 case ObjCObjectPointer: 889 case Enum: 890 return true; 891 892 // -- a class type with ... 893 case Record: 894 // FIXME: Do the tests 895 return false; 896 897 // -- an array of literal type 898 // Extension: variable arrays cannot be literal types, since they're 899 // runtime-sized. 900 case ConstantArray: 901 return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType(); 902 } 903} 904 905bool Type::isTrivialType() const { 906 if (isIncompleteType()) 907 return false; 908 909 // C++0x [basic.types]p9: 910 // Scalar types, trivial class types, arrays of such types, and 911 // cv-qualified versions of these types are collectively called trivial 912 // types. 913 const Type *BaseTy = getBaseElementTypeUnsafe(); 914 assert(BaseTy && "NULL element type"); 915 if (BaseTy->isScalarType()) return true; 916 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 917 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 918 919 // C++0x [class]p5: 920 // A trivial class is a class that has a trivial default constructor 921 if (!ClassDecl->hasTrivialConstructor()) return false; 922 // and is trivially copyable. 923 if (!ClassDecl->isTriviallyCopyable()) return false; 924 925 return true; 926 } 927 928 // No other types can match. 929 return false; 930} 931 932bool Type::isPromotableIntegerType() const { 933 if (const BuiltinType *BT = getAs<BuiltinType>()) 934 switch (BT->getKind()) { 935 case BuiltinType::Bool: 936 case BuiltinType::Char_S: 937 case BuiltinType::Char_U: 938 case BuiltinType::SChar: 939 case BuiltinType::UChar: 940 case BuiltinType::Short: 941 case BuiltinType::UShort: 942 return true; 943 default: 944 return false; 945 } 946 947 // Enumerated types are promotable to their compatible integer types 948 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 949 if (const EnumType *ET = getAs<EnumType>()){ 950 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 951 || ET->getDecl()->isScoped()) 952 return false; 953 954 const BuiltinType *BT 955 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>(); 956 return BT->getKind() == BuiltinType::Int 957 || BT->getKind() == BuiltinType::UInt; 958 } 959 960 return false; 961} 962 963bool Type::isNullPtrType() const { 964 if (const BuiltinType *BT = getAs<BuiltinType>()) 965 return BT->getKind() == BuiltinType::NullPtr; 966 return false; 967} 968 969bool Type::isSpecifierType() const { 970 // Note that this intentionally does not use the canonical type. 971 switch (getTypeClass()) { 972 case Builtin: 973 case Record: 974 case Enum: 975 case Typedef: 976 case Complex: 977 case TypeOfExpr: 978 case TypeOf: 979 case TemplateTypeParm: 980 case SubstTemplateTypeParm: 981 case TemplateSpecialization: 982 case Elaborated: 983 case DependentName: 984 case DependentTemplateSpecialization: 985 case ObjCInterface: 986 case ObjCObject: 987 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 988 return true; 989 default: 990 return false; 991 } 992} 993 994ElaboratedTypeKeyword 995TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 996 switch (TypeSpec) { 997 default: return ETK_None; 998 case TST_typename: return ETK_Typename; 999 case TST_class: return ETK_Class; 1000 case TST_struct: return ETK_Struct; 1001 case TST_union: return ETK_Union; 1002 case TST_enum: return ETK_Enum; 1003 } 1004} 1005 1006TagTypeKind 1007TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 1008 switch(TypeSpec) { 1009 case TST_class: return TTK_Class; 1010 case TST_struct: return TTK_Struct; 1011 case TST_union: return TTK_Union; 1012 case TST_enum: return TTK_Enum; 1013 } 1014 1015 llvm_unreachable("Type specifier is not a tag type kind."); 1016 return TTK_Union; 1017} 1018 1019ElaboratedTypeKeyword 1020TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 1021 switch (Kind) { 1022 case TTK_Class: return ETK_Class; 1023 case TTK_Struct: return ETK_Struct; 1024 case TTK_Union: return ETK_Union; 1025 case TTK_Enum: return ETK_Enum; 1026 } 1027 llvm_unreachable("Unknown tag type kind."); 1028} 1029 1030TagTypeKind 1031TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 1032 switch (Keyword) { 1033 case ETK_Class: return TTK_Class; 1034 case ETK_Struct: return TTK_Struct; 1035 case ETK_Union: return TTK_Union; 1036 case ETK_Enum: return TTK_Enum; 1037 case ETK_None: // Fall through. 1038 case ETK_Typename: 1039 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 1040 } 1041 llvm_unreachable("Unknown elaborated type keyword."); 1042} 1043 1044bool 1045TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 1046 switch (Keyword) { 1047 case ETK_None: 1048 case ETK_Typename: 1049 return false; 1050 case ETK_Class: 1051 case ETK_Struct: 1052 case ETK_Union: 1053 case ETK_Enum: 1054 return true; 1055 } 1056 llvm_unreachable("Unknown elaborated type keyword."); 1057} 1058 1059const char* 1060TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 1061 switch (Keyword) { 1062 case ETK_None: return ""; 1063 case ETK_Typename: return "typename"; 1064 case ETK_Class: return "class"; 1065 case ETK_Struct: return "struct"; 1066 case ETK_Union: return "union"; 1067 case ETK_Enum: return "enum"; 1068 } 1069 1070 llvm_unreachable("Unknown elaborated type keyword."); 1071 return ""; 1072} 1073 1074DependentTemplateSpecializationType::DependentTemplateSpecializationType( 1075 ElaboratedTypeKeyword Keyword, 1076 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 1077 unsigned NumArgs, const TemplateArgument *Args, 1078 QualType Canon) 1079 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, 1080 /*VariablyModified=*/false, 1081 NNS && NNS->containsUnexpandedParameterPack()), 1082 NNS(NNS), Name(Name), NumArgs(NumArgs) { 1083 assert((!NNS || NNS->isDependent()) && 1084 "DependentTemplateSpecializatonType requires dependent qualifier"); 1085 for (unsigned I = 0; I != NumArgs; ++I) { 1086 if (Args[I].containsUnexpandedParameterPack()) 1087 setContainsUnexpandedParameterPack(); 1088 1089 new (&getArgBuffer()[I]) TemplateArgument(Args[I]); 1090 } 1091} 1092 1093void 1094DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1095 const ASTContext &Context, 1096 ElaboratedTypeKeyword Keyword, 1097 NestedNameSpecifier *Qualifier, 1098 const IdentifierInfo *Name, 1099 unsigned NumArgs, 1100 const TemplateArgument *Args) { 1101 ID.AddInteger(Keyword); 1102 ID.AddPointer(Qualifier); 1103 ID.AddPointer(Name); 1104 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1105 Args[Idx].Profile(ID, Context); 1106} 1107 1108bool Type::isElaboratedTypeSpecifier() const { 1109 ElaboratedTypeKeyword Keyword; 1110 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this)) 1111 Keyword = Elab->getKeyword(); 1112 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this)) 1113 Keyword = DepName->getKeyword(); 1114 else if (const DependentTemplateSpecializationType *DepTST = 1115 dyn_cast<DependentTemplateSpecializationType>(this)) 1116 Keyword = DepTST->getKeyword(); 1117 else 1118 return false; 1119 1120 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 1121} 1122 1123const char *Type::getTypeClassName() const { 1124 switch (TypeBits.TC) { 1125#define ABSTRACT_TYPE(Derived, Base) 1126#define TYPE(Derived, Base) case Derived: return #Derived; 1127#include "clang/AST/TypeNodes.def" 1128 } 1129 1130 llvm_unreachable("Invalid type class."); 1131 return 0; 1132} 1133 1134const char *BuiltinType::getName(const LangOptions &LO) const { 1135 switch (getKind()) { 1136 case Void: return "void"; 1137 case Bool: return LO.Bool ? "bool" : "_Bool"; 1138 case Char_S: return "char"; 1139 case Char_U: return "char"; 1140 case SChar: return "signed char"; 1141 case Short: return "short"; 1142 case Int: return "int"; 1143 case Long: return "long"; 1144 case LongLong: return "long long"; 1145 case Int128: return "__int128_t"; 1146 case UChar: return "unsigned char"; 1147 case UShort: return "unsigned short"; 1148 case UInt: return "unsigned int"; 1149 case ULong: return "unsigned long"; 1150 case ULongLong: return "unsigned long long"; 1151 case UInt128: return "__uint128_t"; 1152 case Float: return "float"; 1153 case Double: return "double"; 1154 case LongDouble: return "long double"; 1155 case WChar_S: 1156 case WChar_U: return "wchar_t"; 1157 case Char16: return "char16_t"; 1158 case Char32: return "char32_t"; 1159 case NullPtr: return "nullptr_t"; 1160 case Overload: return "<overloaded function type>"; 1161 case Dependent: return "<dependent type>"; 1162 case UnknownAny: return "<unknown type>"; 1163 case ObjCId: return "id"; 1164 case ObjCClass: return "Class"; 1165 case ObjCSel: return "SEL"; 1166 } 1167 1168 llvm_unreachable("Invalid builtin type."); 1169 return 0; 1170} 1171 1172QualType QualType::getNonLValueExprType(ASTContext &Context) const { 1173 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>()) 1174 return RefType->getPointeeType(); 1175 1176 // C++0x [basic.lval]: 1177 // Class prvalues can have cv-qualified types; non-class prvalues always 1178 // have cv-unqualified types. 1179 // 1180 // See also C99 6.3.2.1p2. 1181 if (!Context.getLangOptions().CPlusPlus || 1182 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 1183 return getUnqualifiedType(); 1184 1185 return *this; 1186} 1187 1188llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) { 1189 switch (CC) { 1190 case CC_Default: 1191 llvm_unreachable("no name for default cc"); 1192 return ""; 1193 1194 case CC_C: return "cdecl"; 1195 case CC_X86StdCall: return "stdcall"; 1196 case CC_X86FastCall: return "fastcall"; 1197 case CC_X86ThisCall: return "thiscall"; 1198 case CC_X86Pascal: return "pascal"; 1199 case CC_AAPCS: return "aapcs"; 1200 case CC_AAPCS_VFP: return "aapcs-vfp"; 1201 } 1202 1203 llvm_unreachable("Invalid calling convention."); 1204 return ""; 1205} 1206 1207FunctionProtoType::FunctionProtoType(QualType result, const QualType *args, 1208 unsigned numArgs, QualType canonical, 1209 const ExtProtoInfo &epi) 1210 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals, 1211 epi.RefQualifier, canonical, 1212 result->isDependentType(), 1213 result->isVariablyModifiedType(), 1214 result->containsUnexpandedParameterPack(), 1215 epi.ExtInfo), 1216 NumArgs(numArgs), NumExceptions(epi.NumExceptions), 1217 ExceptionSpecType(epi.ExceptionSpecType) 1218{ 1219 // Fill in the trailing argument array. 1220 QualType *argSlot = reinterpret_cast<QualType*>(this+1); 1221 for (unsigned i = 0; i != numArgs; ++i) { 1222 if (args[i]->isDependentType()) 1223 setDependent(); 1224 1225 if (args[i]->containsUnexpandedParameterPack()) 1226 setContainsUnexpandedParameterPack(); 1227 1228 argSlot[i] = args[i]; 1229 } 1230 1231 if (getExceptionSpecType() == EST_Dynamic) { 1232 // Fill in the exception array. 1233 QualType *exnSlot = argSlot + numArgs; 1234 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) { 1235 if (epi.Exceptions[i]->isDependentType()) 1236 setDependent(); 1237 1238 if (epi.Exceptions[i]->containsUnexpandedParameterPack()) 1239 setContainsUnexpandedParameterPack(); 1240 1241 exnSlot[i] = epi.Exceptions[i]; 1242 } 1243 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 1244 // Store the noexcept expression and context. 1245 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs); 1246 *noexSlot = epi.NoexceptExpr; 1247 } 1248} 1249 1250FunctionProtoType::NoexceptResult 1251FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const { 1252 ExceptionSpecificationType est = getExceptionSpecType(); 1253 if (est == EST_BasicNoexcept) 1254 return NR_Nothrow; 1255 1256 if (est != EST_ComputedNoexcept) 1257 return NR_NoNoexcept; 1258 1259 Expr *noexceptExpr = getNoexceptExpr(); 1260 if (!noexceptExpr) 1261 return NR_BadNoexcept; 1262 if (noexceptExpr->isValueDependent()) 1263 return NR_Dependent; 1264 1265 llvm::APSInt value; 1266 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0, 1267 /*evaluated*/false); 1268 (void)isICE; 1269 assert(isICE && "AST should not contain bad noexcept expressions."); 1270 1271 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 1272} 1273 1274bool FunctionProtoType::isTemplateVariadic() const { 1275 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx) 1276 if (isa<PackExpansionType>(getArgType(ArgIdx - 1))) 1277 return true; 1278 1279 return false; 1280} 1281 1282void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 1283 const QualType *ArgTys, unsigned NumArgs, 1284 const ExtProtoInfo &epi, 1285 const ASTContext &Context) { 1286 ID.AddPointer(Result.getAsOpaquePtr()); 1287 for (unsigned i = 0; i != NumArgs; ++i) 1288 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 1289 ID.AddBoolean(epi.Variadic); 1290 ID.AddInteger(epi.TypeQuals); 1291 ID.AddInteger(epi.RefQualifier); 1292 ID.AddInteger(epi.ExceptionSpecType); 1293 if (epi.ExceptionSpecType == EST_Dynamic) { 1294 for (unsigned i = 0; i != epi.NumExceptions; ++i) 1295 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr()); 1296 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){ 1297 epi.NoexceptExpr->Profile(ID, Context, true); 1298 } 1299 epi.ExtInfo.Profile(ID); 1300} 1301 1302void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 1303 const ASTContext &Ctx) { 1304 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(), 1305 Ctx); 1306} 1307 1308QualType TypedefType::desugar() const { 1309 return getDecl()->getUnderlyingType(); 1310} 1311 1312TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 1313 : Type(TypeOfExpr, can, E->isTypeDependent(), 1314 E->getType()->isVariablyModifiedType(), 1315 E->containsUnexpandedParameterPack()), 1316 TOExpr(E) { 1317} 1318 1319QualType TypeOfExprType::desugar() const { 1320 return getUnderlyingExpr()->getType(); 1321} 1322 1323void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 1324 const ASTContext &Context, Expr *E) { 1325 E->Profile(ID, Context, true); 1326} 1327 1328DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 1329 : Type(Decltype, can, E->isTypeDependent(), 1330 E->getType()->isVariablyModifiedType(), 1331 E->containsUnexpandedParameterPack()), 1332 E(E), 1333 UnderlyingType(underlyingType) { 1334} 1335 1336DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 1337 : DecltypeType(E, Context.DependentTy), Context(Context) { } 1338 1339void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 1340 const ASTContext &Context, Expr *E) { 1341 E->Profile(ID, Context, true); 1342} 1343 1344TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 1345 : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false, 1346 /*ContainsUnexpandedParameterPack=*/false), 1347 decl(const_cast<TagDecl*>(D)) {} 1348 1349static TagDecl *getInterestingTagDecl(TagDecl *decl) { 1350 for (TagDecl::redecl_iterator I = decl->redecls_begin(), 1351 E = decl->redecls_end(); 1352 I != E; ++I) { 1353 if (I->isDefinition() || I->isBeingDefined()) 1354 return *I; 1355 } 1356 // If there's no definition (not even in progress), return what we have. 1357 return decl; 1358} 1359 1360TagDecl *TagType::getDecl() const { 1361 return getInterestingTagDecl(decl); 1362} 1363 1364bool TagType::isBeingDefined() const { 1365 return getDecl()->isBeingDefined(); 1366} 1367 1368CXXRecordDecl *InjectedClassNameType::getDecl() const { 1369 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 1370} 1371 1372bool RecordType::classof(const TagType *TT) { 1373 return isa<RecordDecl>(TT->getDecl()); 1374} 1375 1376bool EnumType::classof(const TagType *TT) { 1377 return isa<EnumDecl>(TT->getDecl()); 1378} 1379 1380SubstTemplateTypeParmPackType:: 1381SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 1382 QualType Canon, 1383 const TemplateArgument &ArgPack) 1384 : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param), 1385 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 1386{ 1387} 1388 1389TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 1390 return TemplateArgument(Arguments, NumArguments); 1391} 1392 1393void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 1394 Profile(ID, getReplacedParameter(), getArgumentPack()); 1395} 1396 1397void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 1398 const TemplateTypeParmType *Replaced, 1399 const TemplateArgument &ArgPack) { 1400 ID.AddPointer(Replaced); 1401 ID.AddInteger(ArgPack.pack_size()); 1402 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 1403 PEnd = ArgPack.pack_end(); 1404 P != PEnd; ++P) 1405 ID.AddPointer(P->getAsType().getAsOpaquePtr()); 1406} 1407 1408bool TemplateSpecializationType:: 1409anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) { 1410 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size()); 1411} 1412 1413bool TemplateSpecializationType:: 1414anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) { 1415 for (unsigned i = 0; i != N; ++i) 1416 if (Args[i].getArgument().isDependent()) 1417 return true; 1418 return false; 1419} 1420 1421bool TemplateSpecializationType:: 1422anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) { 1423 for (unsigned i = 0; i != N; ++i) 1424 if (Args[i].isDependent()) 1425 return true; 1426 return false; 1427} 1428 1429TemplateSpecializationType:: 1430TemplateSpecializationType(TemplateName T, 1431 const TemplateArgument *Args, 1432 unsigned NumArgs, QualType Canon) 1433 : Type(TemplateSpecialization, 1434 Canon.isNull()? QualType(this, 0) : Canon, 1435 T.isDependent(), false, T.containsUnexpandedParameterPack()), 1436 Template(T), NumArgs(NumArgs) 1437{ 1438 assert(!T.getAsDependentTemplateName() && 1439 "Use DependentTemplateSpecializationType for dependent template-name"); 1440 assert((!Canon.isNull() || 1441 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) && 1442 "No canonical type for non-dependent class template specialization"); 1443 1444 TemplateArgument *TemplateArgs 1445 = reinterpret_cast<TemplateArgument *>(this + 1); 1446 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { 1447 // Update dependent and variably-modified bits. 1448 if (Args[Arg].isDependent()) 1449 setDependent(); 1450 if (Args[Arg].getKind() == TemplateArgument::Type && 1451 Args[Arg].getAsType()->isVariablyModifiedType()) 1452 setVariablyModified(); 1453 if (Args[Arg].containsUnexpandedParameterPack()) 1454 setContainsUnexpandedParameterPack(); 1455 1456 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); 1457 } 1458} 1459 1460void 1461TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1462 TemplateName T, 1463 const TemplateArgument *Args, 1464 unsigned NumArgs, 1465 const ASTContext &Context) { 1466 T.Profile(ID); 1467 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1468 Args[Idx].Profile(ID, Context); 1469} 1470 1471QualType 1472QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 1473 if (!hasNonFastQualifiers()) 1474 return QT.withFastQualifiers(getFastQualifiers()); 1475 1476 return Context.getQualifiedType(QT, *this); 1477} 1478 1479QualType 1480QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 1481 if (!hasNonFastQualifiers()) 1482 return QualType(T, getFastQualifiers()); 1483 1484 return Context.getQualifiedType(T, *this); 1485} 1486 1487void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 1488 QualType BaseType, 1489 ObjCProtocolDecl * const *Protocols, 1490 unsigned NumProtocols) { 1491 ID.AddPointer(BaseType.getAsOpaquePtr()); 1492 for (unsigned i = 0; i != NumProtocols; i++) 1493 ID.AddPointer(Protocols[i]); 1494} 1495 1496void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 1497 Profile(ID, getBaseType(), qual_begin(), getNumProtocols()); 1498} 1499 1500namespace { 1501 1502/// \brief The cached properties of a type. 1503class CachedProperties { 1504 char linkage; 1505 char visibility; 1506 bool local; 1507 1508public: 1509 CachedProperties(Linkage linkage, Visibility visibility, bool local) 1510 : linkage(linkage), visibility(visibility), local(local) {} 1511 1512 Linkage getLinkage() const { return (Linkage) linkage; } 1513 Visibility getVisibility() const { return (Visibility) visibility; } 1514 bool hasLocalOrUnnamedType() const { return local; } 1515 1516 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 1517 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()), 1518 minVisibility(L.getVisibility(), R.getVisibility()), 1519 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 1520 } 1521}; 1522} 1523 1524static CachedProperties computeCachedProperties(const Type *T); 1525 1526namespace clang { 1527/// The type-property cache. This is templated so as to be 1528/// instantiated at an internal type to prevent unnecessary symbol 1529/// leakage. 1530template <class Private> class TypePropertyCache { 1531public: 1532 static CachedProperties get(QualType T) { 1533 return get(T.getTypePtr()); 1534 } 1535 1536 static CachedProperties get(const Type *T) { 1537 ensure(T); 1538 return CachedProperties(T->TypeBits.getLinkage(), 1539 T->TypeBits.getVisibility(), 1540 T->TypeBits.hasLocalOrUnnamedType()); 1541 } 1542 1543 static void ensure(const Type *T) { 1544 // If the cache is valid, we're okay. 1545 if (T->TypeBits.isCacheValid()) return; 1546 1547 // If this type is non-canonical, ask its canonical type for the 1548 // relevant information. 1549 if (!T->isCanonicalUnqualified()) { 1550 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 1551 ensure(CT); 1552 T->TypeBits.CacheValidAndVisibility = 1553 CT->TypeBits.CacheValidAndVisibility; 1554 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 1555 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 1556 return; 1557 } 1558 1559 // Compute the cached properties and then set the cache. 1560 CachedProperties Result = computeCachedProperties(T); 1561 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U; 1562 assert(T->TypeBits.isCacheValid() && 1563 T->TypeBits.getVisibility() == Result.getVisibility()); 1564 T->TypeBits.CachedLinkage = Result.getLinkage(); 1565 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 1566 } 1567}; 1568} 1569 1570// Instantiate the friend template at a private class. In a 1571// reasonable implementation, these symbols will be internal. 1572// It is terrible that this is the best way to accomplish this. 1573namespace { class Private {}; } 1574typedef TypePropertyCache<Private> Cache; 1575 1576static CachedProperties computeCachedProperties(const Type *T) { 1577 switch (T->getTypeClass()) { 1578#define TYPE(Class,Base) 1579#define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 1580#include "clang/AST/TypeNodes.def" 1581 llvm_unreachable("didn't expect a non-canonical type here"); 1582 1583#define TYPE(Class,Base) 1584#define DEPENDENT_TYPE(Class,Base) case Type::Class: 1585#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 1586#include "clang/AST/TypeNodes.def" 1587 // Treat dependent types as external. 1588 assert(T->isDependentType()); 1589 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 1590 1591 case Type::Builtin: 1592 // C++ [basic.link]p8: 1593 // A type is said to have linkage if and only if: 1594 // - it is a fundamental type (3.9.1); or 1595 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 1596 1597 case Type::Record: 1598 case Type::Enum: { 1599 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 1600 1601 // C++ [basic.link]p8: 1602 // - it is a class or enumeration type that is named (or has a name 1603 // for linkage purposes (7.1.3)) and the name has linkage; or 1604 // - it is a specialization of a class template (14); or 1605 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility(); 1606 bool IsLocalOrUnnamed = 1607 Tag->getDeclContext()->isFunctionOrMethod() || 1608 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()); 1609 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed); 1610 } 1611 1612 // C++ [basic.link]p8: 1613 // - it is a compound type (3.9.2) other than a class or enumeration, 1614 // compounded exclusively from types that have linkage; or 1615 case Type::Complex: 1616 return Cache::get(cast<ComplexType>(T)->getElementType()); 1617 case Type::Pointer: 1618 return Cache::get(cast<PointerType>(T)->getPointeeType()); 1619 case Type::BlockPointer: 1620 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 1621 case Type::LValueReference: 1622 case Type::RValueReference: 1623 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 1624 case Type::MemberPointer: { 1625 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1626 return merge(Cache::get(MPT->getClass()), 1627 Cache::get(MPT->getPointeeType())); 1628 } 1629 case Type::ConstantArray: 1630 case Type::IncompleteArray: 1631 case Type::VariableArray: 1632 return Cache::get(cast<ArrayType>(T)->getElementType()); 1633 case Type::Vector: 1634 case Type::ExtVector: 1635 return Cache::get(cast<VectorType>(T)->getElementType()); 1636 case Type::FunctionNoProto: 1637 return Cache::get(cast<FunctionType>(T)->getResultType()); 1638 case Type::FunctionProto: { 1639 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1640 CachedProperties result = Cache::get(FPT->getResultType()); 1641 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(), 1642 ae = FPT->arg_type_end(); ai != ae; ++ai) 1643 result = merge(result, Cache::get(*ai)); 1644 return result; 1645 } 1646 case Type::ObjCInterface: { 1647 NamedDecl::LinkageInfo LV = 1648 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility(); 1649 return CachedProperties(LV.linkage(), LV.visibility(), false); 1650 } 1651 case Type::ObjCObject: 1652 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 1653 case Type::ObjCObjectPointer: 1654 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 1655 } 1656 1657 llvm_unreachable("unhandled type class"); 1658 1659 // C++ [basic.link]p8: 1660 // Names not covered by these rules have no linkage. 1661 return CachedProperties(NoLinkage, DefaultVisibility, false); 1662} 1663 1664/// \brief Determine the linkage of this type. 1665Linkage Type::getLinkage() const { 1666 Cache::ensure(this); 1667 return TypeBits.getLinkage(); 1668} 1669 1670/// \brief Determine the linkage of this type. 1671Visibility Type::getVisibility() const { 1672 Cache::ensure(this); 1673 return TypeBits.getVisibility(); 1674} 1675 1676bool Type::hasUnnamedOrLocalType() const { 1677 Cache::ensure(this); 1678 return TypeBits.hasLocalOrUnnamedType(); 1679} 1680 1681std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const { 1682 Cache::ensure(this); 1683 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility()); 1684} 1685 1686void Type::ClearLinkageCache() { 1687 TypeBits.CacheValidAndVisibility = 0; 1688 if (QualType(this, 0) != CanonicalType) 1689 CanonicalType->TypeBits.CacheValidAndVisibility = 0; 1690} 1691 1692bool Type::hasSizedVLAType() const { 1693 if (!isVariablyModifiedType()) return false; 1694 1695 if (const PointerType *ptr = getAs<PointerType>()) 1696 return ptr->getPointeeType()->hasSizedVLAType(); 1697 if (const ReferenceType *ref = getAs<ReferenceType>()) 1698 return ref->getPointeeType()->hasSizedVLAType(); 1699 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 1700 if (isa<VariableArrayType>(arr) && 1701 cast<VariableArrayType>(arr)->getSizeExpr()) 1702 return true; 1703 1704 return arr->getElementType()->hasSizedVLAType(); 1705 } 1706 1707 return false; 1708} 1709 1710QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 1711 /// Currently, the only destruction kind we recognize is C++ objects 1712 /// with non-trivial destructors. 1713 const CXXRecordDecl *record = 1714 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1715 if (record && !record->hasTrivialDestructor()) 1716 return DK_cxx_destructor; 1717 1718 return DK_none; 1719} 1720