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