Type.cpp revision 5751838965eefa1c08e4fc545498a3ee45cd9611
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 // [...] 878 // -- an array of literal type 879 // Extension: variable arrays cannot be literal types, since they're 880 // runtime-sized. 881 if (isArrayType() && !isConstantArrayType()) 882 return false; 883 const Type *BaseTy = getBaseElementTypeUnsafe(); 884 assert(BaseTy && "NULL element type"); 885 886 // C++0x [basic.types]p10: 887 // A type is a literal type if it is: 888 // -- a scalar type; or 889 if (BaseTy->isScalarType()) return true; 890 // -- a reference type; or 891 if (BaseTy->isReferenceType()) return true; 892 // -- a class type that has all of the following properties: 893 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 894 if (const CXXRecordDecl *ClassDecl = 895 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 896 // -- a trivial destructor, 897 if (!ClassDecl->hasTrivialDestructor()) return false; 898 // -- every constructor call and full-expression in the 899 // brace-or-equal-initializers for non-static data members (if any) 900 // is a constant expression, 901 // FIXME: C++0x: Clang doesn't yet support non-static data member 902 // declarations with initializers, or constexprs. 903 // -- it is an aggregate type or has at least one constexpr 904 // constructor or constructor template that is not a copy or move 905 // constructor, and 906 if (!ClassDecl->isAggregate() && 907 !ClassDecl->hasConstExprNonCopyMoveConstructor()) 908 return false; 909 // -- all non-static data members and base classes of literal types 910 if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false; 911 } 912 913 return true; 914 } 915 return false; 916} 917 918bool Type::isTrivialType() const { 919 if (isIncompleteType()) 920 return false; 921 922 // C++0x [basic.types]p9: 923 // Scalar types, trivial class types, arrays of such types, and 924 // cv-qualified versions of these types are collectively called trivial 925 // types. 926 const Type *BaseTy = getBaseElementTypeUnsafe(); 927 assert(BaseTy && "NULL element type"); 928 if (BaseTy->isScalarType()) return true; 929 if (const RecordType *RT = BaseTy->getAs<RecordType>()) { 930 if (const CXXRecordDecl *ClassDecl = 931 dyn_cast<CXXRecordDecl>(RT->getDecl())) { 932 // C++0x [class]p5: 933 // A trivial class is a class that has a trivial default constructor 934 if (!ClassDecl->hasTrivialConstructor()) return false; 935 // and is trivially copyable. 936 if (!ClassDecl->isTriviallyCopyable()) return false; 937 } 938 939 return true; 940 } 941 942 // No other types can match. 943 return false; 944} 945 946bool Type::isPromotableIntegerType() const { 947 if (const BuiltinType *BT = getAs<BuiltinType>()) 948 switch (BT->getKind()) { 949 case BuiltinType::Bool: 950 case BuiltinType::Char_S: 951 case BuiltinType::Char_U: 952 case BuiltinType::SChar: 953 case BuiltinType::UChar: 954 case BuiltinType::Short: 955 case BuiltinType::UShort: 956 return true; 957 default: 958 return false; 959 } 960 961 // Enumerated types are promotable to their compatible integer types 962 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 963 if (const EnumType *ET = getAs<EnumType>()){ 964 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 965 || ET->getDecl()->isScoped()) 966 return false; 967 968 const BuiltinType *BT 969 = ET->getDecl()->getPromotionType()->getAs<BuiltinType>(); 970 return BT->getKind() == BuiltinType::Int 971 || BT->getKind() == BuiltinType::UInt; 972 } 973 974 return false; 975} 976 977bool Type::isNullPtrType() const { 978 if (const BuiltinType *BT = getAs<BuiltinType>()) 979 return BT->getKind() == BuiltinType::NullPtr; 980 return false; 981} 982 983bool Type::isSpecifierType() const { 984 // Note that this intentionally does not use the canonical type. 985 switch (getTypeClass()) { 986 case Builtin: 987 case Record: 988 case Enum: 989 case Typedef: 990 case Complex: 991 case TypeOfExpr: 992 case TypeOf: 993 case TemplateTypeParm: 994 case SubstTemplateTypeParm: 995 case TemplateSpecialization: 996 case Elaborated: 997 case DependentName: 998 case DependentTemplateSpecialization: 999 case ObjCInterface: 1000 case ObjCObject: 1001 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 1002 return true; 1003 default: 1004 return false; 1005 } 1006} 1007 1008ElaboratedTypeKeyword 1009TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 1010 switch (TypeSpec) { 1011 default: return ETK_None; 1012 case TST_typename: return ETK_Typename; 1013 case TST_class: return ETK_Class; 1014 case TST_struct: return ETK_Struct; 1015 case TST_union: return ETK_Union; 1016 case TST_enum: return ETK_Enum; 1017 } 1018} 1019 1020TagTypeKind 1021TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 1022 switch(TypeSpec) { 1023 case TST_class: return TTK_Class; 1024 case TST_struct: return TTK_Struct; 1025 case TST_union: return TTK_Union; 1026 case TST_enum: return TTK_Enum; 1027 } 1028 1029 llvm_unreachable("Type specifier is not a tag type kind."); 1030 return TTK_Union; 1031} 1032 1033ElaboratedTypeKeyword 1034TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 1035 switch (Kind) { 1036 case TTK_Class: return ETK_Class; 1037 case TTK_Struct: return ETK_Struct; 1038 case TTK_Union: return ETK_Union; 1039 case TTK_Enum: return ETK_Enum; 1040 } 1041 llvm_unreachable("Unknown tag type kind."); 1042} 1043 1044TagTypeKind 1045TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 1046 switch (Keyword) { 1047 case ETK_Class: return TTK_Class; 1048 case ETK_Struct: return TTK_Struct; 1049 case ETK_Union: return TTK_Union; 1050 case ETK_Enum: return TTK_Enum; 1051 case ETK_None: // Fall through. 1052 case ETK_Typename: 1053 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 1054 } 1055 llvm_unreachable("Unknown elaborated type keyword."); 1056} 1057 1058bool 1059TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 1060 switch (Keyword) { 1061 case ETK_None: 1062 case ETK_Typename: 1063 return false; 1064 case ETK_Class: 1065 case ETK_Struct: 1066 case ETK_Union: 1067 case ETK_Enum: 1068 return true; 1069 } 1070 llvm_unreachable("Unknown elaborated type keyword."); 1071} 1072 1073const char* 1074TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 1075 switch (Keyword) { 1076 case ETK_None: return ""; 1077 case ETK_Typename: return "typename"; 1078 case ETK_Class: return "class"; 1079 case ETK_Struct: return "struct"; 1080 case ETK_Union: return "union"; 1081 case ETK_Enum: return "enum"; 1082 } 1083 1084 llvm_unreachable("Unknown elaborated type keyword."); 1085 return ""; 1086} 1087 1088DependentTemplateSpecializationType::DependentTemplateSpecializationType( 1089 ElaboratedTypeKeyword Keyword, 1090 NestedNameSpecifier *NNS, const IdentifierInfo *Name, 1091 unsigned NumArgs, const TemplateArgument *Args, 1092 QualType Canon) 1093 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, 1094 /*VariablyModified=*/false, 1095 NNS && NNS->containsUnexpandedParameterPack()), 1096 NNS(NNS), Name(Name), NumArgs(NumArgs) { 1097 assert((!NNS || NNS->isDependent()) && 1098 "DependentTemplateSpecializatonType requires dependent qualifier"); 1099 for (unsigned I = 0; I != NumArgs; ++I) { 1100 if (Args[I].containsUnexpandedParameterPack()) 1101 setContainsUnexpandedParameterPack(); 1102 1103 new (&getArgBuffer()[I]) TemplateArgument(Args[I]); 1104 } 1105} 1106 1107void 1108DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1109 const ASTContext &Context, 1110 ElaboratedTypeKeyword Keyword, 1111 NestedNameSpecifier *Qualifier, 1112 const IdentifierInfo *Name, 1113 unsigned NumArgs, 1114 const TemplateArgument *Args) { 1115 ID.AddInteger(Keyword); 1116 ID.AddPointer(Qualifier); 1117 ID.AddPointer(Name); 1118 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1119 Args[Idx].Profile(ID, Context); 1120} 1121 1122bool Type::isElaboratedTypeSpecifier() const { 1123 ElaboratedTypeKeyword Keyword; 1124 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this)) 1125 Keyword = Elab->getKeyword(); 1126 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this)) 1127 Keyword = DepName->getKeyword(); 1128 else if (const DependentTemplateSpecializationType *DepTST = 1129 dyn_cast<DependentTemplateSpecializationType>(this)) 1130 Keyword = DepTST->getKeyword(); 1131 else 1132 return false; 1133 1134 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 1135} 1136 1137const char *Type::getTypeClassName() const { 1138 switch (TypeBits.TC) { 1139#define ABSTRACT_TYPE(Derived, Base) 1140#define TYPE(Derived, Base) case Derived: return #Derived; 1141#include "clang/AST/TypeNodes.def" 1142 } 1143 1144 llvm_unreachable("Invalid type class."); 1145 return 0; 1146} 1147 1148const char *BuiltinType::getName(const LangOptions &LO) const { 1149 switch (getKind()) { 1150 case Void: return "void"; 1151 case Bool: return LO.Bool ? "bool" : "_Bool"; 1152 case Char_S: return "char"; 1153 case Char_U: return "char"; 1154 case SChar: return "signed char"; 1155 case Short: return "short"; 1156 case Int: return "int"; 1157 case Long: return "long"; 1158 case LongLong: return "long long"; 1159 case Int128: return "__int128_t"; 1160 case UChar: return "unsigned char"; 1161 case UShort: return "unsigned short"; 1162 case UInt: return "unsigned int"; 1163 case ULong: return "unsigned long"; 1164 case ULongLong: return "unsigned long long"; 1165 case UInt128: return "__uint128_t"; 1166 case Float: return "float"; 1167 case Double: return "double"; 1168 case LongDouble: return "long double"; 1169 case WChar_S: 1170 case WChar_U: return "wchar_t"; 1171 case Char16: return "char16_t"; 1172 case Char32: return "char32_t"; 1173 case NullPtr: return "nullptr_t"; 1174 case Overload: return "<overloaded function type>"; 1175 case BoundMember: return "<bound member function type>"; 1176 case Dependent: return "<dependent type>"; 1177 case UnknownAny: return "<unknown type>"; 1178 case ObjCId: return "id"; 1179 case ObjCClass: return "Class"; 1180 case ObjCSel: return "SEL"; 1181 } 1182 1183 llvm_unreachable("Invalid builtin type."); 1184 return 0; 1185} 1186 1187QualType QualType::getNonLValueExprType(ASTContext &Context) const { 1188 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>()) 1189 return RefType->getPointeeType(); 1190 1191 // C++0x [basic.lval]: 1192 // Class prvalues can have cv-qualified types; non-class prvalues always 1193 // have cv-unqualified types. 1194 // 1195 // See also C99 6.3.2.1p2. 1196 if (!Context.getLangOptions().CPlusPlus || 1197 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 1198 return getUnqualifiedType(); 1199 1200 return *this; 1201} 1202 1203llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) { 1204 switch (CC) { 1205 case CC_Default: 1206 llvm_unreachable("no name for default cc"); 1207 return ""; 1208 1209 case CC_C: return "cdecl"; 1210 case CC_X86StdCall: return "stdcall"; 1211 case CC_X86FastCall: return "fastcall"; 1212 case CC_X86ThisCall: return "thiscall"; 1213 case CC_X86Pascal: return "pascal"; 1214 case CC_AAPCS: return "aapcs"; 1215 case CC_AAPCS_VFP: return "aapcs-vfp"; 1216 } 1217 1218 llvm_unreachable("Invalid calling convention."); 1219 return ""; 1220} 1221 1222FunctionProtoType::FunctionProtoType(QualType result, const QualType *args, 1223 unsigned numArgs, QualType canonical, 1224 const ExtProtoInfo &epi) 1225 : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals, 1226 epi.RefQualifier, canonical, 1227 result->isDependentType(), 1228 result->isVariablyModifiedType(), 1229 result->containsUnexpandedParameterPack(), 1230 epi.ExtInfo), 1231 NumArgs(numArgs), NumExceptions(epi.NumExceptions), 1232 ExceptionSpecType(epi.ExceptionSpecType) 1233{ 1234 // Fill in the trailing argument array. 1235 QualType *argSlot = reinterpret_cast<QualType*>(this+1); 1236 for (unsigned i = 0; i != numArgs; ++i) { 1237 if (args[i]->isDependentType()) 1238 setDependent(); 1239 1240 if (args[i]->containsUnexpandedParameterPack()) 1241 setContainsUnexpandedParameterPack(); 1242 1243 argSlot[i] = args[i]; 1244 } 1245 1246 if (getExceptionSpecType() == EST_Dynamic) { 1247 // Fill in the exception array. 1248 QualType *exnSlot = argSlot + numArgs; 1249 for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) { 1250 if (epi.Exceptions[i]->isDependentType()) 1251 setDependent(); 1252 1253 if (epi.Exceptions[i]->containsUnexpandedParameterPack()) 1254 setContainsUnexpandedParameterPack(); 1255 1256 exnSlot[i] = epi.Exceptions[i]; 1257 } 1258 } else if (getExceptionSpecType() == EST_ComputedNoexcept) { 1259 // Store the noexcept expression and context. 1260 Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs); 1261 *noexSlot = epi.NoexceptExpr; 1262 } 1263} 1264 1265FunctionProtoType::NoexceptResult 1266FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const { 1267 ExceptionSpecificationType est = getExceptionSpecType(); 1268 if (est == EST_BasicNoexcept) 1269 return NR_Nothrow; 1270 1271 if (est != EST_ComputedNoexcept) 1272 return NR_NoNoexcept; 1273 1274 Expr *noexceptExpr = getNoexceptExpr(); 1275 if (!noexceptExpr) 1276 return NR_BadNoexcept; 1277 if (noexceptExpr->isValueDependent()) 1278 return NR_Dependent; 1279 1280 llvm::APSInt value; 1281 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0, 1282 /*evaluated*/false); 1283 (void)isICE; 1284 assert(isICE && "AST should not contain bad noexcept expressions."); 1285 1286 return value.getBoolValue() ? NR_Nothrow : NR_Throw; 1287} 1288 1289bool FunctionProtoType::isTemplateVariadic() const { 1290 for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx) 1291 if (isa<PackExpansionType>(getArgType(ArgIdx - 1))) 1292 return true; 1293 1294 return false; 1295} 1296 1297void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 1298 const QualType *ArgTys, unsigned NumArgs, 1299 const ExtProtoInfo &epi, 1300 const ASTContext &Context) { 1301 ID.AddPointer(Result.getAsOpaquePtr()); 1302 for (unsigned i = 0; i != NumArgs; ++i) 1303 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 1304 ID.AddBoolean(epi.Variadic); 1305 ID.AddInteger(epi.TypeQuals); 1306 ID.AddInteger(epi.RefQualifier); 1307 ID.AddInteger(epi.ExceptionSpecType); 1308 if (epi.ExceptionSpecType == EST_Dynamic) { 1309 for (unsigned i = 0; i != epi.NumExceptions; ++i) 1310 ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr()); 1311 } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){ 1312 epi.NoexceptExpr->Profile(ID, Context, true); 1313 } 1314 epi.ExtInfo.Profile(ID); 1315} 1316 1317void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 1318 const ASTContext &Ctx) { 1319 Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(), 1320 Ctx); 1321} 1322 1323QualType TypedefType::desugar() const { 1324 return getDecl()->getUnderlyingType(); 1325} 1326 1327TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 1328 : Type(TypeOfExpr, can, E->isTypeDependent(), 1329 E->getType()->isVariablyModifiedType(), 1330 E->containsUnexpandedParameterPack()), 1331 TOExpr(E) { 1332} 1333 1334QualType TypeOfExprType::desugar() const { 1335 return getUnderlyingExpr()->getType(); 1336} 1337 1338void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 1339 const ASTContext &Context, Expr *E) { 1340 E->Profile(ID, Context, true); 1341} 1342 1343DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 1344 : Type(Decltype, can, E->isTypeDependent(), 1345 E->getType()->isVariablyModifiedType(), 1346 E->containsUnexpandedParameterPack()), 1347 E(E), 1348 UnderlyingType(underlyingType) { 1349} 1350 1351DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 1352 : DecltypeType(E, Context.DependentTy), Context(Context) { } 1353 1354void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 1355 const ASTContext &Context, Expr *E) { 1356 E->Profile(ID, Context, true); 1357} 1358 1359TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 1360 : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false, 1361 /*ContainsUnexpandedParameterPack=*/false), 1362 decl(const_cast<TagDecl*>(D)) {} 1363 1364static TagDecl *getInterestingTagDecl(TagDecl *decl) { 1365 for (TagDecl::redecl_iterator I = decl->redecls_begin(), 1366 E = decl->redecls_end(); 1367 I != E; ++I) { 1368 if (I->isDefinition() || I->isBeingDefined()) 1369 return *I; 1370 } 1371 // If there's no definition (not even in progress), return what we have. 1372 return decl; 1373} 1374 1375TagDecl *TagType::getDecl() const { 1376 return getInterestingTagDecl(decl); 1377} 1378 1379bool TagType::isBeingDefined() const { 1380 return getDecl()->isBeingDefined(); 1381} 1382 1383CXXRecordDecl *InjectedClassNameType::getDecl() const { 1384 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 1385} 1386 1387bool RecordType::classof(const TagType *TT) { 1388 return isa<RecordDecl>(TT->getDecl()); 1389} 1390 1391static uint64_t countBasesWithFields(QualType BaseType) { 1392 uint64_t BasesWithFields = 0; 1393 if (const RecordType *T = BaseType->getAs<RecordType>()) { 1394 CXXRecordDecl *RD = cast<CXXRecordDecl>(T->getDecl()); 1395 for (CXXRecordDecl::field_iterator Field = RD->field_begin(), 1396 E = RD->field_end(); Field != E; ++Field) 1397 BasesWithFields = 1; 1398 for (CXXRecordDecl::base_class_const_iterator B = RD->bases_begin(), 1399 BE = RD->bases_end(); B != BE; ++B) 1400 BasesWithFields += countBasesWithFields(B->getType()); 1401 } 1402 return BasesWithFields; 1403} 1404 1405bool RecordType::hasStandardLayout(ASTContext& Context) const { 1406 CXXRecordDecl *RD = cast<CXXRecordDecl>(getDecl()); 1407 if (! RD) { 1408 assert(cast<RecordDecl>(getDecl()) && 1409 "RecordType does not have a corresponding RecordDecl"); 1410 return true; 1411 } 1412 1413 // A standard-layout class is a class that: 1414 1415 for (CXXRecordDecl::method_iterator M = RD->method_begin(), 1416 ME = RD->method_end(); M != ME; ++M) { 1417 CXXMethodDecl *Method = *M; 1418 1419 // C++0x [class]p7: 1420 // A standard-layout class is a class that [...] 1421 // -- has no virtual functions (10.3) [...] 1422 if (Method->isVirtual()) 1423 return false; 1424 } 1425 1426 AccessSpecifier AS = AS_none; 1427 QualType FirstFieldType; 1428 bool FirstFieldType_set = false; 1429 uint64_t FieldCount = 0; 1430 1431 for (CXXRecordDecl::field_iterator Field = RD->field_begin(), 1432 E = RD->field_end(); Field != E; ++Field, ++FieldCount) { 1433 // C++0x [class]p7: 1434 // A standard-layout class is a class that [...] 1435 // -- has no non-static data members of type non-standard-layout class 1436 // (or array of such types) or reference [...] 1437 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 1438 if (const RecordType *T = 1439 Context.getBaseElementType(FieldType)->getAs<RecordType>()) { 1440 if (! T->hasStandardLayout(Context) || T->isReferenceType()) 1441 return false; 1442 } 1443 if (! FirstFieldType_set) { 1444 FirstFieldType = FieldType; 1445 FirstFieldType_set = true; 1446 } 1447 1448 // C++0x [class]p7: 1449 // A standard-layout class is a class that [...] 1450 // -- has the same access control (Clause 11) for all non-static data 1451 // members [...] 1452 if (AS == AS_none) 1453 AS = (*Field)->getAccess(); 1454 else if (AS != (*Field)->getAccess()) 1455 return false; 1456 } 1457 1458 for (CXXRecordDecl::base_class_const_iterator B = RD->bases_begin(), 1459 BE = RD->bases_end(); B != BE; ++B) { 1460 // C++0x [class]p7: 1461 // A standard-layout class is a class that [...] 1462 // -- no virtual base classes (10.1) [...] 1463 if (B->isVirtual()) 1464 return false; 1465 1466 QualType BT = B->getType(); 1467 1468 // C++0x [class]p7: 1469 // A standard-layout class is a class that [...] 1470 // -- has no non-standard-layout base classes [...] 1471 if (const RecordType *T = BT->getAs<RecordType>()) 1472 if (! T->hasStandardLayout(Context)) 1473 return false; 1474 1475 // C++0x [class]p7: 1476 // A standard-layout class is a class that [...] 1477 // -- has no base classes of the same type as the first non-static data 1478 // member. 1479 if (BT == FirstFieldType) 1480 return false; 1481 1482 // C++0x [class]p7: 1483 // A standard-layout class is a class that [...] 1484 // -- either has no non-static data members in the most derived class 1485 // and at most one base class with non-static data members, or has 1486 // no base classes with non-static data members [...] 1487 if (countBasesWithFields(BT) > (FieldCount == 0 ? 1 : 0)) 1488 return false; 1489 } 1490 1491 return true; 1492} 1493 1494bool EnumType::classof(const TagType *TT) { 1495 return isa<EnumDecl>(TT->getDecl()); 1496} 1497 1498SubstTemplateTypeParmPackType:: 1499SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 1500 QualType Canon, 1501 const TemplateArgument &ArgPack) 1502 : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param), 1503 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 1504{ 1505} 1506 1507TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 1508 return TemplateArgument(Arguments, NumArguments); 1509} 1510 1511void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 1512 Profile(ID, getReplacedParameter(), getArgumentPack()); 1513} 1514 1515void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 1516 const TemplateTypeParmType *Replaced, 1517 const TemplateArgument &ArgPack) { 1518 ID.AddPointer(Replaced); 1519 ID.AddInteger(ArgPack.pack_size()); 1520 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 1521 PEnd = ArgPack.pack_end(); 1522 P != PEnd; ++P) 1523 ID.AddPointer(P->getAsType().getAsOpaquePtr()); 1524} 1525 1526bool TemplateSpecializationType:: 1527anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) { 1528 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size()); 1529} 1530 1531bool TemplateSpecializationType:: 1532anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) { 1533 for (unsigned i = 0; i != N; ++i) 1534 if (Args[i].getArgument().isDependent()) 1535 return true; 1536 return false; 1537} 1538 1539bool TemplateSpecializationType:: 1540anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) { 1541 for (unsigned i = 0; i != N; ++i) 1542 if (Args[i].isDependent()) 1543 return true; 1544 return false; 1545} 1546 1547TemplateSpecializationType:: 1548TemplateSpecializationType(TemplateName T, 1549 const TemplateArgument *Args, 1550 unsigned NumArgs, QualType Canon) 1551 : Type(TemplateSpecialization, 1552 Canon.isNull()? QualType(this, 0) : Canon, 1553 T.isDependent(), false, T.containsUnexpandedParameterPack()), 1554 Template(T), NumArgs(NumArgs) 1555{ 1556 assert(!T.getAsDependentTemplateName() && 1557 "Use DependentTemplateSpecializationType for dependent template-name"); 1558 assert((!Canon.isNull() || 1559 T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) && 1560 "No canonical type for non-dependent class template specialization"); 1561 1562 TemplateArgument *TemplateArgs 1563 = reinterpret_cast<TemplateArgument *>(this + 1); 1564 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) { 1565 // Update dependent and variably-modified bits. 1566 if (Args[Arg].isDependent()) 1567 setDependent(); 1568 if (Args[Arg].getKind() == TemplateArgument::Type && 1569 Args[Arg].getAsType()->isVariablyModifiedType()) 1570 setVariablyModified(); 1571 if (Args[Arg].containsUnexpandedParameterPack()) 1572 setContainsUnexpandedParameterPack(); 1573 1574 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]); 1575 } 1576} 1577 1578void 1579TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 1580 TemplateName T, 1581 const TemplateArgument *Args, 1582 unsigned NumArgs, 1583 const ASTContext &Context) { 1584 T.Profile(ID); 1585 for (unsigned Idx = 0; Idx < NumArgs; ++Idx) 1586 Args[Idx].Profile(ID, Context); 1587} 1588 1589QualType 1590QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 1591 if (!hasNonFastQualifiers()) 1592 return QT.withFastQualifiers(getFastQualifiers()); 1593 1594 return Context.getQualifiedType(QT, *this); 1595} 1596 1597QualType 1598QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 1599 if (!hasNonFastQualifiers()) 1600 return QualType(T, getFastQualifiers()); 1601 1602 return Context.getQualifiedType(T, *this); 1603} 1604 1605void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 1606 QualType BaseType, 1607 ObjCProtocolDecl * const *Protocols, 1608 unsigned NumProtocols) { 1609 ID.AddPointer(BaseType.getAsOpaquePtr()); 1610 for (unsigned i = 0; i != NumProtocols; i++) 1611 ID.AddPointer(Protocols[i]); 1612} 1613 1614void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 1615 Profile(ID, getBaseType(), qual_begin(), getNumProtocols()); 1616} 1617 1618namespace { 1619 1620/// \brief The cached properties of a type. 1621class CachedProperties { 1622 char linkage; 1623 char visibility; 1624 bool local; 1625 1626public: 1627 CachedProperties(Linkage linkage, Visibility visibility, bool local) 1628 : linkage(linkage), visibility(visibility), local(local) {} 1629 1630 Linkage getLinkage() const { return (Linkage) linkage; } 1631 Visibility getVisibility() const { return (Visibility) visibility; } 1632 bool hasLocalOrUnnamedType() const { return local; } 1633 1634 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 1635 return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()), 1636 minVisibility(L.getVisibility(), R.getVisibility()), 1637 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 1638 } 1639}; 1640} 1641 1642static CachedProperties computeCachedProperties(const Type *T); 1643 1644namespace clang { 1645/// The type-property cache. This is templated so as to be 1646/// instantiated at an internal type to prevent unnecessary symbol 1647/// leakage. 1648template <class Private> class TypePropertyCache { 1649public: 1650 static CachedProperties get(QualType T) { 1651 return get(T.getTypePtr()); 1652 } 1653 1654 static CachedProperties get(const Type *T) { 1655 ensure(T); 1656 return CachedProperties(T->TypeBits.getLinkage(), 1657 T->TypeBits.getVisibility(), 1658 T->TypeBits.hasLocalOrUnnamedType()); 1659 } 1660 1661 static void ensure(const Type *T) { 1662 // If the cache is valid, we're okay. 1663 if (T->TypeBits.isCacheValid()) return; 1664 1665 // If this type is non-canonical, ask its canonical type for the 1666 // relevant information. 1667 if (!T->isCanonicalUnqualified()) { 1668 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 1669 ensure(CT); 1670 T->TypeBits.CacheValidAndVisibility = 1671 CT->TypeBits.CacheValidAndVisibility; 1672 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 1673 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 1674 return; 1675 } 1676 1677 // Compute the cached properties and then set the cache. 1678 CachedProperties Result = computeCachedProperties(T); 1679 T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U; 1680 assert(T->TypeBits.isCacheValid() && 1681 T->TypeBits.getVisibility() == Result.getVisibility()); 1682 T->TypeBits.CachedLinkage = Result.getLinkage(); 1683 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 1684 } 1685}; 1686} 1687 1688// Instantiate the friend template at a private class. In a 1689// reasonable implementation, these symbols will be internal. 1690// It is terrible that this is the best way to accomplish this. 1691namespace { class Private {}; } 1692typedef TypePropertyCache<Private> Cache; 1693 1694static CachedProperties computeCachedProperties(const Type *T) { 1695 switch (T->getTypeClass()) { 1696#define TYPE(Class,Base) 1697#define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 1698#include "clang/AST/TypeNodes.def" 1699 llvm_unreachable("didn't expect a non-canonical type here"); 1700 1701#define TYPE(Class,Base) 1702#define DEPENDENT_TYPE(Class,Base) case Type::Class: 1703#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 1704#include "clang/AST/TypeNodes.def" 1705 // Treat dependent types as external. 1706 assert(T->isDependentType()); 1707 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 1708 1709 case Type::Builtin: 1710 // C++ [basic.link]p8: 1711 // A type is said to have linkage if and only if: 1712 // - it is a fundamental type (3.9.1); or 1713 return CachedProperties(ExternalLinkage, DefaultVisibility, false); 1714 1715 case Type::Record: 1716 case Type::Enum: { 1717 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 1718 1719 // C++ [basic.link]p8: 1720 // - it is a class or enumeration type that is named (or has a name 1721 // for linkage purposes (7.1.3)) and the name has linkage; or 1722 // - it is a specialization of a class template (14); or 1723 NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility(); 1724 bool IsLocalOrUnnamed = 1725 Tag->getDeclContext()->isFunctionOrMethod() || 1726 (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()); 1727 return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed); 1728 } 1729 1730 // C++ [basic.link]p8: 1731 // - it is a compound type (3.9.2) other than a class or enumeration, 1732 // compounded exclusively from types that have linkage; or 1733 case Type::Complex: 1734 return Cache::get(cast<ComplexType>(T)->getElementType()); 1735 case Type::Pointer: 1736 return Cache::get(cast<PointerType>(T)->getPointeeType()); 1737 case Type::BlockPointer: 1738 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 1739 case Type::LValueReference: 1740 case Type::RValueReference: 1741 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 1742 case Type::MemberPointer: { 1743 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1744 return merge(Cache::get(MPT->getClass()), 1745 Cache::get(MPT->getPointeeType())); 1746 } 1747 case Type::ConstantArray: 1748 case Type::IncompleteArray: 1749 case Type::VariableArray: 1750 return Cache::get(cast<ArrayType>(T)->getElementType()); 1751 case Type::Vector: 1752 case Type::ExtVector: 1753 return Cache::get(cast<VectorType>(T)->getElementType()); 1754 case Type::FunctionNoProto: 1755 return Cache::get(cast<FunctionType>(T)->getResultType()); 1756 case Type::FunctionProto: { 1757 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1758 CachedProperties result = Cache::get(FPT->getResultType()); 1759 for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(), 1760 ae = FPT->arg_type_end(); ai != ae; ++ai) 1761 result = merge(result, Cache::get(*ai)); 1762 return result; 1763 } 1764 case Type::ObjCInterface: { 1765 NamedDecl::LinkageInfo LV = 1766 cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility(); 1767 return CachedProperties(LV.linkage(), LV.visibility(), false); 1768 } 1769 case Type::ObjCObject: 1770 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 1771 case Type::ObjCObjectPointer: 1772 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 1773 } 1774 1775 llvm_unreachable("unhandled type class"); 1776 1777 // C++ [basic.link]p8: 1778 // Names not covered by these rules have no linkage. 1779 return CachedProperties(NoLinkage, DefaultVisibility, false); 1780} 1781 1782/// \brief Determine the linkage of this type. 1783Linkage Type::getLinkage() const { 1784 Cache::ensure(this); 1785 return TypeBits.getLinkage(); 1786} 1787 1788/// \brief Determine the linkage of this type. 1789Visibility Type::getVisibility() const { 1790 Cache::ensure(this); 1791 return TypeBits.getVisibility(); 1792} 1793 1794bool Type::hasUnnamedOrLocalType() const { 1795 Cache::ensure(this); 1796 return TypeBits.hasLocalOrUnnamedType(); 1797} 1798 1799std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const { 1800 Cache::ensure(this); 1801 return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility()); 1802} 1803 1804void Type::ClearLinkageCache() { 1805 TypeBits.CacheValidAndVisibility = 0; 1806 if (QualType(this, 0) != CanonicalType) 1807 CanonicalType->TypeBits.CacheValidAndVisibility = 0; 1808} 1809 1810bool Type::hasSizedVLAType() const { 1811 if (!isVariablyModifiedType()) return false; 1812 1813 if (const PointerType *ptr = getAs<PointerType>()) 1814 return ptr->getPointeeType()->hasSizedVLAType(); 1815 if (const ReferenceType *ref = getAs<ReferenceType>()) 1816 return ref->getPointeeType()->hasSizedVLAType(); 1817 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 1818 if (isa<VariableArrayType>(arr) && 1819 cast<VariableArrayType>(arr)->getSizeExpr()) 1820 return true; 1821 1822 return arr->getElementType()->hasSizedVLAType(); 1823 } 1824 1825 return false; 1826} 1827 1828QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 1829 /// Currently, the only destruction kind we recognize is C++ objects 1830 /// with non-trivial destructors. 1831 const CXXRecordDecl *record = 1832 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1833 if (record && !record->hasTrivialDestructor()) 1834 return DK_cxx_destructor; 1835 1836 return DK_none; 1837} 1838