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