1 //===- Type.cpp - Type representation and manipulation --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements type-related functionality. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/Type.h" 14 #include "Linkage.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DependenceFlags.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/NestedNameSpecifier.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/PrettyPrinter.h" 28 #include "clang/AST/TemplateBase.h" 29 #include "clang/AST/TemplateName.h" 30 #include "clang/AST/TypeVisitor.h" 31 #include "clang/Basic/AddressSpaces.h" 32 #include "clang/Basic/ExceptionSpecificationType.h" 33 #include "clang/Basic/IdentifierTable.h" 34 #include "clang/Basic/LLVM.h" 35 #include "clang/Basic/LangOptions.h" 36 #include "clang/Basic/Linkage.h" 37 #include "clang/Basic/Specifiers.h" 38 #include "clang/Basic/TargetCXXABI.h" 39 #include "clang/Basic/TargetInfo.h" 40 #include "clang/Basic/Visibility.h" 41 #include "llvm/ADT/APInt.h" 42 #include "llvm/ADT/APSInt.h" 43 #include "llvm/ADT/ArrayRef.h" 44 #include "llvm/ADT/FoldingSet.h" 45 #include "llvm/ADT/None.h" 46 #include "llvm/ADT/SmallVector.h" 47 #include "llvm/Support/Casting.h" 48 #include "llvm/Support/ErrorHandling.h" 49 #include "llvm/Support/MathExtras.h" 50 #include <algorithm> 51 #include <cassert> 52 #include <cstdint> 53 #include <cstring> 54 #include <type_traits> 55 56 using namespace clang; 57 58 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const { 59 return (*this != Other) && 60 // CVR qualifiers superset 61 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) && 62 // ObjC GC qualifiers superset 63 ((getObjCGCAttr() == Other.getObjCGCAttr()) || 64 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) && 65 // Address space superset. 66 ((getAddressSpace() == Other.getAddressSpace()) || 67 (hasAddressSpace()&& !Other.hasAddressSpace())) && 68 // Lifetime qualifier superset. 69 ((getObjCLifetime() == Other.getObjCLifetime()) || 70 (hasObjCLifetime() && !Other.hasObjCLifetime())); 71 } 72 73 const IdentifierInfo* QualType::getBaseTypeIdentifier() const { 74 const Type* ty = getTypePtr(); 75 NamedDecl *ND = nullptr; 76 if (ty->isPointerType() || ty->isReferenceType()) 77 return ty->getPointeeType().getBaseTypeIdentifier(); 78 else if (ty->isRecordType()) 79 ND = ty->castAs<RecordType>()->getDecl(); 80 else if (ty->isEnumeralType()) 81 ND = ty->castAs<EnumType>()->getDecl(); 82 else if (ty->getTypeClass() == Type::Typedef) 83 ND = ty->castAs<TypedefType>()->getDecl(); 84 else if (ty->isArrayType()) 85 return ty->castAsArrayTypeUnsafe()-> 86 getElementType().getBaseTypeIdentifier(); 87 88 if (ND) 89 return ND->getIdentifier(); 90 return nullptr; 91 } 92 93 bool QualType::mayBeDynamicClass() const { 94 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl(); 95 return ClassDecl && ClassDecl->mayBeDynamicClass(); 96 } 97 98 bool QualType::mayBeNotDynamicClass() const { 99 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl(); 100 return !ClassDecl || ClassDecl->mayBeNonDynamicClass(); 101 } 102 103 bool QualType::isConstant(QualType T, const ASTContext &Ctx) { 104 if (T.isConstQualified()) 105 return true; 106 107 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 108 return AT->getElementType().isConstant(Ctx); 109 110 return T.getAddressSpace() == LangAS::opencl_constant; 111 } 112 113 // C++ [temp.dep.type]p1: 114 // A type is dependent if it is... 115 // - an array type constructed from any dependent type or whose 116 // size is specified by a constant expression that is 117 // value-dependent, 118 ArrayType::ArrayType(TypeClass tc, QualType et, QualType can, 119 ArraySizeModifier sm, unsigned tq, const Expr *sz) 120 // Note, we need to check for DependentSizedArrayType explicitly here 121 // because we use a DependentSizedArrayType with no size expression as the 122 // type of a dependent array of unknown bound with a dependent braced 123 // initializer: 124 // 125 // template<int ...N> int arr[] = {N...}; 126 : Type(tc, can, 127 et->getDependence() | 128 (sz ? toTypeDependence( 129 turnValueToTypeDependence(sz->getDependence())) 130 : TypeDependence::None) | 131 (tc == VariableArray ? TypeDependence::VariablyModified 132 : TypeDependence::None) | 133 (tc == DependentSizedArray 134 ? TypeDependence::DependentInstantiation 135 : TypeDependence::None)), 136 ElementType(et) { 137 ArrayTypeBits.IndexTypeQuals = tq; 138 ArrayTypeBits.SizeModifier = sm; 139 } 140 141 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context, 142 QualType ElementType, 143 const llvm::APInt &NumElements) { 144 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity(); 145 146 // Fast path the common cases so we can avoid the conservative computation 147 // below, which in common cases allocates "large" APSInt values, which are 148 // slow. 149 150 // If the element size is a power of 2, we can directly compute the additional 151 // number of addressing bits beyond those required for the element count. 152 if (llvm::isPowerOf2_64(ElementSize)) { 153 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize); 154 } 155 156 // If both the element count and element size fit in 32-bits, we can do the 157 // computation directly in 64-bits. 158 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 && 159 (NumElements.getZExtValue() >> 32) == 0) { 160 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize; 161 return 64 - llvm::countLeadingZeros(TotalSize); 162 } 163 164 // Otherwise, use APSInt to handle arbitrary sized values. 165 llvm::APSInt SizeExtended(NumElements, true); 166 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType()); 167 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits, 168 SizeExtended.getBitWidth()) * 2); 169 170 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize)); 171 TotalSize *= SizeExtended; 172 173 return TotalSize.getActiveBits(); 174 } 175 176 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) { 177 unsigned Bits = Context.getTypeSize(Context.getSizeType()); 178 179 // Limit the number of bits in size_t so that maximal bit size fits 64 bit 180 // integer (see PR8256). We can do this as currently there is no hardware 181 // that supports full 64-bit virtual space. 182 if (Bits > 61) 183 Bits = 61; 184 185 return Bits; 186 } 187 188 void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID, 189 const ASTContext &Context, QualType ET, 190 const llvm::APInt &ArraySize, 191 const Expr *SizeExpr, ArraySizeModifier SizeMod, 192 unsigned TypeQuals) { 193 ID.AddPointer(ET.getAsOpaquePtr()); 194 ID.AddInteger(ArraySize.getZExtValue()); 195 ID.AddInteger(SizeMod); 196 ID.AddInteger(TypeQuals); 197 ID.AddBoolean(SizeExpr != nullptr); 198 if (SizeExpr) 199 SizeExpr->Profile(ID, Context, true); 200 } 201 202 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 203 QualType et, QualType can, 204 Expr *e, ArraySizeModifier sm, 205 unsigned tq, 206 SourceRange brackets) 207 : ArrayType(DependentSizedArray, et, can, sm, tq, e), 208 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {} 209 210 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID, 211 const ASTContext &Context, 212 QualType ET, 213 ArraySizeModifier SizeMod, 214 unsigned TypeQuals, 215 Expr *E) { 216 ID.AddPointer(ET.getAsOpaquePtr()); 217 ID.AddInteger(SizeMod); 218 ID.AddInteger(TypeQuals); 219 E->Profile(ID, Context, true); 220 } 221 222 DependentVectorType::DependentVectorType(const ASTContext &Context, 223 QualType ElementType, 224 QualType CanonType, Expr *SizeExpr, 225 SourceLocation Loc, 226 VectorType::VectorKind VecKind) 227 : Type(DependentVector, CanonType, 228 TypeDependence::DependentInstantiation | 229 ElementType->getDependence() | 230 (SizeExpr ? toTypeDependence(SizeExpr->getDependence()) 231 : TypeDependence::None)), 232 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) { 233 VectorTypeBits.VecKind = VecKind; 234 } 235 236 void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID, 237 const ASTContext &Context, 238 QualType ElementType, const Expr *SizeExpr, 239 VectorType::VectorKind VecKind) { 240 ID.AddPointer(ElementType.getAsOpaquePtr()); 241 ID.AddInteger(VecKind); 242 SizeExpr->Profile(ID, Context, true); 243 } 244 245 DependentSizedExtVectorType::DependentSizedExtVectorType( 246 const ASTContext &Context, QualType ElementType, QualType can, 247 Expr *SizeExpr, SourceLocation loc) 248 : Type(DependentSizedExtVector, can, 249 TypeDependence::DependentInstantiation | 250 ElementType->getDependence() | 251 (SizeExpr ? toTypeDependence(SizeExpr->getDependence()) 252 : TypeDependence::None)), 253 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) { 254 } 255 256 void 257 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID, 258 const ASTContext &Context, 259 QualType ElementType, Expr *SizeExpr) { 260 ID.AddPointer(ElementType.getAsOpaquePtr()); 261 SizeExpr->Profile(ID, Context, true); 262 } 263 264 DependentAddressSpaceType::DependentAddressSpaceType(const ASTContext &Context, 265 QualType PointeeType, 266 QualType can, 267 Expr *AddrSpaceExpr, 268 SourceLocation loc) 269 : Type(DependentAddressSpace, can, 270 TypeDependence::DependentInstantiation | 271 PointeeType->getDependence() | 272 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence()) 273 : TypeDependence::None)), 274 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType), 275 loc(loc) {} 276 277 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID, 278 const ASTContext &Context, 279 QualType PointeeType, 280 Expr *AddrSpaceExpr) { 281 ID.AddPointer(PointeeType.getAsOpaquePtr()); 282 AddrSpaceExpr->Profile(ID, Context, true); 283 } 284 285 MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType, 286 const Expr *RowExpr, const Expr *ColumnExpr) 287 : Type(tc, canonType, 288 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent | 289 TypeDependence::Instantiation | 290 (matrixType->isVariablyModifiedType() 291 ? TypeDependence::VariablyModified 292 : TypeDependence::None) | 293 (matrixType->containsUnexpandedParameterPack() || 294 (RowExpr && 295 RowExpr->containsUnexpandedParameterPack()) || 296 (ColumnExpr && 297 ColumnExpr->containsUnexpandedParameterPack()) 298 ? TypeDependence::UnexpandedPack 299 : TypeDependence::None)) 300 : matrixType->getDependence())), 301 ElementType(matrixType) {} 302 303 ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows, 304 unsigned nColumns, QualType canonType) 305 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns, 306 canonType) {} 307 308 ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType, 309 unsigned nRows, unsigned nColumns, 310 QualType canonType) 311 : MatrixType(tc, matrixType, canonType), NumRows(nRows), 312 NumColumns(nColumns) {} 313 314 DependentSizedMatrixType::DependentSizedMatrixType( 315 const ASTContext &CTX, QualType ElementType, QualType CanonicalType, 316 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc) 317 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr, 318 ColumnExpr), 319 Context(CTX), RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {} 320 321 void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID, 322 const ASTContext &CTX, 323 QualType ElementType, Expr *RowExpr, 324 Expr *ColumnExpr) { 325 ID.AddPointer(ElementType.getAsOpaquePtr()); 326 RowExpr->Profile(ID, CTX, true); 327 ColumnExpr->Profile(ID, CTX, true); 328 } 329 330 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType, 331 VectorKind vecKind) 332 : VectorType(Vector, vecType, nElements, canonType, vecKind) {} 333 334 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements, 335 QualType canonType, VectorKind vecKind) 336 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) { 337 VectorTypeBits.VecKind = vecKind; 338 VectorTypeBits.NumElements = nElements; 339 } 340 341 BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits) 342 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned), 343 NumBits(NumBits) {} 344 345 DependentBitIntType::DependentBitIntType(const ASTContext &Context, 346 bool IsUnsigned, Expr *NumBitsExpr) 347 : Type(DependentBitInt, QualType{}, 348 toTypeDependence(NumBitsExpr->getDependence())), 349 Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {} 350 351 bool DependentBitIntType::isUnsigned() const { 352 return ExprAndUnsigned.getInt(); 353 } 354 355 clang::Expr *DependentBitIntType::getNumBitsExpr() const { 356 return ExprAndUnsigned.getPointer(); 357 } 358 359 void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID, 360 const ASTContext &Context, bool IsUnsigned, 361 Expr *NumBitsExpr) { 362 ID.AddBoolean(IsUnsigned); 363 NumBitsExpr->Profile(ID, Context, true); 364 } 365 366 /// getArrayElementTypeNoTypeQual - If this is an array type, return the 367 /// element type of the array, potentially with type qualifiers missing. 368 /// This method should never be used when type qualifiers are meaningful. 369 const Type *Type::getArrayElementTypeNoTypeQual() const { 370 // If this is directly an array type, return it. 371 if (const auto *ATy = dyn_cast<ArrayType>(this)) 372 return ATy->getElementType().getTypePtr(); 373 374 // If the canonical form of this type isn't the right kind, reject it. 375 if (!isa<ArrayType>(CanonicalType)) 376 return nullptr; 377 378 // If this is a typedef for an array type, strip the typedef off without 379 // losing all typedef information. 380 return cast<ArrayType>(getUnqualifiedDesugaredType()) 381 ->getElementType().getTypePtr(); 382 } 383 384 /// getDesugaredType - Return the specified type with any "sugar" removed from 385 /// the type. This takes off typedefs, typeof's etc. If the outer level of 386 /// the type is already concrete, it returns it unmodified. This is similar 387 /// to getting the canonical type, but it doesn't remove *all* typedefs. For 388 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 389 /// concrete. 390 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) { 391 SplitQualType split = getSplitDesugaredType(T); 392 return Context.getQualifiedType(split.Ty, split.Quals); 393 } 394 395 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type, 396 const ASTContext &Context) { 397 SplitQualType split = type.split(); 398 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType(); 399 return Context.getQualifiedType(desugar, split.Quals); 400 } 401 402 // Check that no type class is polymorphic. LLVM style RTTI should be used 403 // instead. If absolutely needed an exception can still be added here by 404 // defining the appropriate macro (but please don't do this). 405 #define TYPE(CLASS, BASE) \ 406 static_assert(!std::is_polymorphic<CLASS##Type>::value, \ 407 #CLASS "Type should not be polymorphic!"); 408 #include "clang/AST/TypeNodes.inc" 409 410 // Check that no type class has a non-trival destructor. Types are 411 // allocated with the BumpPtrAllocator from ASTContext and therefore 412 // their destructor is not executed. 413 // 414 // FIXME: ConstantArrayType is not trivially destructible because of its 415 // APInt member. It should be replaced in favor of ASTContext allocation. 416 #define TYPE(CLASS, BASE) \ 417 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \ 418 std::is_same<CLASS##Type, ConstantArrayType>::value, \ 419 #CLASS "Type should be trivially destructible!"); 420 #include "clang/AST/TypeNodes.inc" 421 422 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const { 423 switch (getTypeClass()) { 424 #define ABSTRACT_TYPE(Class, Parent) 425 #define TYPE(Class, Parent) \ 426 case Type::Class: { \ 427 const auto *ty = cast<Class##Type>(this); \ 428 if (!ty->isSugared()) return QualType(ty, 0); \ 429 return ty->desugar(); \ 430 } 431 #include "clang/AST/TypeNodes.inc" 432 } 433 llvm_unreachable("bad type kind!"); 434 } 435 436 SplitQualType QualType::getSplitDesugaredType(QualType T) { 437 QualifierCollector Qs; 438 439 QualType Cur = T; 440 while (true) { 441 const Type *CurTy = Qs.strip(Cur); 442 switch (CurTy->getTypeClass()) { 443 #define ABSTRACT_TYPE(Class, Parent) 444 #define TYPE(Class, Parent) \ 445 case Type::Class: { \ 446 const auto *Ty = cast<Class##Type>(CurTy); \ 447 if (!Ty->isSugared()) \ 448 return SplitQualType(Ty, Qs); \ 449 Cur = Ty->desugar(); \ 450 break; \ 451 } 452 #include "clang/AST/TypeNodes.inc" 453 } 454 } 455 } 456 457 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) { 458 SplitQualType split = type.split(); 459 460 // All the qualifiers we've seen so far. 461 Qualifiers quals = split.Quals; 462 463 // The last type node we saw with any nodes inside it. 464 const Type *lastTypeWithQuals = split.Ty; 465 466 while (true) { 467 QualType next; 468 469 // Do a single-step desugar, aborting the loop if the type isn't 470 // sugared. 471 switch (split.Ty->getTypeClass()) { 472 #define ABSTRACT_TYPE(Class, Parent) 473 #define TYPE(Class, Parent) \ 474 case Type::Class: { \ 475 const auto *ty = cast<Class##Type>(split.Ty); \ 476 if (!ty->isSugared()) goto done; \ 477 next = ty->desugar(); \ 478 break; \ 479 } 480 #include "clang/AST/TypeNodes.inc" 481 } 482 483 // Otherwise, split the underlying type. If that yields qualifiers, 484 // update the information. 485 split = next.split(); 486 if (!split.Quals.empty()) { 487 lastTypeWithQuals = split.Ty; 488 quals.addConsistentQualifiers(split.Quals); 489 } 490 } 491 492 done: 493 return SplitQualType(lastTypeWithQuals, quals); 494 } 495 496 QualType QualType::IgnoreParens(QualType T) { 497 // FIXME: this seems inherently un-qualifiers-safe. 498 while (const auto *PT = T->getAs<ParenType>()) 499 T = PT->getInnerType(); 500 return T; 501 } 502 503 /// This will check for a T (which should be a Type which can act as 504 /// sugar, such as a TypedefType) by removing any existing sugar until it 505 /// reaches a T or a non-sugared type. 506 template<typename T> static const T *getAsSugar(const Type *Cur) { 507 while (true) { 508 if (const auto *Sugar = dyn_cast<T>(Cur)) 509 return Sugar; 510 switch (Cur->getTypeClass()) { 511 #define ABSTRACT_TYPE(Class, Parent) 512 #define TYPE(Class, Parent) \ 513 case Type::Class: { \ 514 const auto *Ty = cast<Class##Type>(Cur); \ 515 if (!Ty->isSugared()) return 0; \ 516 Cur = Ty->desugar().getTypePtr(); \ 517 break; \ 518 } 519 #include "clang/AST/TypeNodes.inc" 520 } 521 } 522 } 523 524 template <> const TypedefType *Type::getAs() const { 525 return getAsSugar<TypedefType>(this); 526 } 527 528 template <> const TemplateSpecializationType *Type::getAs() const { 529 return getAsSugar<TemplateSpecializationType>(this); 530 } 531 532 template <> const AttributedType *Type::getAs() const { 533 return getAsSugar<AttributedType>(this); 534 } 535 536 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic 537 /// sugar off the given type. This should produce an object of the 538 /// same dynamic type as the canonical type. 539 const Type *Type::getUnqualifiedDesugaredType() const { 540 const Type *Cur = this; 541 542 while (true) { 543 switch (Cur->getTypeClass()) { 544 #define ABSTRACT_TYPE(Class, Parent) 545 #define TYPE(Class, Parent) \ 546 case Class: { \ 547 const auto *Ty = cast<Class##Type>(Cur); \ 548 if (!Ty->isSugared()) return Cur; \ 549 Cur = Ty->desugar().getTypePtr(); \ 550 break; \ 551 } 552 #include "clang/AST/TypeNodes.inc" 553 } 554 } 555 } 556 557 bool Type::isClassType() const { 558 if (const auto *RT = getAs<RecordType>()) 559 return RT->getDecl()->isClass(); 560 return false; 561 } 562 563 bool Type::isStructureType() const { 564 if (const auto *RT = getAs<RecordType>()) 565 return RT->getDecl()->isStruct(); 566 return false; 567 } 568 569 bool Type::isObjCBoxableRecordType() const { 570 if (const auto *RT = getAs<RecordType>()) 571 return RT->getDecl()->hasAttr<ObjCBoxableAttr>(); 572 return false; 573 } 574 575 bool Type::isInterfaceType() const { 576 if (const auto *RT = getAs<RecordType>()) 577 return RT->getDecl()->isInterface(); 578 return false; 579 } 580 581 bool Type::isStructureOrClassType() const { 582 if (const auto *RT = getAs<RecordType>()) { 583 RecordDecl *RD = RT->getDecl(); 584 return RD->isStruct() || RD->isClass() || RD->isInterface(); 585 } 586 return false; 587 } 588 589 bool Type::isVoidPointerType() const { 590 if (const auto *PT = getAs<PointerType>()) 591 return PT->getPointeeType()->isVoidType(); 592 return false; 593 } 594 595 bool Type::isUnionType() const { 596 if (const auto *RT = getAs<RecordType>()) 597 return RT->getDecl()->isUnion(); 598 return false; 599 } 600 601 bool Type::isComplexType() const { 602 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType)) 603 return CT->getElementType()->isFloatingType(); 604 return false; 605 } 606 607 bool Type::isComplexIntegerType() const { 608 // Check for GCC complex integer extension. 609 return getAsComplexIntegerType(); 610 } 611 612 bool Type::isScopedEnumeralType() const { 613 if (const auto *ET = getAs<EnumType>()) 614 return ET->getDecl()->isScoped(); 615 return false; 616 } 617 618 const ComplexType *Type::getAsComplexIntegerType() const { 619 if (const auto *Complex = getAs<ComplexType>()) 620 if (Complex->getElementType()->isIntegerType()) 621 return Complex; 622 return nullptr; 623 } 624 625 QualType Type::getPointeeType() const { 626 if (const auto *PT = getAs<PointerType>()) 627 return PT->getPointeeType(); 628 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 629 return OPT->getPointeeType(); 630 if (const auto *BPT = getAs<BlockPointerType>()) 631 return BPT->getPointeeType(); 632 if (const auto *RT = getAs<ReferenceType>()) 633 return RT->getPointeeType(); 634 if (const auto *MPT = getAs<MemberPointerType>()) 635 return MPT->getPointeeType(); 636 if (const auto *DT = getAs<DecayedType>()) 637 return DT->getPointeeType(); 638 return {}; 639 } 640 641 const RecordType *Type::getAsStructureType() const { 642 // If this is directly a structure type, return it. 643 if (const auto *RT = dyn_cast<RecordType>(this)) { 644 if (RT->getDecl()->isStruct()) 645 return RT; 646 } 647 648 // If the canonical form of this type isn't the right kind, reject it. 649 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) { 650 if (!RT->getDecl()->isStruct()) 651 return nullptr; 652 653 // If this is a typedef for a structure type, strip the typedef off without 654 // losing all typedef information. 655 return cast<RecordType>(getUnqualifiedDesugaredType()); 656 } 657 return nullptr; 658 } 659 660 const RecordType *Type::getAsUnionType() const { 661 // If this is directly a union type, return it. 662 if (const auto *RT = dyn_cast<RecordType>(this)) { 663 if (RT->getDecl()->isUnion()) 664 return RT; 665 } 666 667 // If the canonical form of this type isn't the right kind, reject it. 668 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) { 669 if (!RT->getDecl()->isUnion()) 670 return nullptr; 671 672 // If this is a typedef for a union type, strip the typedef off without 673 // losing all typedef information. 674 return cast<RecordType>(getUnqualifiedDesugaredType()); 675 } 676 677 return nullptr; 678 } 679 680 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx, 681 const ObjCObjectType *&bound) const { 682 bound = nullptr; 683 684 const auto *OPT = getAs<ObjCObjectPointerType>(); 685 if (!OPT) 686 return false; 687 688 // Easy case: id. 689 if (OPT->isObjCIdType()) 690 return true; 691 692 // If it's not a __kindof type, reject it now. 693 if (!OPT->isKindOfType()) 694 return false; 695 696 // If it's Class or qualified Class, it's not an object type. 697 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) 698 return false; 699 700 // Figure out the type bound for the __kindof type. 701 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx) 702 ->getAs<ObjCObjectType>(); 703 return true; 704 } 705 706 bool Type::isObjCClassOrClassKindOfType() const { 707 const auto *OPT = getAs<ObjCObjectPointerType>(); 708 if (!OPT) 709 return false; 710 711 // Easy case: Class. 712 if (OPT->isObjCClassType()) 713 return true; 714 715 // If it's not a __kindof type, reject it now. 716 if (!OPT->isKindOfType()) 717 return false; 718 719 // If it's Class or qualified Class, it's a class __kindof type. 720 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType(); 721 } 722 723 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can, 724 ArrayRef<ObjCProtocolDecl *> protocols) 725 : Type(ObjCTypeParam, can, toSemanticDependence(can->getDependence())), 726 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) { 727 initialize(protocols); 728 } 729 730 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base, 731 ArrayRef<QualType> typeArgs, 732 ArrayRef<ObjCProtocolDecl *> protocols, 733 bool isKindOf) 734 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) { 735 ObjCObjectTypeBits.IsKindOf = isKindOf; 736 737 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size(); 738 assert(getTypeArgsAsWritten().size() == typeArgs.size() && 739 "bitfield overflow in type argument count"); 740 if (!typeArgs.empty()) 741 memcpy(getTypeArgStorage(), typeArgs.data(), 742 typeArgs.size() * sizeof(QualType)); 743 744 for (auto typeArg : typeArgs) { 745 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified); 746 } 747 // Initialize the protocol qualifiers. The protocol storage is known 748 // after we set number of type arguments. 749 initialize(protocols); 750 } 751 752 bool ObjCObjectType::isSpecialized() const { 753 // If we have type arguments written here, the type is specialized. 754 if (ObjCObjectTypeBits.NumTypeArgs > 0) 755 return true; 756 757 // Otherwise, check whether the base type is specialized. 758 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 759 // Terminate when we reach an interface type. 760 if (isa<ObjCInterfaceType>(objcObject)) 761 return false; 762 763 return objcObject->isSpecialized(); 764 } 765 766 // Not specialized. 767 return false; 768 } 769 770 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const { 771 // We have type arguments written on this type. 772 if (isSpecializedAsWritten()) 773 return getTypeArgsAsWritten(); 774 775 // Look at the base type, which might have type arguments. 776 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 777 // Terminate when we reach an interface type. 778 if (isa<ObjCInterfaceType>(objcObject)) 779 return {}; 780 781 return objcObject->getTypeArgs(); 782 } 783 784 // No type arguments. 785 return {}; 786 } 787 788 bool ObjCObjectType::isKindOfType() const { 789 if (isKindOfTypeAsWritten()) 790 return true; 791 792 // Look at the base type, which might have type arguments. 793 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) { 794 // Terminate when we reach an interface type. 795 if (isa<ObjCInterfaceType>(objcObject)) 796 return false; 797 798 return objcObject->isKindOfType(); 799 } 800 801 // Not a "__kindof" type. 802 return false; 803 } 804 805 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals( 806 const ASTContext &ctx) const { 807 if (!isKindOfType() && qual_empty()) 808 return QualType(this, 0); 809 810 // Recursively strip __kindof. 811 SplitQualType splitBaseType = getBaseType().split(); 812 QualType baseType(splitBaseType.Ty, 0); 813 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>()) 814 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx); 815 816 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType, 817 splitBaseType.Quals), 818 getTypeArgsAsWritten(), 819 /*protocols=*/{}, 820 /*isKindOf=*/false); 821 } 822 823 ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const { 824 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl(); 825 if (ObjCInterfaceDecl *Def = Canon->getDefinition()) 826 return Def; 827 return Canon; 828 } 829 830 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals( 831 const ASTContext &ctx) const { 832 if (!isKindOfType() && qual_empty()) 833 return this; 834 835 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx); 836 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>(); 837 } 838 839 namespace { 840 841 /// Visitor used to perform a simple type transformation that does not change 842 /// the semantics of the type. 843 template <typename Derived> 844 struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> { 845 ASTContext &Ctx; 846 847 QualType recurse(QualType type) { 848 // Split out the qualifiers from the type. 849 SplitQualType splitType = type.split(); 850 851 // Visit the type itself. 852 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty); 853 if (result.isNull()) 854 return result; 855 856 // Reconstruct the transformed type by applying the local qualifiers 857 // from the split type. 858 return Ctx.getQualifiedType(result, splitType.Quals); 859 } 860 861 public: 862 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {} 863 864 // None of the clients of this transformation can occur where 865 // there are dependent types, so skip dependent types. 866 #define TYPE(Class, Base) 867 #define DEPENDENT_TYPE(Class, Base) \ 868 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 869 #include "clang/AST/TypeNodes.inc" 870 871 #define TRIVIAL_TYPE_CLASS(Class) \ 872 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); } 873 #define SUGARED_TYPE_CLASS(Class) \ 874 QualType Visit##Class##Type(const Class##Type *T) { \ 875 if (!T->isSugared()) \ 876 return QualType(T, 0); \ 877 QualType desugaredType = recurse(T->desugar()); \ 878 if (desugaredType.isNull()) \ 879 return {}; \ 880 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \ 881 return QualType(T, 0); \ 882 return desugaredType; \ 883 } 884 885 TRIVIAL_TYPE_CLASS(Builtin) 886 887 QualType VisitComplexType(const ComplexType *T) { 888 QualType elementType = recurse(T->getElementType()); 889 if (elementType.isNull()) 890 return {}; 891 892 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 893 return QualType(T, 0); 894 895 return Ctx.getComplexType(elementType); 896 } 897 898 QualType VisitPointerType(const PointerType *T) { 899 QualType pointeeType = recurse(T->getPointeeType()); 900 if (pointeeType.isNull()) 901 return {}; 902 903 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 904 return QualType(T, 0); 905 906 return Ctx.getPointerType(pointeeType); 907 } 908 909 QualType VisitBlockPointerType(const BlockPointerType *T) { 910 QualType pointeeType = recurse(T->getPointeeType()); 911 if (pointeeType.isNull()) 912 return {}; 913 914 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 915 return QualType(T, 0); 916 917 return Ctx.getBlockPointerType(pointeeType); 918 } 919 920 QualType VisitLValueReferenceType(const LValueReferenceType *T) { 921 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 922 if (pointeeType.isNull()) 923 return {}; 924 925 if (pointeeType.getAsOpaquePtr() 926 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 927 return QualType(T, 0); 928 929 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue()); 930 } 931 932 QualType VisitRValueReferenceType(const RValueReferenceType *T) { 933 QualType pointeeType = recurse(T->getPointeeTypeAsWritten()); 934 if (pointeeType.isNull()) 935 return {}; 936 937 if (pointeeType.getAsOpaquePtr() 938 == T->getPointeeTypeAsWritten().getAsOpaquePtr()) 939 return QualType(T, 0); 940 941 return Ctx.getRValueReferenceType(pointeeType); 942 } 943 944 QualType VisitMemberPointerType(const MemberPointerType *T) { 945 QualType pointeeType = recurse(T->getPointeeType()); 946 if (pointeeType.isNull()) 947 return {}; 948 949 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr()) 950 return QualType(T, 0); 951 952 return Ctx.getMemberPointerType(pointeeType, T->getClass()); 953 } 954 955 QualType VisitConstantArrayType(const ConstantArrayType *T) { 956 QualType elementType = recurse(T->getElementType()); 957 if (elementType.isNull()) 958 return {}; 959 960 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 961 return QualType(T, 0); 962 963 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(), 964 T->getSizeModifier(), 965 T->getIndexTypeCVRQualifiers()); 966 } 967 968 QualType VisitVariableArrayType(const VariableArrayType *T) { 969 QualType elementType = recurse(T->getElementType()); 970 if (elementType.isNull()) 971 return {}; 972 973 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 974 return QualType(T, 0); 975 976 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(), 977 T->getSizeModifier(), 978 T->getIndexTypeCVRQualifiers(), 979 T->getBracketsRange()); 980 } 981 982 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) { 983 QualType elementType = recurse(T->getElementType()); 984 if (elementType.isNull()) 985 return {}; 986 987 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 988 return QualType(T, 0); 989 990 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(), 991 T->getIndexTypeCVRQualifiers()); 992 } 993 994 QualType VisitVectorType(const VectorType *T) { 995 QualType elementType = recurse(T->getElementType()); 996 if (elementType.isNull()) 997 return {}; 998 999 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 1000 return QualType(T, 0); 1001 1002 return Ctx.getVectorType(elementType, T->getNumElements(), 1003 T->getVectorKind()); 1004 } 1005 1006 QualType VisitExtVectorType(const ExtVectorType *T) { 1007 QualType elementType = recurse(T->getElementType()); 1008 if (elementType.isNull()) 1009 return {}; 1010 1011 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 1012 return QualType(T, 0); 1013 1014 return Ctx.getExtVectorType(elementType, T->getNumElements()); 1015 } 1016 1017 QualType VisitConstantMatrixType(const ConstantMatrixType *T) { 1018 QualType elementType = recurse(T->getElementType()); 1019 if (elementType.isNull()) 1020 return {}; 1021 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr()) 1022 return QualType(T, 0); 1023 1024 return Ctx.getConstantMatrixType(elementType, T->getNumRows(), 1025 T->getNumColumns()); 1026 } 1027 1028 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 1029 QualType returnType = recurse(T->getReturnType()); 1030 if (returnType.isNull()) 1031 return {}; 1032 1033 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr()) 1034 return QualType(T, 0); 1035 1036 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo()); 1037 } 1038 1039 QualType VisitFunctionProtoType(const FunctionProtoType *T) { 1040 QualType returnType = recurse(T->getReturnType()); 1041 if (returnType.isNull()) 1042 return {}; 1043 1044 // Transform parameter types. 1045 SmallVector<QualType, 4> paramTypes; 1046 bool paramChanged = false; 1047 for (auto paramType : T->getParamTypes()) { 1048 QualType newParamType = recurse(paramType); 1049 if (newParamType.isNull()) 1050 return {}; 1051 1052 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 1053 paramChanged = true; 1054 1055 paramTypes.push_back(newParamType); 1056 } 1057 1058 // Transform extended info. 1059 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo(); 1060 bool exceptionChanged = false; 1061 if (info.ExceptionSpec.Type == EST_Dynamic) { 1062 SmallVector<QualType, 4> exceptionTypes; 1063 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 1064 QualType newExceptionType = recurse(exceptionType); 1065 if (newExceptionType.isNull()) 1066 return {}; 1067 1068 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) 1069 exceptionChanged = true; 1070 1071 exceptionTypes.push_back(newExceptionType); 1072 } 1073 1074 if (exceptionChanged) { 1075 info.ExceptionSpec.Exceptions = 1076 llvm::makeArrayRef(exceptionTypes).copy(Ctx); 1077 } 1078 } 1079 1080 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() && 1081 !paramChanged && !exceptionChanged) 1082 return QualType(T, 0); 1083 1084 return Ctx.getFunctionType(returnType, paramTypes, info); 1085 } 1086 1087 QualType VisitParenType(const ParenType *T) { 1088 QualType innerType = recurse(T->getInnerType()); 1089 if (innerType.isNull()) 1090 return {}; 1091 1092 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr()) 1093 return QualType(T, 0); 1094 1095 return Ctx.getParenType(innerType); 1096 } 1097 1098 SUGARED_TYPE_CLASS(Typedef) 1099 SUGARED_TYPE_CLASS(ObjCTypeParam) 1100 SUGARED_TYPE_CLASS(MacroQualified) 1101 1102 QualType VisitAdjustedType(const AdjustedType *T) { 1103 QualType originalType = recurse(T->getOriginalType()); 1104 if (originalType.isNull()) 1105 return {}; 1106 1107 QualType adjustedType = recurse(T->getAdjustedType()); 1108 if (adjustedType.isNull()) 1109 return {}; 1110 1111 if (originalType.getAsOpaquePtr() 1112 == T->getOriginalType().getAsOpaquePtr() && 1113 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr()) 1114 return QualType(T, 0); 1115 1116 return Ctx.getAdjustedType(originalType, adjustedType); 1117 } 1118 1119 QualType VisitDecayedType(const DecayedType *T) { 1120 QualType originalType = recurse(T->getOriginalType()); 1121 if (originalType.isNull()) 1122 return {}; 1123 1124 if (originalType.getAsOpaquePtr() 1125 == T->getOriginalType().getAsOpaquePtr()) 1126 return QualType(T, 0); 1127 1128 return Ctx.getDecayedType(originalType); 1129 } 1130 1131 SUGARED_TYPE_CLASS(TypeOfExpr) 1132 SUGARED_TYPE_CLASS(TypeOf) 1133 SUGARED_TYPE_CLASS(Decltype) 1134 SUGARED_TYPE_CLASS(UnaryTransform) 1135 TRIVIAL_TYPE_CLASS(Record) 1136 TRIVIAL_TYPE_CLASS(Enum) 1137 1138 // FIXME: Non-trivial to implement, but important for C++ 1139 SUGARED_TYPE_CLASS(Elaborated) 1140 1141 QualType VisitAttributedType(const AttributedType *T) { 1142 QualType modifiedType = recurse(T->getModifiedType()); 1143 if (modifiedType.isNull()) 1144 return {}; 1145 1146 QualType equivalentType = recurse(T->getEquivalentType()); 1147 if (equivalentType.isNull()) 1148 return {}; 1149 1150 if (modifiedType.getAsOpaquePtr() 1151 == T->getModifiedType().getAsOpaquePtr() && 1152 equivalentType.getAsOpaquePtr() 1153 == T->getEquivalentType().getAsOpaquePtr()) 1154 return QualType(T, 0); 1155 1156 return Ctx.getAttributedType(T->getAttrKind(), modifiedType, 1157 equivalentType); 1158 } 1159 1160 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 1161 QualType replacementType = recurse(T->getReplacementType()); 1162 if (replacementType.isNull()) 1163 return {}; 1164 1165 if (replacementType.getAsOpaquePtr() 1166 == T->getReplacementType().getAsOpaquePtr()) 1167 return QualType(T, 0); 1168 1169 return Ctx.getSubstTemplateTypeParmType(T->getReplacedParameter(), 1170 replacementType); 1171 } 1172 1173 // FIXME: Non-trivial to implement, but important for C++ 1174 SUGARED_TYPE_CLASS(TemplateSpecialization) 1175 1176 QualType VisitAutoType(const AutoType *T) { 1177 if (!T->isDeduced()) 1178 return QualType(T, 0); 1179 1180 QualType deducedType = recurse(T->getDeducedType()); 1181 if (deducedType.isNull()) 1182 return {}; 1183 1184 if (deducedType.getAsOpaquePtr() 1185 == T->getDeducedType().getAsOpaquePtr()) 1186 return QualType(T, 0); 1187 1188 return Ctx.getAutoType(deducedType, T->getKeyword(), 1189 T->isDependentType(), /*IsPack=*/false, 1190 T->getTypeConstraintConcept(), 1191 T->getTypeConstraintArguments()); 1192 } 1193 1194 QualType VisitObjCObjectType(const ObjCObjectType *T) { 1195 QualType baseType = recurse(T->getBaseType()); 1196 if (baseType.isNull()) 1197 return {}; 1198 1199 // Transform type arguments. 1200 bool typeArgChanged = false; 1201 SmallVector<QualType, 4> typeArgs; 1202 for (auto typeArg : T->getTypeArgsAsWritten()) { 1203 QualType newTypeArg = recurse(typeArg); 1204 if (newTypeArg.isNull()) 1205 return {}; 1206 1207 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) 1208 typeArgChanged = true; 1209 1210 typeArgs.push_back(newTypeArg); 1211 } 1212 1213 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() && 1214 !typeArgChanged) 1215 return QualType(T, 0); 1216 1217 return Ctx.getObjCObjectType(baseType, typeArgs, 1218 llvm::makeArrayRef(T->qual_begin(), 1219 T->getNumProtocols()), 1220 T->isKindOfTypeAsWritten()); 1221 } 1222 1223 TRIVIAL_TYPE_CLASS(ObjCInterface) 1224 1225 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1226 QualType pointeeType = recurse(T->getPointeeType()); 1227 if (pointeeType.isNull()) 1228 return {}; 1229 1230 if (pointeeType.getAsOpaquePtr() 1231 == T->getPointeeType().getAsOpaquePtr()) 1232 return QualType(T, 0); 1233 1234 return Ctx.getObjCObjectPointerType(pointeeType); 1235 } 1236 1237 QualType VisitAtomicType(const AtomicType *T) { 1238 QualType valueType = recurse(T->getValueType()); 1239 if (valueType.isNull()) 1240 return {}; 1241 1242 if (valueType.getAsOpaquePtr() 1243 == T->getValueType().getAsOpaquePtr()) 1244 return QualType(T, 0); 1245 1246 return Ctx.getAtomicType(valueType); 1247 } 1248 1249 #undef TRIVIAL_TYPE_CLASS 1250 #undef SUGARED_TYPE_CLASS 1251 }; 1252 1253 struct SubstObjCTypeArgsVisitor 1254 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> { 1255 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>; 1256 1257 ArrayRef<QualType> TypeArgs; 1258 ObjCSubstitutionContext SubstContext; 1259 1260 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs, 1261 ObjCSubstitutionContext context) 1262 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {} 1263 1264 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) { 1265 // Replace an Objective-C type parameter reference with the corresponding 1266 // type argument. 1267 ObjCTypeParamDecl *typeParam = OTPTy->getDecl(); 1268 // If we have type arguments, use them. 1269 if (!TypeArgs.empty()) { 1270 QualType argType = TypeArgs[typeParam->getIndex()]; 1271 if (OTPTy->qual_empty()) 1272 return argType; 1273 1274 // Apply protocol lists if exists. 1275 bool hasError; 1276 SmallVector<ObjCProtocolDecl *, 8> protocolsVec; 1277 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end()); 1278 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec; 1279 return Ctx.applyObjCProtocolQualifiers( 1280 argType, protocolsToApply, hasError, true/*allowOnPointerType*/); 1281 } 1282 1283 switch (SubstContext) { 1284 case ObjCSubstitutionContext::Ordinary: 1285 case ObjCSubstitutionContext::Parameter: 1286 case ObjCSubstitutionContext::Superclass: 1287 // Substitute the bound. 1288 return typeParam->getUnderlyingType(); 1289 1290 case ObjCSubstitutionContext::Result: 1291 case ObjCSubstitutionContext::Property: { 1292 // Substitute the __kindof form of the underlying type. 1293 const auto *objPtr = 1294 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>(); 1295 1296 // __kindof types, id, and Class don't need an additional 1297 // __kindof. 1298 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType()) 1299 return typeParam->getUnderlyingType(); 1300 1301 // Add __kindof. 1302 const auto *obj = objPtr->getObjectType(); 1303 QualType resultTy = Ctx.getObjCObjectType( 1304 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(), 1305 /*isKindOf=*/true); 1306 1307 // Rebuild object pointer type. 1308 return Ctx.getObjCObjectPointerType(resultTy); 1309 } 1310 } 1311 llvm_unreachable("Unexpected ObjCSubstitutionContext!"); 1312 } 1313 1314 QualType VisitFunctionType(const FunctionType *funcType) { 1315 // If we have a function type, update the substitution context 1316 // appropriately. 1317 1318 //Substitute result type. 1319 QualType returnType = funcType->getReturnType().substObjCTypeArgs( 1320 Ctx, TypeArgs, ObjCSubstitutionContext::Result); 1321 if (returnType.isNull()) 1322 return {}; 1323 1324 // Handle non-prototyped functions, which only substitute into the result 1325 // type. 1326 if (isa<FunctionNoProtoType>(funcType)) { 1327 // If the return type was unchanged, do nothing. 1328 if (returnType.getAsOpaquePtr() == 1329 funcType->getReturnType().getAsOpaquePtr()) 1330 return BaseType::VisitFunctionType(funcType); 1331 1332 // Otherwise, build a new type. 1333 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo()); 1334 } 1335 1336 const auto *funcProtoType = cast<FunctionProtoType>(funcType); 1337 1338 // Transform parameter types. 1339 SmallVector<QualType, 4> paramTypes; 1340 bool paramChanged = false; 1341 for (auto paramType : funcProtoType->getParamTypes()) { 1342 QualType newParamType = paramType.substObjCTypeArgs( 1343 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter); 1344 if (newParamType.isNull()) 1345 return {}; 1346 1347 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr()) 1348 paramChanged = true; 1349 1350 paramTypes.push_back(newParamType); 1351 } 1352 1353 // Transform extended info. 1354 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo(); 1355 bool exceptionChanged = false; 1356 if (info.ExceptionSpec.Type == EST_Dynamic) { 1357 SmallVector<QualType, 4> exceptionTypes; 1358 for (auto exceptionType : info.ExceptionSpec.Exceptions) { 1359 QualType newExceptionType = exceptionType.substObjCTypeArgs( 1360 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary); 1361 if (newExceptionType.isNull()) 1362 return {}; 1363 1364 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr()) 1365 exceptionChanged = true; 1366 1367 exceptionTypes.push_back(newExceptionType); 1368 } 1369 1370 if (exceptionChanged) { 1371 info.ExceptionSpec.Exceptions = 1372 llvm::makeArrayRef(exceptionTypes).copy(Ctx); 1373 } 1374 } 1375 1376 if (returnType.getAsOpaquePtr() == 1377 funcProtoType->getReturnType().getAsOpaquePtr() && 1378 !paramChanged && !exceptionChanged) 1379 return BaseType::VisitFunctionType(funcType); 1380 1381 return Ctx.getFunctionType(returnType, paramTypes, info); 1382 } 1383 1384 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) { 1385 // Substitute into the type arguments of a specialized Objective-C object 1386 // type. 1387 if (objcObjectType->isSpecializedAsWritten()) { 1388 SmallVector<QualType, 4> newTypeArgs; 1389 bool anyChanged = false; 1390 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) { 1391 QualType newTypeArg = typeArg.substObjCTypeArgs( 1392 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary); 1393 if (newTypeArg.isNull()) 1394 return {}; 1395 1396 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) { 1397 // If we're substituting based on an unspecialized context type, 1398 // produce an unspecialized type. 1399 ArrayRef<ObjCProtocolDecl *> protocols( 1400 objcObjectType->qual_begin(), objcObjectType->getNumProtocols()); 1401 if (TypeArgs.empty() && 1402 SubstContext != ObjCSubstitutionContext::Superclass) { 1403 return Ctx.getObjCObjectType( 1404 objcObjectType->getBaseType(), {}, protocols, 1405 objcObjectType->isKindOfTypeAsWritten()); 1406 } 1407 1408 anyChanged = true; 1409 } 1410 1411 newTypeArgs.push_back(newTypeArg); 1412 } 1413 1414 if (anyChanged) { 1415 ArrayRef<ObjCProtocolDecl *> protocols( 1416 objcObjectType->qual_begin(), objcObjectType->getNumProtocols()); 1417 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs, 1418 protocols, 1419 objcObjectType->isKindOfTypeAsWritten()); 1420 } 1421 } 1422 1423 return BaseType::VisitObjCObjectType(objcObjectType); 1424 } 1425 1426 QualType VisitAttributedType(const AttributedType *attrType) { 1427 QualType newType = BaseType::VisitAttributedType(attrType); 1428 if (newType.isNull()) 1429 return {}; 1430 1431 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr()); 1432 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf) 1433 return newType; 1434 1435 // Find out if it's an Objective-C object or object pointer type; 1436 QualType newEquivType = newAttrType->getEquivalentType(); 1437 const ObjCObjectPointerType *ptrType = 1438 newEquivType->getAs<ObjCObjectPointerType>(); 1439 const ObjCObjectType *objType = ptrType 1440 ? ptrType->getObjectType() 1441 : newEquivType->getAs<ObjCObjectType>(); 1442 if (!objType) 1443 return newType; 1444 1445 // Rebuild the "equivalent" type, which pushes __kindof down into 1446 // the object type. 1447 newEquivType = Ctx.getObjCObjectType( 1448 objType->getBaseType(), objType->getTypeArgsAsWritten(), 1449 objType->getProtocols(), 1450 // There is no need to apply kindof on an unqualified id type. 1451 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true); 1452 1453 // If we started with an object pointer type, rebuild it. 1454 if (ptrType) 1455 newEquivType = Ctx.getObjCObjectPointerType(newEquivType); 1456 1457 // Rebuild the attributed type. 1458 return Ctx.getAttributedType(newAttrType->getAttrKind(), 1459 newAttrType->getModifiedType(), newEquivType); 1460 } 1461 }; 1462 1463 struct StripObjCKindOfTypeVisitor 1464 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> { 1465 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>; 1466 1467 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {} 1468 1469 QualType VisitObjCObjectType(const ObjCObjectType *objType) { 1470 if (!objType->isKindOfType()) 1471 return BaseType::VisitObjCObjectType(objType); 1472 1473 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx); 1474 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(), 1475 objType->getProtocols(), 1476 /*isKindOf=*/false); 1477 } 1478 }; 1479 1480 } // namespace 1481 1482 /// Substitute the given type arguments for Objective-C type 1483 /// parameters within the given type, recursively. 1484 QualType QualType::substObjCTypeArgs(ASTContext &ctx, 1485 ArrayRef<QualType> typeArgs, 1486 ObjCSubstitutionContext context) const { 1487 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context); 1488 return visitor.recurse(*this); 1489 } 1490 1491 QualType QualType::substObjCMemberType(QualType objectType, 1492 const DeclContext *dc, 1493 ObjCSubstitutionContext context) const { 1494 if (auto subs = objectType->getObjCSubstitutions(dc)) 1495 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context); 1496 1497 return *this; 1498 } 1499 1500 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const { 1501 // FIXME: Because ASTContext::getAttributedType() is non-const. 1502 auto &ctx = const_cast<ASTContext &>(constCtx); 1503 StripObjCKindOfTypeVisitor visitor(ctx); 1504 return visitor.recurse(*this); 1505 } 1506 1507 QualType QualType::getAtomicUnqualifiedType() const { 1508 if (const auto AT = getTypePtr()->getAs<AtomicType>()) 1509 return AT->getValueType().getUnqualifiedType(); 1510 return getUnqualifiedType(); 1511 } 1512 1513 Optional<ArrayRef<QualType>> Type::getObjCSubstitutions( 1514 const DeclContext *dc) const { 1515 // Look through method scopes. 1516 if (const auto method = dyn_cast<ObjCMethodDecl>(dc)) 1517 dc = method->getDeclContext(); 1518 1519 // Find the class or category in which the type we're substituting 1520 // was declared. 1521 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc); 1522 const ObjCCategoryDecl *dcCategoryDecl = nullptr; 1523 ObjCTypeParamList *dcTypeParams = nullptr; 1524 if (dcClassDecl) { 1525 // If the class does not have any type parameters, there's no 1526 // substitution to do. 1527 dcTypeParams = dcClassDecl->getTypeParamList(); 1528 if (!dcTypeParams) 1529 return None; 1530 } else { 1531 // If we are in neither a class nor a category, there's no 1532 // substitution to perform. 1533 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc); 1534 if (!dcCategoryDecl) 1535 return None; 1536 1537 // If the category does not have any type parameters, there's no 1538 // substitution to do. 1539 dcTypeParams = dcCategoryDecl->getTypeParamList(); 1540 if (!dcTypeParams) 1541 return None; 1542 1543 dcClassDecl = dcCategoryDecl->getClassInterface(); 1544 if (!dcClassDecl) 1545 return None; 1546 } 1547 assert(dcTypeParams && "No substitutions to perform"); 1548 assert(dcClassDecl && "No class context"); 1549 1550 // Find the underlying object type. 1551 const ObjCObjectType *objectType; 1552 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) { 1553 objectType = objectPointerType->getObjectType(); 1554 } else if (getAs<BlockPointerType>()) { 1555 ASTContext &ctx = dc->getParentASTContext(); 1556 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {}) 1557 ->castAs<ObjCObjectType>(); 1558 } else { 1559 objectType = getAs<ObjCObjectType>(); 1560 } 1561 1562 /// Extract the class from the receiver object type. 1563 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface() 1564 : nullptr; 1565 if (!curClassDecl) { 1566 // If we don't have a context type (e.g., this is "id" or some 1567 // variant thereof), substitute the bounds. 1568 return llvm::ArrayRef<QualType>(); 1569 } 1570 1571 // Follow the superclass chain until we've mapped the receiver type 1572 // to the same class as the context. 1573 while (curClassDecl != dcClassDecl) { 1574 // Map to the superclass type. 1575 QualType superType = objectType->getSuperClassType(); 1576 if (superType.isNull()) { 1577 objectType = nullptr; 1578 break; 1579 } 1580 1581 objectType = superType->castAs<ObjCObjectType>(); 1582 curClassDecl = objectType->getInterface(); 1583 } 1584 1585 // If we don't have a receiver type, or the receiver type does not 1586 // have type arguments, substitute in the defaults. 1587 if (!objectType || objectType->isUnspecialized()) { 1588 return llvm::ArrayRef<QualType>(); 1589 } 1590 1591 // The receiver type has the type arguments we want. 1592 return objectType->getTypeArgs(); 1593 } 1594 1595 bool Type::acceptsObjCTypeParams() const { 1596 if (auto *IfaceT = getAsObjCInterfaceType()) { 1597 if (auto *ID = IfaceT->getInterface()) { 1598 if (ID->getTypeParamList()) 1599 return true; 1600 } 1601 } 1602 1603 return false; 1604 } 1605 1606 void ObjCObjectType::computeSuperClassTypeSlow() const { 1607 // Retrieve the class declaration for this type. If there isn't one 1608 // (e.g., this is some variant of "id" or "Class"), then there is no 1609 // superclass type. 1610 ObjCInterfaceDecl *classDecl = getInterface(); 1611 if (!classDecl) { 1612 CachedSuperClassType.setInt(true); 1613 return; 1614 } 1615 1616 // Extract the superclass type. 1617 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType(); 1618 if (!superClassObjTy) { 1619 CachedSuperClassType.setInt(true); 1620 return; 1621 } 1622 1623 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface(); 1624 if (!superClassDecl) { 1625 CachedSuperClassType.setInt(true); 1626 return; 1627 } 1628 1629 // If the superclass doesn't have type parameters, then there is no 1630 // substitution to perform. 1631 QualType superClassType(superClassObjTy, 0); 1632 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList(); 1633 if (!superClassTypeParams) { 1634 CachedSuperClassType.setPointerAndInt( 1635 superClassType->castAs<ObjCObjectType>(), true); 1636 return; 1637 } 1638 1639 // If the superclass reference is unspecialized, return it. 1640 if (superClassObjTy->isUnspecialized()) { 1641 CachedSuperClassType.setPointerAndInt(superClassObjTy, true); 1642 return; 1643 } 1644 1645 // If the subclass is not parameterized, there aren't any type 1646 // parameters in the superclass reference to substitute. 1647 ObjCTypeParamList *typeParams = classDecl->getTypeParamList(); 1648 if (!typeParams) { 1649 CachedSuperClassType.setPointerAndInt( 1650 superClassType->castAs<ObjCObjectType>(), true); 1651 return; 1652 } 1653 1654 // If the subclass type isn't specialized, return the unspecialized 1655 // superclass. 1656 if (isUnspecialized()) { 1657 QualType unspecializedSuper 1658 = classDecl->getASTContext().getObjCInterfaceType( 1659 superClassObjTy->getInterface()); 1660 CachedSuperClassType.setPointerAndInt( 1661 unspecializedSuper->castAs<ObjCObjectType>(), 1662 true); 1663 return; 1664 } 1665 1666 // Substitute the provided type arguments into the superclass type. 1667 ArrayRef<QualType> typeArgs = getTypeArgs(); 1668 assert(typeArgs.size() == typeParams->size()); 1669 CachedSuperClassType.setPointerAndInt( 1670 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs, 1671 ObjCSubstitutionContext::Superclass) 1672 ->castAs<ObjCObjectType>(), 1673 true); 1674 } 1675 1676 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const { 1677 if (auto interfaceDecl = getObjectType()->getInterface()) { 1678 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl) 1679 ->castAs<ObjCInterfaceType>(); 1680 } 1681 1682 return nullptr; 1683 } 1684 1685 QualType ObjCObjectPointerType::getSuperClassType() const { 1686 QualType superObjectType = getObjectType()->getSuperClassType(); 1687 if (superObjectType.isNull()) 1688 return superObjectType; 1689 1690 ASTContext &ctx = getInterfaceDecl()->getASTContext(); 1691 return ctx.getObjCObjectPointerType(superObjectType); 1692 } 1693 1694 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const { 1695 // There is no sugar for ObjCObjectType's, just return the canonical 1696 // type pointer if it is the right class. There is no typedef information to 1697 // return and these cannot be Address-space qualified. 1698 if (const auto *T = getAs<ObjCObjectType>()) 1699 if (T->getNumProtocols() && T->getInterface()) 1700 return T; 1701 return nullptr; 1702 } 1703 1704 bool Type::isObjCQualifiedInterfaceType() const { 1705 return getAsObjCQualifiedInterfaceType() != nullptr; 1706 } 1707 1708 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const { 1709 // There is no sugar for ObjCQualifiedIdType's, just return the canonical 1710 // type pointer if it is the right class. 1711 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1712 if (OPT->isObjCQualifiedIdType()) 1713 return OPT; 1714 } 1715 return nullptr; 1716 } 1717 1718 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const { 1719 // There is no sugar for ObjCQualifiedClassType's, just return the canonical 1720 // type pointer if it is the right class. 1721 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1722 if (OPT->isObjCQualifiedClassType()) 1723 return OPT; 1724 } 1725 return nullptr; 1726 } 1727 1728 const ObjCObjectType *Type::getAsObjCInterfaceType() const { 1729 if (const auto *OT = getAs<ObjCObjectType>()) { 1730 if (OT->getInterface()) 1731 return OT; 1732 } 1733 return nullptr; 1734 } 1735 1736 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const { 1737 if (const auto *OPT = getAs<ObjCObjectPointerType>()) { 1738 if (OPT->getInterfaceType()) 1739 return OPT; 1740 } 1741 return nullptr; 1742 } 1743 1744 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const { 1745 QualType PointeeType; 1746 if (const auto *PT = getAs<PointerType>()) 1747 PointeeType = PT->getPointeeType(); 1748 else if (const auto *RT = getAs<ReferenceType>()) 1749 PointeeType = RT->getPointeeType(); 1750 else 1751 return nullptr; 1752 1753 if (const auto *RT = PointeeType->getAs<RecordType>()) 1754 return dyn_cast<CXXRecordDecl>(RT->getDecl()); 1755 1756 return nullptr; 1757 } 1758 1759 CXXRecordDecl *Type::getAsCXXRecordDecl() const { 1760 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl()); 1761 } 1762 1763 RecordDecl *Type::getAsRecordDecl() const { 1764 return dyn_cast_or_null<RecordDecl>(getAsTagDecl()); 1765 } 1766 1767 TagDecl *Type::getAsTagDecl() const { 1768 if (const auto *TT = getAs<TagType>()) 1769 return TT->getDecl(); 1770 if (const auto *Injected = getAs<InjectedClassNameType>()) 1771 return Injected->getDecl(); 1772 1773 return nullptr; 1774 } 1775 1776 bool Type::hasAttr(attr::Kind AK) const { 1777 const Type *Cur = this; 1778 while (const auto *AT = Cur->getAs<AttributedType>()) { 1779 if (AT->getAttrKind() == AK) 1780 return true; 1781 Cur = AT->getEquivalentType().getTypePtr(); 1782 } 1783 return false; 1784 } 1785 1786 namespace { 1787 1788 class GetContainedDeducedTypeVisitor : 1789 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> { 1790 bool Syntactic; 1791 1792 public: 1793 GetContainedDeducedTypeVisitor(bool Syntactic = false) 1794 : Syntactic(Syntactic) {} 1795 1796 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit; 1797 1798 Type *Visit(QualType T) { 1799 if (T.isNull()) 1800 return nullptr; 1801 return Visit(T.getTypePtr()); 1802 } 1803 1804 // The deduced type itself. 1805 Type *VisitDeducedType(const DeducedType *AT) { 1806 return const_cast<DeducedType*>(AT); 1807 } 1808 1809 // Only these types can contain the desired 'auto' type. 1810 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 1811 return Visit(T->getReplacementType()); 1812 } 1813 1814 Type *VisitElaboratedType(const ElaboratedType *T) { 1815 return Visit(T->getNamedType()); 1816 } 1817 1818 Type *VisitPointerType(const PointerType *T) { 1819 return Visit(T->getPointeeType()); 1820 } 1821 1822 Type *VisitBlockPointerType(const BlockPointerType *T) { 1823 return Visit(T->getPointeeType()); 1824 } 1825 1826 Type *VisitReferenceType(const ReferenceType *T) { 1827 return Visit(T->getPointeeTypeAsWritten()); 1828 } 1829 1830 Type *VisitMemberPointerType(const MemberPointerType *T) { 1831 return Visit(T->getPointeeType()); 1832 } 1833 1834 Type *VisitArrayType(const ArrayType *T) { 1835 return Visit(T->getElementType()); 1836 } 1837 1838 Type *VisitDependentSizedExtVectorType( 1839 const DependentSizedExtVectorType *T) { 1840 return Visit(T->getElementType()); 1841 } 1842 1843 Type *VisitVectorType(const VectorType *T) { 1844 return Visit(T->getElementType()); 1845 } 1846 1847 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) { 1848 return Visit(T->getElementType()); 1849 } 1850 1851 Type *VisitConstantMatrixType(const ConstantMatrixType *T) { 1852 return Visit(T->getElementType()); 1853 } 1854 1855 Type *VisitFunctionProtoType(const FunctionProtoType *T) { 1856 if (Syntactic && T->hasTrailingReturn()) 1857 return const_cast<FunctionProtoType*>(T); 1858 return VisitFunctionType(T); 1859 } 1860 1861 Type *VisitFunctionType(const FunctionType *T) { 1862 return Visit(T->getReturnType()); 1863 } 1864 1865 Type *VisitParenType(const ParenType *T) { 1866 return Visit(T->getInnerType()); 1867 } 1868 1869 Type *VisitAttributedType(const AttributedType *T) { 1870 return Visit(T->getModifiedType()); 1871 } 1872 1873 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) { 1874 return Visit(T->getUnderlyingType()); 1875 } 1876 1877 Type *VisitAdjustedType(const AdjustedType *T) { 1878 return Visit(T->getOriginalType()); 1879 } 1880 1881 Type *VisitPackExpansionType(const PackExpansionType *T) { 1882 return Visit(T->getPattern()); 1883 } 1884 }; 1885 1886 } // namespace 1887 1888 DeducedType *Type::getContainedDeducedType() const { 1889 return cast_or_null<DeducedType>( 1890 GetContainedDeducedTypeVisitor().Visit(this)); 1891 } 1892 1893 bool Type::hasAutoForTrailingReturnType() const { 1894 return isa_and_nonnull<FunctionType>( 1895 GetContainedDeducedTypeVisitor(true).Visit(this)); 1896 } 1897 1898 bool Type::hasIntegerRepresentation() const { 1899 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 1900 return VT->getElementType()->isIntegerType(); 1901 if (CanonicalType->isVLSTBuiltinType()) { 1902 const auto *VT = cast<BuiltinType>(CanonicalType); 1903 return VT->getKind() == BuiltinType::SveBool || 1904 (VT->getKind() >= BuiltinType::SveInt8 && 1905 VT->getKind() <= BuiltinType::SveUint64); 1906 } 1907 1908 return isIntegerType(); 1909 } 1910 1911 /// Determine whether this type is an integral type. 1912 /// 1913 /// This routine determines whether the given type is an integral type per 1914 /// C++ [basic.fundamental]p7. Although the C standard does not define the 1915 /// term "integral type", it has a similar term "integer type", and in C++ 1916 /// the two terms are equivalent. However, C's "integer type" includes 1917 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext 1918 /// parameter is used to determine whether we should be following the C or 1919 /// C++ rules when determining whether this type is an integral/integer type. 1920 /// 1921 /// For cases where C permits "an integer type" and C++ permits "an integral 1922 /// type", use this routine. 1923 /// 1924 /// For cases where C permits "an integer type" and C++ permits "an integral 1925 /// or enumeration type", use \c isIntegralOrEnumerationType() instead. 1926 /// 1927 /// \param Ctx The context in which this type occurs. 1928 /// 1929 /// \returns true if the type is considered an integral type, false otherwise. 1930 bool Type::isIntegralType(const ASTContext &Ctx) const { 1931 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1932 return BT->getKind() >= BuiltinType::Bool && 1933 BT->getKind() <= BuiltinType::Int128; 1934 1935 // Complete enum types are integral in C. 1936 if (!Ctx.getLangOpts().CPlusPlus) 1937 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 1938 return ET->getDecl()->isComplete(); 1939 1940 return isBitIntType(); 1941 } 1942 1943 bool Type::isIntegralOrUnscopedEnumerationType() const { 1944 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1945 return BT->getKind() >= BuiltinType::Bool && 1946 BT->getKind() <= BuiltinType::Int128; 1947 1948 if (isBitIntType()) 1949 return true; 1950 1951 return isUnscopedEnumerationType(); 1952 } 1953 1954 bool Type::isUnscopedEnumerationType() const { 1955 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 1956 return !ET->getDecl()->isScoped(); 1957 1958 return false; 1959 } 1960 1961 bool Type::isCharType() const { 1962 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1963 return BT->getKind() == BuiltinType::Char_U || 1964 BT->getKind() == BuiltinType::UChar || 1965 BT->getKind() == BuiltinType::Char_S || 1966 BT->getKind() == BuiltinType::SChar; 1967 return false; 1968 } 1969 1970 bool Type::isWideCharType() const { 1971 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1972 return BT->getKind() == BuiltinType::WChar_S || 1973 BT->getKind() == BuiltinType::WChar_U; 1974 return false; 1975 } 1976 1977 bool Type::isChar8Type() const { 1978 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) 1979 return BT->getKind() == BuiltinType::Char8; 1980 return false; 1981 } 1982 1983 bool Type::isChar16Type() const { 1984 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1985 return BT->getKind() == BuiltinType::Char16; 1986 return false; 1987 } 1988 1989 bool Type::isChar32Type() const { 1990 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 1991 return BT->getKind() == BuiltinType::Char32; 1992 return false; 1993 } 1994 1995 /// Determine whether this type is any of the built-in character 1996 /// types. 1997 bool Type::isAnyCharacterType() const { 1998 const auto *BT = dyn_cast<BuiltinType>(CanonicalType); 1999 if (!BT) return false; 2000 switch (BT->getKind()) { 2001 default: return false; 2002 case BuiltinType::Char_U: 2003 case BuiltinType::UChar: 2004 case BuiltinType::WChar_U: 2005 case BuiltinType::Char8: 2006 case BuiltinType::Char16: 2007 case BuiltinType::Char32: 2008 case BuiltinType::Char_S: 2009 case BuiltinType::SChar: 2010 case BuiltinType::WChar_S: 2011 return true; 2012 } 2013 } 2014 2015 /// isSignedIntegerType - Return true if this is an integer type that is 2016 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 2017 /// an enum decl which has a signed representation 2018 bool Type::isSignedIntegerType() const { 2019 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2020 return BT->getKind() >= BuiltinType::Char_S && 2021 BT->getKind() <= BuiltinType::Int128; 2022 } 2023 2024 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 2025 // Incomplete enum types are not treated as integer types. 2026 // FIXME: In C++, enum types are never integer types. 2027 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 2028 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 2029 } 2030 2031 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType)) 2032 return IT->isSigned(); 2033 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType)) 2034 return IT->isSigned(); 2035 2036 return false; 2037 } 2038 2039 bool Type::isSignedIntegerOrEnumerationType() const { 2040 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2041 return BT->getKind() >= BuiltinType::Char_S && 2042 BT->getKind() <= BuiltinType::Int128; 2043 } 2044 2045 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2046 if (ET->getDecl()->isComplete()) 2047 return ET->getDecl()->getIntegerType()->isSignedIntegerType(); 2048 } 2049 2050 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType)) 2051 return IT->isSigned(); 2052 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType)) 2053 return IT->isSigned(); 2054 2055 return false; 2056 } 2057 2058 bool Type::hasSignedIntegerRepresentation() const { 2059 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2060 return VT->getElementType()->isSignedIntegerOrEnumerationType(); 2061 else 2062 return isSignedIntegerOrEnumerationType(); 2063 } 2064 2065 /// isUnsignedIntegerType - Return true if this is an integer type that is 2066 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum 2067 /// decl which has an unsigned representation 2068 bool Type::isUnsignedIntegerType() const { 2069 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2070 return BT->getKind() >= BuiltinType::Bool && 2071 BT->getKind() <= BuiltinType::UInt128; 2072 } 2073 2074 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2075 // Incomplete enum types are not treated as integer types. 2076 // FIXME: In C++, enum types are never integer types. 2077 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 2078 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 2079 } 2080 2081 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType)) 2082 return IT->isUnsigned(); 2083 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType)) 2084 return IT->isUnsigned(); 2085 2086 return false; 2087 } 2088 2089 bool Type::isUnsignedIntegerOrEnumerationType() const { 2090 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 2091 return BT->getKind() >= BuiltinType::Bool && 2092 BT->getKind() <= BuiltinType::UInt128; 2093 } 2094 2095 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) { 2096 if (ET->getDecl()->isComplete()) 2097 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType(); 2098 } 2099 2100 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType)) 2101 return IT->isUnsigned(); 2102 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType)) 2103 return IT->isUnsigned(); 2104 2105 return false; 2106 } 2107 2108 bool Type::hasUnsignedIntegerRepresentation() const { 2109 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2110 return VT->getElementType()->isUnsignedIntegerOrEnumerationType(); 2111 if (const auto *VT = dyn_cast<MatrixType>(CanonicalType)) 2112 return VT->getElementType()->isUnsignedIntegerOrEnumerationType(); 2113 if (CanonicalType->isVLSTBuiltinType()) { 2114 const auto *VT = cast<BuiltinType>(CanonicalType); 2115 return VT->getKind() >= BuiltinType::SveUint8 && 2116 VT->getKind() <= BuiltinType::SveUint64; 2117 } 2118 return isUnsignedIntegerOrEnumerationType(); 2119 } 2120 2121 bool Type::isFloatingType() const { 2122 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2123 return BT->getKind() >= BuiltinType::Half && 2124 BT->getKind() <= BuiltinType::Ibm128; 2125 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType)) 2126 return CT->getElementType()->isFloatingType(); 2127 return false; 2128 } 2129 2130 bool Type::hasFloatingRepresentation() const { 2131 if (const auto *VT = dyn_cast<VectorType>(CanonicalType)) 2132 return VT->getElementType()->isFloatingType(); 2133 else 2134 return isFloatingType(); 2135 } 2136 2137 bool Type::isRealFloatingType() const { 2138 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2139 return BT->isFloatingPoint(); 2140 return false; 2141 } 2142 2143 bool Type::isRealType() const { 2144 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2145 return BT->getKind() >= BuiltinType::Bool && 2146 BT->getKind() <= BuiltinType::Ibm128; 2147 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 2148 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped(); 2149 return isBitIntType(); 2150 } 2151 2152 bool Type::isArithmeticType() const { 2153 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 2154 return BT->getKind() >= BuiltinType::Bool && 2155 BT->getKind() <= BuiltinType::Ibm128 && 2156 BT->getKind() != BuiltinType::BFloat16; 2157 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 2158 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2). 2159 // If a body isn't seen by the time we get here, return false. 2160 // 2161 // C++0x: Enumerations are not arithmetic types. For now, just return 2162 // false for scoped enumerations since that will disable any 2163 // unwanted implicit conversions. 2164 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete(); 2165 return isa<ComplexType>(CanonicalType) || isBitIntType(); 2166 } 2167 2168 Type::ScalarTypeKind Type::getScalarTypeKind() const { 2169 assert(isScalarType()); 2170 2171 const Type *T = CanonicalType.getTypePtr(); 2172 if (const auto *BT = dyn_cast<BuiltinType>(T)) { 2173 if (BT->getKind() == BuiltinType::Bool) return STK_Bool; 2174 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer; 2175 if (BT->isInteger()) return STK_Integral; 2176 if (BT->isFloatingPoint()) return STK_Floating; 2177 if (BT->isFixedPointType()) return STK_FixedPoint; 2178 llvm_unreachable("unknown scalar builtin type"); 2179 } else if (isa<PointerType>(T)) { 2180 return STK_CPointer; 2181 } else if (isa<BlockPointerType>(T)) { 2182 return STK_BlockPointer; 2183 } else if (isa<ObjCObjectPointerType>(T)) { 2184 return STK_ObjCObjectPointer; 2185 } else if (isa<MemberPointerType>(T)) { 2186 return STK_MemberPointer; 2187 } else if (isa<EnumType>(T)) { 2188 assert(cast<EnumType>(T)->getDecl()->isComplete()); 2189 return STK_Integral; 2190 } else if (const auto *CT = dyn_cast<ComplexType>(T)) { 2191 if (CT->getElementType()->isRealFloatingType()) 2192 return STK_FloatingComplex; 2193 return STK_IntegralComplex; 2194 } else if (isBitIntType()) { 2195 return STK_Integral; 2196 } 2197 2198 llvm_unreachable("unknown scalar type"); 2199 } 2200 2201 /// Determines whether the type is a C++ aggregate type or C 2202 /// aggregate or union type. 2203 /// 2204 /// An aggregate type is an array or a class type (struct, union, or 2205 /// class) that has no user-declared constructors, no private or 2206 /// protected non-static data members, no base classes, and no virtual 2207 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type 2208 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also 2209 /// includes union types. 2210 bool Type::isAggregateType() const { 2211 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) { 2212 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl())) 2213 return ClassDecl->isAggregate(); 2214 2215 return true; 2216 } 2217 2218 return isa<ArrayType>(CanonicalType); 2219 } 2220 2221 /// isConstantSizeType - Return true if this is not a variable sized type, 2222 /// according to the rules of C99 6.7.5p3. It is not legal to call this on 2223 /// incomplete types or dependent types. 2224 bool Type::isConstantSizeType() const { 2225 assert(!isIncompleteType() && "This doesn't make sense for incomplete types"); 2226 assert(!isDependentType() && "This doesn't make sense for dependent types"); 2227 // The VAT must have a size, as it is known to be complete. 2228 return !isa<VariableArrayType>(CanonicalType); 2229 } 2230 2231 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1) 2232 /// - a type that can describe objects, but which lacks information needed to 2233 /// determine its size. 2234 bool Type::isIncompleteType(NamedDecl **Def) const { 2235 if (Def) 2236 *Def = nullptr; 2237 2238 switch (CanonicalType->getTypeClass()) { 2239 default: return false; 2240 case Builtin: 2241 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never 2242 // be completed. 2243 return isVoidType(); 2244 case Enum: { 2245 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl(); 2246 if (Def) 2247 *Def = EnumD; 2248 return !EnumD->isComplete(); 2249 } 2250 case Record: { 2251 // A tagged type (struct/union/enum/class) is incomplete if the decl is a 2252 // forward declaration, but not a full definition (C99 6.2.5p22). 2253 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl(); 2254 if (Def) 2255 *Def = Rec; 2256 return !Rec->isCompleteDefinition(); 2257 } 2258 case ConstantArray: 2259 case VariableArray: 2260 // An array is incomplete if its element type is incomplete 2261 // (C++ [dcl.array]p1). 2262 // We don't handle dependent-sized arrays (dependent types are never treated 2263 // as incomplete). 2264 return cast<ArrayType>(CanonicalType)->getElementType() 2265 ->isIncompleteType(Def); 2266 case IncompleteArray: 2267 // An array of unknown size is an incomplete type (C99 6.2.5p22). 2268 return true; 2269 case MemberPointer: { 2270 // Member pointers in the MS ABI have special behavior in 2271 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl 2272 // to indicate which inheritance model to use. 2273 auto *MPTy = cast<MemberPointerType>(CanonicalType); 2274 const Type *ClassTy = MPTy->getClass(); 2275 // Member pointers with dependent class types don't get special treatment. 2276 if (ClassTy->isDependentType()) 2277 return false; 2278 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl(); 2279 ASTContext &Context = RD->getASTContext(); 2280 // Member pointers not in the MS ABI don't get special treatment. 2281 if (!Context.getTargetInfo().getCXXABI().isMicrosoft()) 2282 return false; 2283 // The inheritance attribute might only be present on the most recent 2284 // CXXRecordDecl, use that one. 2285 RD = RD->getMostRecentNonInjectedDecl(); 2286 // Nothing interesting to do if the inheritance attribute is already set. 2287 if (RD->hasAttr<MSInheritanceAttr>()) 2288 return false; 2289 return true; 2290 } 2291 case ObjCObject: 2292 return cast<ObjCObjectType>(CanonicalType)->getBaseType() 2293 ->isIncompleteType(Def); 2294 case ObjCInterface: { 2295 // ObjC interfaces are incomplete if they are @class, not @interface. 2296 ObjCInterfaceDecl *Interface 2297 = cast<ObjCInterfaceType>(CanonicalType)->getDecl(); 2298 if (Def) 2299 *Def = Interface; 2300 return !Interface->hasDefinition(); 2301 } 2302 } 2303 } 2304 2305 bool Type::isSizelessBuiltinType() const { 2306 if (const BuiltinType *BT = getAs<BuiltinType>()) { 2307 switch (BT->getKind()) { 2308 // SVE Types 2309 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 2310 #include "clang/Basic/AArch64SVEACLETypes.def" 2311 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 2312 #include "clang/Basic/RISCVVTypes.def" 2313 return true; 2314 default: 2315 return false; 2316 } 2317 } 2318 return false; 2319 } 2320 2321 bool Type::isSizelessType() const { return isSizelessBuiltinType(); } 2322 2323 bool Type::isVLSTBuiltinType() const { 2324 if (const BuiltinType *BT = getAs<BuiltinType>()) { 2325 switch (BT->getKind()) { 2326 case BuiltinType::SveInt8: 2327 case BuiltinType::SveInt16: 2328 case BuiltinType::SveInt32: 2329 case BuiltinType::SveInt64: 2330 case BuiltinType::SveUint8: 2331 case BuiltinType::SveUint16: 2332 case BuiltinType::SveUint32: 2333 case BuiltinType::SveUint64: 2334 case BuiltinType::SveFloat16: 2335 case BuiltinType::SveFloat32: 2336 case BuiltinType::SveFloat64: 2337 case BuiltinType::SveBFloat16: 2338 case BuiltinType::SveBool: 2339 return true; 2340 default: 2341 return false; 2342 } 2343 } 2344 return false; 2345 } 2346 2347 QualType Type::getSveEltType(const ASTContext &Ctx) const { 2348 assert(isVLSTBuiltinType() && "unsupported type!"); 2349 2350 const BuiltinType *BTy = getAs<BuiltinType>(); 2351 if (BTy->getKind() == BuiltinType::SveBool) 2352 // Represent predicates as i8 rather than i1 to avoid any layout issues. 2353 // The type is bitcasted to a scalable predicate type when casting between 2354 // scalable and fixed-length vectors. 2355 return Ctx.UnsignedCharTy; 2356 else 2357 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType; 2358 } 2359 2360 bool QualType::isPODType(const ASTContext &Context) const { 2361 // C++11 has a more relaxed definition of POD. 2362 if (Context.getLangOpts().CPlusPlus11) 2363 return isCXX11PODType(Context); 2364 2365 return isCXX98PODType(Context); 2366 } 2367 2368 bool QualType::isCXX98PODType(const ASTContext &Context) const { 2369 // The compiler shouldn't query this for incomplete types, but the user might. 2370 // We return false for that case. Except for incomplete arrays of PODs, which 2371 // are PODs according to the standard. 2372 if (isNull()) 2373 return false; 2374 2375 if ((*this)->isIncompleteArrayType()) 2376 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2377 2378 if ((*this)->isIncompleteType()) 2379 return false; 2380 2381 if (hasNonTrivialObjCLifetime()) 2382 return false; 2383 2384 QualType CanonicalType = getTypePtr()->CanonicalType; 2385 switch (CanonicalType->getTypeClass()) { 2386 // Everything not explicitly mentioned is not POD. 2387 default: return false; 2388 case Type::VariableArray: 2389 case Type::ConstantArray: 2390 // IncompleteArray is handled above. 2391 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2392 2393 case Type::ObjCObjectPointer: 2394 case Type::BlockPointer: 2395 case Type::Builtin: 2396 case Type::Complex: 2397 case Type::Pointer: 2398 case Type::MemberPointer: 2399 case Type::Vector: 2400 case Type::ExtVector: 2401 case Type::BitInt: 2402 return true; 2403 2404 case Type::Enum: 2405 return true; 2406 2407 case Type::Record: 2408 if (const auto *ClassDecl = 2409 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 2410 return ClassDecl->isPOD(); 2411 2412 // C struct/union is POD. 2413 return true; 2414 } 2415 } 2416 2417 bool QualType::isTrivialType(const ASTContext &Context) const { 2418 // The compiler shouldn't query this for incomplete types, but the user might. 2419 // We return false for that case. Except for incomplete arrays of PODs, which 2420 // are PODs according to the standard. 2421 if (isNull()) 2422 return false; 2423 2424 if ((*this)->isArrayType()) 2425 return Context.getBaseElementType(*this).isTrivialType(Context); 2426 2427 if ((*this)->isSizelessBuiltinType()) 2428 return true; 2429 2430 // Return false for incomplete types after skipping any incomplete array 2431 // types which are expressly allowed by the standard and thus our API. 2432 if ((*this)->isIncompleteType()) 2433 return false; 2434 2435 if (hasNonTrivialObjCLifetime()) 2436 return false; 2437 2438 QualType CanonicalType = getTypePtr()->CanonicalType; 2439 if (CanonicalType->isDependentType()) 2440 return false; 2441 2442 // C++0x [basic.types]p9: 2443 // Scalar types, trivial class types, arrays of such types, and 2444 // cv-qualified versions of these types are collectively called trivial 2445 // types. 2446 2447 // As an extension, Clang treats vector types as Scalar types. 2448 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2449 return true; 2450 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2451 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2452 // C++11 [class]p6: 2453 // A trivial class is a class that has a default constructor, 2454 // has no non-trivial default constructors, and is trivially 2455 // copyable. 2456 return ClassDecl->hasDefaultConstructor() && 2457 !ClassDecl->hasNonTrivialDefaultConstructor() && 2458 ClassDecl->isTriviallyCopyable(); 2459 } 2460 2461 return true; 2462 } 2463 2464 // No other types can match. 2465 return false; 2466 } 2467 2468 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { 2469 if ((*this)->isArrayType()) 2470 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context); 2471 2472 if (hasNonTrivialObjCLifetime()) 2473 return false; 2474 2475 // C++11 [basic.types]p9 - See Core 2094 2476 // Scalar types, trivially copyable class types, arrays of such types, and 2477 // cv-qualified versions of these types are collectively 2478 // called trivially copyable types. 2479 2480 QualType CanonicalType = getCanonicalType(); 2481 if (CanonicalType->isDependentType()) 2482 return false; 2483 2484 if (CanonicalType->isSizelessBuiltinType()) 2485 return true; 2486 2487 // Return false for incomplete types after skipping any incomplete array types 2488 // which are expressly allowed by the standard and thus our API. 2489 if (CanonicalType->isIncompleteType()) 2490 return false; 2491 2492 // As an extension, Clang treats vector types as Scalar types. 2493 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2494 return true; 2495 2496 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2497 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2498 if (!ClassDecl->isTriviallyCopyable()) return false; 2499 } 2500 2501 return true; 2502 } 2503 2504 // No other types can match. 2505 return false; 2506 } 2507 2508 bool QualType::isTriviallyRelocatableType(const ASTContext &Context) const { 2509 QualType BaseElementType = Context.getBaseElementType(*this); 2510 2511 if (BaseElementType->isIncompleteType()) { 2512 return false; 2513 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) { 2514 return RD->canPassInRegisters(); 2515 } else { 2516 switch (isNonTrivialToPrimitiveDestructiveMove()) { 2517 case PCK_Trivial: 2518 return !isDestructedType(); 2519 case PCK_ARCStrong: 2520 return true; 2521 default: 2522 return false; 2523 } 2524 } 2525 } 2526 2527 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const { 2528 return !Context.getLangOpts().ObjCAutoRefCount && 2529 Context.getLangOpts().ObjCWeak && 2530 getObjCLifetime() != Qualifiers::OCL_Weak; 2531 } 2532 2533 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) { 2534 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion(); 2535 } 2536 2537 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) { 2538 return RD->hasNonTrivialToPrimitiveDestructCUnion(); 2539 } 2540 2541 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) { 2542 return RD->hasNonTrivialToPrimitiveCopyCUnion(); 2543 } 2544 2545 QualType::PrimitiveDefaultInitializeKind 2546 QualType::isNonTrivialToPrimitiveDefaultInitialize() const { 2547 if (const auto *RT = 2548 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2549 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) 2550 return PDIK_Struct; 2551 2552 switch (getQualifiers().getObjCLifetime()) { 2553 case Qualifiers::OCL_Strong: 2554 return PDIK_ARCStrong; 2555 case Qualifiers::OCL_Weak: 2556 return PDIK_ARCWeak; 2557 default: 2558 return PDIK_Trivial; 2559 } 2560 } 2561 2562 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const { 2563 if (const auto *RT = 2564 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2565 if (RT->getDecl()->isNonTrivialToPrimitiveCopy()) 2566 return PCK_Struct; 2567 2568 Qualifiers Qs = getQualifiers(); 2569 switch (Qs.getObjCLifetime()) { 2570 case Qualifiers::OCL_Strong: 2571 return PCK_ARCStrong; 2572 case Qualifiers::OCL_Weak: 2573 return PCK_ARCWeak; 2574 default: 2575 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial; 2576 } 2577 } 2578 2579 QualType::PrimitiveCopyKind 2580 QualType::isNonTrivialToPrimitiveDestructiveMove() const { 2581 return isNonTrivialToPrimitiveCopy(); 2582 } 2583 2584 bool Type::isLiteralType(const ASTContext &Ctx) const { 2585 if (isDependentType()) 2586 return false; 2587 2588 // C++1y [basic.types]p10: 2589 // A type is a literal type if it is: 2590 // -- cv void; or 2591 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2592 return true; 2593 2594 // C++11 [basic.types]p10: 2595 // A type is a literal type if it is: 2596 // [...] 2597 // -- an array of literal type other than an array of runtime bound; or 2598 if (isVariableArrayType()) 2599 return false; 2600 const Type *BaseTy = getBaseElementTypeUnsafe(); 2601 assert(BaseTy && "NULL element type"); 2602 2603 // Return false for incomplete types after skipping any incomplete array 2604 // types; those are expressly allowed by the standard and thus our API. 2605 if (BaseTy->isIncompleteType()) 2606 return false; 2607 2608 // C++11 [basic.types]p10: 2609 // A type is a literal type if it is: 2610 // -- a scalar type; or 2611 // As an extension, Clang treats vector types and complex types as 2612 // literal types. 2613 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2614 BaseTy->isAnyComplexType()) 2615 return true; 2616 // -- a reference type; or 2617 if (BaseTy->isReferenceType()) 2618 return true; 2619 // -- a class type that has all of the following properties: 2620 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2621 // -- a trivial destructor, 2622 // -- every constructor call and full-expression in the 2623 // brace-or-equal-initializers for non-static data members (if any) 2624 // is a constant expression, 2625 // -- it is an aggregate type or has at least one constexpr 2626 // constructor or constructor template that is not a copy or move 2627 // constructor, and 2628 // -- all non-static data members and base classes of literal types 2629 // 2630 // We resolve DR1361 by ignoring the second bullet. 2631 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2632 return ClassDecl->isLiteral(); 2633 2634 return true; 2635 } 2636 2637 // We treat _Atomic T as a literal type if T is a literal type. 2638 if (const auto *AT = BaseTy->getAs<AtomicType>()) 2639 return AT->getValueType()->isLiteralType(Ctx); 2640 2641 // If this type hasn't been deduced yet, then conservatively assume that 2642 // it'll work out to be a literal type. 2643 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2644 return true; 2645 2646 return false; 2647 } 2648 2649 bool Type::isStructuralType() const { 2650 // C++20 [temp.param]p6: 2651 // A structural type is one of the following: 2652 // -- a scalar type; or 2653 // -- a vector type [Clang extension]; or 2654 if (isScalarType() || isVectorType()) 2655 return true; 2656 // -- an lvalue reference type; or 2657 if (isLValueReferenceType()) 2658 return true; 2659 // -- a literal class type [...under some conditions] 2660 if (const CXXRecordDecl *RD = getAsCXXRecordDecl()) 2661 return RD->isStructural(); 2662 return false; 2663 } 2664 2665 bool Type::isStandardLayoutType() const { 2666 if (isDependentType()) 2667 return false; 2668 2669 // C++0x [basic.types]p9: 2670 // Scalar types, standard-layout class types, arrays of such types, and 2671 // cv-qualified versions of these types are collectively called 2672 // standard-layout types. 2673 const Type *BaseTy = getBaseElementTypeUnsafe(); 2674 assert(BaseTy && "NULL element type"); 2675 2676 // Return false for incomplete types after skipping any incomplete array 2677 // types which are expressly allowed by the standard and thus our API. 2678 if (BaseTy->isIncompleteType()) 2679 return false; 2680 2681 // As an extension, Clang treats vector types as Scalar types. 2682 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2683 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2684 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2685 if (!ClassDecl->isStandardLayout()) 2686 return false; 2687 2688 // Default to 'true' for non-C++ class types. 2689 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2690 // all the requirements of standard layout classes. 2691 return true; 2692 } 2693 2694 // No other types can match. 2695 return false; 2696 } 2697 2698 // This is effectively the intersection of isTrivialType and 2699 // isStandardLayoutType. We implement it directly to avoid redundant 2700 // conversions from a type to a CXXRecordDecl. 2701 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2702 const Type *ty = getTypePtr(); 2703 if (ty->isDependentType()) 2704 return false; 2705 2706 if (hasNonTrivialObjCLifetime()) 2707 return false; 2708 2709 // C++11 [basic.types]p9: 2710 // Scalar types, POD classes, arrays of such types, and cv-qualified 2711 // versions of these types are collectively called trivial types. 2712 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2713 assert(BaseTy && "NULL element type"); 2714 2715 if (BaseTy->isSizelessBuiltinType()) 2716 return true; 2717 2718 // Return false for incomplete types after skipping any incomplete array 2719 // types which are expressly allowed by the standard and thus our API. 2720 if (BaseTy->isIncompleteType()) 2721 return false; 2722 2723 // As an extension, Clang treats vector types as Scalar types. 2724 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2725 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2726 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2727 // C++11 [class]p10: 2728 // A POD struct is a non-union class that is both a trivial class [...] 2729 if (!ClassDecl->isTrivial()) return false; 2730 2731 // C++11 [class]p10: 2732 // A POD struct is a non-union class that is both a trivial class and 2733 // a standard-layout class [...] 2734 if (!ClassDecl->isStandardLayout()) return false; 2735 2736 // C++11 [class]p10: 2737 // A POD struct is a non-union class that is both a trivial class and 2738 // a standard-layout class, and has no non-static data members of type 2739 // non-POD struct, non-POD union (or array of such types). [...] 2740 // 2741 // We don't directly query the recursive aspect as the requirements for 2742 // both standard-layout classes and trivial classes apply recursively 2743 // already. 2744 } 2745 2746 return true; 2747 } 2748 2749 // No other types can match. 2750 return false; 2751 } 2752 2753 bool Type::isNothrowT() const { 2754 if (const auto *RD = getAsCXXRecordDecl()) { 2755 IdentifierInfo *II = RD->getIdentifier(); 2756 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace()) 2757 return true; 2758 } 2759 return false; 2760 } 2761 2762 bool Type::isAlignValT() const { 2763 if (const auto *ET = getAs<EnumType>()) { 2764 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2765 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace()) 2766 return true; 2767 } 2768 return false; 2769 } 2770 2771 bool Type::isStdByteType() const { 2772 if (const auto *ET = getAs<EnumType>()) { 2773 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2774 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace()) 2775 return true; 2776 } 2777 return false; 2778 } 2779 2780 bool Type::isPromotableIntegerType() const { 2781 if (const auto *BT = getAs<BuiltinType>()) 2782 switch (BT->getKind()) { 2783 case BuiltinType::Bool: 2784 case BuiltinType::Char_S: 2785 case BuiltinType::Char_U: 2786 case BuiltinType::SChar: 2787 case BuiltinType::UChar: 2788 case BuiltinType::Short: 2789 case BuiltinType::UShort: 2790 case BuiltinType::WChar_S: 2791 case BuiltinType::WChar_U: 2792 case BuiltinType::Char8: 2793 case BuiltinType::Char16: 2794 case BuiltinType::Char32: 2795 return true; 2796 default: 2797 return false; 2798 } 2799 2800 // Enumerated types are promotable to their compatible integer types 2801 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2802 if (const auto *ET = getAs<EnumType>()){ 2803 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2804 || ET->getDecl()->isScoped()) 2805 return false; 2806 2807 return true; 2808 } 2809 2810 return false; 2811 } 2812 2813 bool Type::isSpecifierType() const { 2814 // Note that this intentionally does not use the canonical type. 2815 switch (getTypeClass()) { 2816 case Builtin: 2817 case Record: 2818 case Enum: 2819 case Typedef: 2820 case Complex: 2821 case TypeOfExpr: 2822 case TypeOf: 2823 case TemplateTypeParm: 2824 case SubstTemplateTypeParm: 2825 case TemplateSpecialization: 2826 case Elaborated: 2827 case DependentName: 2828 case DependentTemplateSpecialization: 2829 case ObjCInterface: 2830 case ObjCObject: 2831 return true; 2832 default: 2833 return false; 2834 } 2835 } 2836 2837 ElaboratedTypeKeyword 2838 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2839 switch (TypeSpec) { 2840 default: return ETK_None; 2841 case TST_typename: return ETK_Typename; 2842 case TST_class: return ETK_Class; 2843 case TST_struct: return ETK_Struct; 2844 case TST_interface: return ETK_Interface; 2845 case TST_union: return ETK_Union; 2846 case TST_enum: return ETK_Enum; 2847 } 2848 } 2849 2850 TagTypeKind 2851 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2852 switch(TypeSpec) { 2853 case TST_class: return TTK_Class; 2854 case TST_struct: return TTK_Struct; 2855 case TST_interface: return TTK_Interface; 2856 case TST_union: return TTK_Union; 2857 case TST_enum: return TTK_Enum; 2858 } 2859 2860 llvm_unreachable("Type specifier is not a tag type kind."); 2861 } 2862 2863 ElaboratedTypeKeyword 2864 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2865 switch (Kind) { 2866 case TTK_Class: return ETK_Class; 2867 case TTK_Struct: return ETK_Struct; 2868 case TTK_Interface: return ETK_Interface; 2869 case TTK_Union: return ETK_Union; 2870 case TTK_Enum: return ETK_Enum; 2871 } 2872 llvm_unreachable("Unknown tag type kind."); 2873 } 2874 2875 TagTypeKind 2876 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2877 switch (Keyword) { 2878 case ETK_Class: return TTK_Class; 2879 case ETK_Struct: return TTK_Struct; 2880 case ETK_Interface: return TTK_Interface; 2881 case ETK_Union: return TTK_Union; 2882 case ETK_Enum: return TTK_Enum; 2883 case ETK_None: // Fall through. 2884 case ETK_Typename: 2885 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2886 } 2887 llvm_unreachable("Unknown elaborated type keyword."); 2888 } 2889 2890 bool 2891 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2892 switch (Keyword) { 2893 case ETK_None: 2894 case ETK_Typename: 2895 return false; 2896 case ETK_Class: 2897 case ETK_Struct: 2898 case ETK_Interface: 2899 case ETK_Union: 2900 case ETK_Enum: 2901 return true; 2902 } 2903 llvm_unreachable("Unknown elaborated type keyword."); 2904 } 2905 2906 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2907 switch (Keyword) { 2908 case ETK_None: return {}; 2909 case ETK_Typename: return "typename"; 2910 case ETK_Class: return "class"; 2911 case ETK_Struct: return "struct"; 2912 case ETK_Interface: return "__interface"; 2913 case ETK_Union: return "union"; 2914 case ETK_Enum: return "enum"; 2915 } 2916 2917 llvm_unreachable("Unknown elaborated type keyword."); 2918 } 2919 2920 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2921 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 2922 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon) 2923 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, 2924 TypeDependence::DependentInstantiation | 2925 (NNS ? toTypeDependence(NNS->getDependence()) 2926 : TypeDependence::None)), 2927 NNS(NNS), Name(Name) { 2928 DependentTemplateSpecializationTypeBits.NumArgs = Args.size(); 2929 assert((!NNS || NNS->isDependent()) && 2930 "DependentTemplateSpecializatonType requires dependent qualifier"); 2931 TemplateArgument *ArgBuffer = getArgBuffer(); 2932 for (const TemplateArgument &Arg : Args) { 2933 addDependence(toTypeDependence(Arg.getDependence() & 2934 TemplateArgumentDependence::UnexpandedPack)); 2935 2936 new (ArgBuffer++) TemplateArgument(Arg); 2937 } 2938 } 2939 2940 void 2941 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2942 const ASTContext &Context, 2943 ElaboratedTypeKeyword Keyword, 2944 NestedNameSpecifier *Qualifier, 2945 const IdentifierInfo *Name, 2946 ArrayRef<TemplateArgument> Args) { 2947 ID.AddInteger(Keyword); 2948 ID.AddPointer(Qualifier); 2949 ID.AddPointer(Name); 2950 for (const TemplateArgument &Arg : Args) 2951 Arg.Profile(ID, Context); 2952 } 2953 2954 bool Type::isElaboratedTypeSpecifier() const { 2955 ElaboratedTypeKeyword Keyword; 2956 if (const auto *Elab = dyn_cast<ElaboratedType>(this)) 2957 Keyword = Elab->getKeyword(); 2958 else if (const auto *DepName = dyn_cast<DependentNameType>(this)) 2959 Keyword = DepName->getKeyword(); 2960 else if (const auto *DepTST = 2961 dyn_cast<DependentTemplateSpecializationType>(this)) 2962 Keyword = DepTST->getKeyword(); 2963 else 2964 return false; 2965 2966 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2967 } 2968 2969 const char *Type::getTypeClassName() const { 2970 switch (TypeBits.TC) { 2971 #define ABSTRACT_TYPE(Derived, Base) 2972 #define TYPE(Derived, Base) case Derived: return #Derived; 2973 #include "clang/AST/TypeNodes.inc" 2974 } 2975 2976 llvm_unreachable("Invalid type class."); 2977 } 2978 2979 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2980 switch (getKind()) { 2981 case Void: 2982 return "void"; 2983 case Bool: 2984 return Policy.Bool ? "bool" : "_Bool"; 2985 case Char_S: 2986 return "char"; 2987 case Char_U: 2988 return "char"; 2989 case SChar: 2990 return "signed char"; 2991 case Short: 2992 return "short"; 2993 case Int: 2994 return "int"; 2995 case Long: 2996 return "long"; 2997 case LongLong: 2998 return "long long"; 2999 case Int128: 3000 return "__int128"; 3001 case UChar: 3002 return "unsigned char"; 3003 case UShort: 3004 return "unsigned short"; 3005 case UInt: 3006 return "unsigned int"; 3007 case ULong: 3008 return "unsigned long"; 3009 case ULongLong: 3010 return "unsigned long long"; 3011 case UInt128: 3012 return "unsigned __int128"; 3013 case Half: 3014 return Policy.Half ? "half" : "__fp16"; 3015 case BFloat16: 3016 return "__bf16"; 3017 case Float: 3018 return "float"; 3019 case Double: 3020 return "double"; 3021 case LongDouble: 3022 return "long double"; 3023 case ShortAccum: 3024 return "short _Accum"; 3025 case Accum: 3026 return "_Accum"; 3027 case LongAccum: 3028 return "long _Accum"; 3029 case UShortAccum: 3030 return "unsigned short _Accum"; 3031 case UAccum: 3032 return "unsigned _Accum"; 3033 case ULongAccum: 3034 return "unsigned long _Accum"; 3035 case BuiltinType::ShortFract: 3036 return "short _Fract"; 3037 case BuiltinType::Fract: 3038 return "_Fract"; 3039 case BuiltinType::LongFract: 3040 return "long _Fract"; 3041 case BuiltinType::UShortFract: 3042 return "unsigned short _Fract"; 3043 case BuiltinType::UFract: 3044 return "unsigned _Fract"; 3045 case BuiltinType::ULongFract: 3046 return "unsigned long _Fract"; 3047 case BuiltinType::SatShortAccum: 3048 return "_Sat short _Accum"; 3049 case BuiltinType::SatAccum: 3050 return "_Sat _Accum"; 3051 case BuiltinType::SatLongAccum: 3052 return "_Sat long _Accum"; 3053 case BuiltinType::SatUShortAccum: 3054 return "_Sat unsigned short _Accum"; 3055 case BuiltinType::SatUAccum: 3056 return "_Sat unsigned _Accum"; 3057 case BuiltinType::SatULongAccum: 3058 return "_Sat unsigned long _Accum"; 3059 case BuiltinType::SatShortFract: 3060 return "_Sat short _Fract"; 3061 case BuiltinType::SatFract: 3062 return "_Sat _Fract"; 3063 case BuiltinType::SatLongFract: 3064 return "_Sat long _Fract"; 3065 case BuiltinType::SatUShortFract: 3066 return "_Sat unsigned short _Fract"; 3067 case BuiltinType::SatUFract: 3068 return "_Sat unsigned _Fract"; 3069 case BuiltinType::SatULongFract: 3070 return "_Sat unsigned long _Fract"; 3071 case Float16: 3072 return "_Float16"; 3073 case Float128: 3074 return "__float128"; 3075 case Ibm128: 3076 return "__ibm128"; 3077 case WChar_S: 3078 case WChar_U: 3079 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 3080 case Char8: 3081 return "char8_t"; 3082 case Char16: 3083 return "char16_t"; 3084 case Char32: 3085 return "char32_t"; 3086 case NullPtr: 3087 return "std::nullptr_t"; 3088 case Overload: 3089 return "<overloaded function type>"; 3090 case BoundMember: 3091 return "<bound member function type>"; 3092 case PseudoObject: 3093 return "<pseudo-object type>"; 3094 case Dependent: 3095 return "<dependent type>"; 3096 case UnknownAny: 3097 return "<unknown type>"; 3098 case ARCUnbridgedCast: 3099 return "<ARC unbridged cast type>"; 3100 case BuiltinFn: 3101 return "<builtin fn type>"; 3102 case ObjCId: 3103 return "id"; 3104 case ObjCClass: 3105 return "Class"; 3106 case ObjCSel: 3107 return "SEL"; 3108 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3109 case Id: \ 3110 return "__" #Access " " #ImgType "_t"; 3111 #include "clang/Basic/OpenCLImageTypes.def" 3112 case OCLSampler: 3113 return "sampler_t"; 3114 case OCLEvent: 3115 return "event_t"; 3116 case OCLClkEvent: 3117 return "clk_event_t"; 3118 case OCLQueue: 3119 return "queue_t"; 3120 case OCLReserveID: 3121 return "reserve_id_t"; 3122 case IncompleteMatrixIdx: 3123 return "<incomplete matrix index type>"; 3124 case OMPArraySection: 3125 return "<OpenMP array section type>"; 3126 case OMPArrayShaping: 3127 return "<OpenMP array shaping type>"; 3128 case OMPIterator: 3129 return "<OpenMP iterator type>"; 3130 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3131 case Id: \ 3132 return #ExtType; 3133 #include "clang/Basic/OpenCLExtensionTypes.def" 3134 #define SVE_TYPE(Name, Id, SingletonId) \ 3135 case Id: \ 3136 return Name; 3137 #include "clang/Basic/AArch64SVEACLETypes.def" 3138 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3139 case Id: \ 3140 return #Name; 3141 #include "clang/Basic/PPCTypes.def" 3142 #define RVV_TYPE(Name, Id, SingletonId) \ 3143 case Id: \ 3144 return Name; 3145 #include "clang/Basic/RISCVVTypes.def" 3146 } 3147 3148 llvm_unreachable("Invalid builtin type."); 3149 } 3150 3151 QualType QualType::getNonPackExpansionType() const { 3152 // We never wrap type sugar around a PackExpansionType. 3153 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr())) 3154 return PET->getPattern(); 3155 return *this; 3156 } 3157 3158 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 3159 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) 3160 return RefType->getPointeeType(); 3161 3162 // C++0x [basic.lval]: 3163 // Class prvalues can have cv-qualified types; non-class prvalues always 3164 // have cv-unqualified types. 3165 // 3166 // See also C99 6.3.2.1p2. 3167 if (!Context.getLangOpts().CPlusPlus || 3168 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 3169 return getUnqualifiedType(); 3170 3171 return *this; 3172 } 3173 3174 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 3175 switch (CC) { 3176 case CC_C: return "cdecl"; 3177 case CC_X86StdCall: return "stdcall"; 3178 case CC_X86FastCall: return "fastcall"; 3179 case CC_X86ThisCall: return "thiscall"; 3180 case CC_X86Pascal: return "pascal"; 3181 case CC_X86VectorCall: return "vectorcall"; 3182 case CC_Win64: return "ms_abi"; 3183 case CC_X86_64SysV: return "sysv_abi"; 3184 case CC_X86RegCall : return "regcall"; 3185 case CC_AAPCS: return "aapcs"; 3186 case CC_AAPCS_VFP: return "aapcs-vfp"; 3187 case CC_AArch64VectorCall: return "aarch64_vector_pcs"; 3188 case CC_IntelOclBicc: return "intel_ocl_bicc"; 3189 case CC_SpirFunction: return "spir_function"; 3190 case CC_OpenCLKernel: return "opencl_kernel"; 3191 case CC_Swift: return "swiftcall"; 3192 case CC_SwiftAsync: return "swiftasynccall"; 3193 case CC_PreserveMost: return "preserve_most"; 3194 case CC_PreserveAll: return "preserve_all"; 3195 } 3196 3197 llvm_unreachable("Invalid calling convention."); 3198 } 3199 3200 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 3201 QualType canonical, 3202 const ExtProtoInfo &epi) 3203 : FunctionType(FunctionProto, result, canonical, result->getDependence(), 3204 epi.ExtInfo) { 3205 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers(); 3206 FunctionTypeBits.RefQualifier = epi.RefQualifier; 3207 FunctionTypeBits.NumParams = params.size(); 3208 assert(getNumParams() == params.size() && "NumParams overflow!"); 3209 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type; 3210 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos; 3211 FunctionTypeBits.Variadic = epi.Variadic; 3212 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn; 3213 3214 // Fill in the extra trailing bitfields if present. 3215 if (hasExtraBitfields(epi.ExceptionSpec.Type)) { 3216 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>(); 3217 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size(); 3218 } 3219 3220 // Fill in the trailing argument array. 3221 auto *argSlot = getTrailingObjects<QualType>(); 3222 for (unsigned i = 0; i != getNumParams(); ++i) { 3223 addDependence(params[i]->getDependence() & 3224 ~TypeDependence::VariablyModified); 3225 argSlot[i] = params[i]; 3226 } 3227 3228 // Fill in the exception type array if present. 3229 if (getExceptionSpecType() == EST_Dynamic) { 3230 assert(hasExtraBitfields() && "missing trailing extra bitfields!"); 3231 auto *exnSlot = 3232 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>()); 3233 unsigned I = 0; 3234 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 3235 // Note that, before C++17, a dependent exception specification does 3236 // *not* make a type dependent; it's not even part of the C++ type 3237 // system. 3238 addDependence( 3239 ExceptionType->getDependence() & 3240 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3241 3242 exnSlot[I++] = ExceptionType; 3243 } 3244 } 3245 // Fill in the Expr * in the exception specification if present. 3246 else if (isComputedNoexcept(getExceptionSpecType())) { 3247 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr"); 3248 assert((getExceptionSpecType() == EST_DependentNoexcept) == 3249 epi.ExceptionSpec.NoexceptExpr->isValueDependent()); 3250 3251 // Store the noexcept expression and context. 3252 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr; 3253 3254 addDependence( 3255 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) & 3256 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3257 } 3258 // Fill in the FunctionDecl * in the exception specification if present. 3259 else if (getExceptionSpecType() == EST_Uninstantiated) { 3260 // Store the function decl from which we will resolve our 3261 // exception specification. 3262 auto **slot = getTrailingObjects<FunctionDecl *>(); 3263 slot[0] = epi.ExceptionSpec.SourceDecl; 3264 slot[1] = epi.ExceptionSpec.SourceTemplate; 3265 // This exception specification doesn't make the type dependent, because 3266 // it's not instantiated as part of instantiating the type. 3267 } else if (getExceptionSpecType() == EST_Unevaluated) { 3268 // Store the function decl from which we will resolve our 3269 // exception specification. 3270 auto **slot = getTrailingObjects<FunctionDecl *>(); 3271 slot[0] = epi.ExceptionSpec.SourceDecl; 3272 } 3273 3274 // If this is a canonical type, and its exception specification is dependent, 3275 // then it's a dependent type. This only happens in C++17 onwards. 3276 if (isCanonicalUnqualified()) { 3277 if (getExceptionSpecType() == EST_Dynamic || 3278 getExceptionSpecType() == EST_DependentNoexcept) { 3279 assert(hasDependentExceptionSpec() && "type should not be canonical"); 3280 addDependence(TypeDependence::DependentInstantiation); 3281 } 3282 } else if (getCanonicalTypeInternal()->isDependentType()) { 3283 // Ask our canonical type whether our exception specification was dependent. 3284 addDependence(TypeDependence::DependentInstantiation); 3285 } 3286 3287 // Fill in the extra parameter info if present. 3288 if (epi.ExtParameterInfos) { 3289 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>(); 3290 for (unsigned i = 0; i != getNumParams(); ++i) 3291 extParamInfos[i] = epi.ExtParameterInfos[i]; 3292 } 3293 3294 if (epi.TypeQuals.hasNonFastQualifiers()) { 3295 FunctionTypeBits.HasExtQuals = 1; 3296 *getTrailingObjects<Qualifiers>() = epi.TypeQuals; 3297 } else { 3298 FunctionTypeBits.HasExtQuals = 0; 3299 } 3300 3301 // Fill in the Ellipsis location info if present. 3302 if (epi.Variadic) { 3303 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>(); 3304 EllipsisLoc = epi.EllipsisLoc; 3305 } 3306 } 3307 3308 bool FunctionProtoType::hasDependentExceptionSpec() const { 3309 if (Expr *NE = getNoexceptExpr()) 3310 return NE->isValueDependent(); 3311 for (QualType ET : exceptions()) 3312 // A pack expansion with a non-dependent pattern is still dependent, 3313 // because we don't know whether the pattern is in the exception spec 3314 // or not (that depends on whether the pack has 0 expansions). 3315 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 3316 return true; 3317 return false; 3318 } 3319 3320 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const { 3321 if (Expr *NE = getNoexceptExpr()) 3322 return NE->isInstantiationDependent(); 3323 for (QualType ET : exceptions()) 3324 if (ET->isInstantiationDependentType()) 3325 return true; 3326 return false; 3327 } 3328 3329 CanThrowResult FunctionProtoType::canThrow() const { 3330 switch (getExceptionSpecType()) { 3331 case EST_Unparsed: 3332 case EST_Unevaluated: 3333 llvm_unreachable("should not call this with unresolved exception specs"); 3334 3335 case EST_DynamicNone: 3336 case EST_BasicNoexcept: 3337 case EST_NoexceptTrue: 3338 case EST_NoThrow: 3339 return CT_Cannot; 3340 3341 case EST_None: 3342 case EST_MSAny: 3343 case EST_NoexceptFalse: 3344 return CT_Can; 3345 3346 case EST_Dynamic: 3347 // A dynamic exception specification is throwing unless every exception 3348 // type is an (unexpanded) pack expansion type. 3349 for (unsigned I = 0; I != getNumExceptions(); ++I) 3350 if (!getExceptionType(I)->getAs<PackExpansionType>()) 3351 return CT_Can; 3352 return CT_Dependent; 3353 3354 case EST_Uninstantiated: 3355 case EST_DependentNoexcept: 3356 return CT_Dependent; 3357 } 3358 3359 llvm_unreachable("unexpected exception specification kind"); 3360 } 3361 3362 bool FunctionProtoType::isTemplateVariadic() const { 3363 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 3364 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 3365 return true; 3366 3367 return false; 3368 } 3369 3370 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 3371 const QualType *ArgTys, unsigned NumParams, 3372 const ExtProtoInfo &epi, 3373 const ASTContext &Context, bool Canonical) { 3374 // We have to be careful not to get ambiguous profile encodings. 3375 // Note that valid type pointers are never ambiguous with anything else. 3376 // 3377 // The encoding grammar begins: 3378 // type type* bool int bool 3379 // If that final bool is true, then there is a section for the EH spec: 3380 // bool type* 3381 // This is followed by an optional "consumed argument" section of the 3382 // same length as the first type sequence: 3383 // bool* 3384 // Finally, we have the ext info and trailing return type flag: 3385 // int bool 3386 // 3387 // There is no ambiguity between the consumed arguments and an empty EH 3388 // spec because of the leading 'bool' which unambiguously indicates 3389 // whether the following bool is the EH spec or part of the arguments. 3390 3391 ID.AddPointer(Result.getAsOpaquePtr()); 3392 for (unsigned i = 0; i != NumParams; ++i) 3393 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 3394 // This method is relatively performance sensitive, so as a performance 3395 // shortcut, use one AddInteger call instead of four for the next four 3396 // fields. 3397 assert(!(unsigned(epi.Variadic) & ~1) && 3398 !(unsigned(epi.RefQualifier) & ~3) && 3399 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 3400 "Values larger than expected."); 3401 ID.AddInteger(unsigned(epi.Variadic) + 3402 (epi.RefQualifier << 1) + 3403 (epi.ExceptionSpec.Type << 3)); 3404 ID.Add(epi.TypeQuals); 3405 if (epi.ExceptionSpec.Type == EST_Dynamic) { 3406 for (QualType Ex : epi.ExceptionSpec.Exceptions) 3407 ID.AddPointer(Ex.getAsOpaquePtr()); 3408 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) { 3409 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical); 3410 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 3411 epi.ExceptionSpec.Type == EST_Unevaluated) { 3412 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 3413 } 3414 if (epi.ExtParameterInfos) { 3415 for (unsigned i = 0; i != NumParams; ++i) 3416 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 3417 } 3418 epi.ExtInfo.Profile(ID); 3419 ID.AddBoolean(epi.HasTrailingReturn); 3420 } 3421 3422 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 3423 const ASTContext &Ctx) { 3424 Profile(ID, getReturnType(), param_type_begin(), getNumParams(), 3425 getExtProtoInfo(), Ctx, isCanonicalUnqualified()); 3426 } 3427 3428 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D, 3429 QualType underlying, QualType can) 3430 : Type(tc, can, toSemanticDependence(underlying->getDependence())), 3431 Decl(const_cast<TypedefNameDecl *>(D)) { 3432 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 3433 } 3434 3435 QualType TypedefType::desugar() const { 3436 return getDecl()->getUnderlyingType(); 3437 } 3438 3439 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying, 3440 QualType Canon) 3441 : Type(Using, Canon, toSemanticDependence(Underlying->getDependence())), 3442 Found(const_cast<UsingShadowDecl *>(Found)) { 3443 assert(Underlying == getUnderlyingType()); 3444 } 3445 3446 QualType UsingType::getUnderlyingType() const { 3447 return QualType(cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0); 3448 } 3449 3450 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); } 3451 3452 QualType MacroQualifiedType::getModifiedType() const { 3453 // Step over MacroQualifiedTypes from the same macro to find the type 3454 // ultimately qualified by the macro qualifier. 3455 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType(); 3456 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) { 3457 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier()) 3458 break; 3459 Inner = InnerMQT->getModifiedType(); 3460 } 3461 return Inner; 3462 } 3463 3464 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 3465 : Type(TypeOfExpr, can, 3466 toTypeDependence(E->getDependence()) | 3467 (E->getType()->getDependence() & 3468 TypeDependence::VariablyModified)), 3469 TOExpr(E) {} 3470 3471 bool TypeOfExprType::isSugared() const { 3472 return !TOExpr->isTypeDependent(); 3473 } 3474 3475 QualType TypeOfExprType::desugar() const { 3476 if (isSugared()) 3477 return getUnderlyingExpr()->getType(); 3478 3479 return QualType(this, 0); 3480 } 3481 3482 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 3483 const ASTContext &Context, Expr *E) { 3484 E->Profile(ID, Context, true); 3485 } 3486 3487 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 3488 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 3489 // decltype(e) denotes a unique dependent type." Hence a decltype type is 3490 // type-dependent even if its expression is only instantiation-dependent. 3491 : Type(Decltype, can, 3492 toTypeDependence(E->getDependence()) | 3493 (E->isInstantiationDependent() ? TypeDependence::Dependent 3494 : TypeDependence::None) | 3495 (E->getType()->getDependence() & 3496 TypeDependence::VariablyModified)), 3497 E(E), UnderlyingType(underlyingType) {} 3498 3499 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 3500 3501 QualType DecltypeType::desugar() const { 3502 if (isSugared()) 3503 return getUnderlyingType(); 3504 3505 return QualType(this, 0); 3506 } 3507 3508 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 3509 : DecltypeType(E, Context.DependentTy), Context(Context) {} 3510 3511 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 3512 const ASTContext &Context, Expr *E) { 3513 E->Profile(ID, Context, true); 3514 } 3515 3516 UnaryTransformType::UnaryTransformType(QualType BaseType, 3517 QualType UnderlyingType, UTTKind UKind, 3518 QualType CanonicalType) 3519 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()), 3520 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {} 3521 3522 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 3523 QualType BaseType, 3524 UTTKind UKind) 3525 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {} 3526 3527 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 3528 : Type(TC, can, 3529 D->isDependentType() ? TypeDependence::DependentInstantiation 3530 : TypeDependence::None), 3531 decl(const_cast<TagDecl *>(D)) {} 3532 3533 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 3534 for (auto I : decl->redecls()) { 3535 if (I->isCompleteDefinition() || I->isBeingDefined()) 3536 return I; 3537 } 3538 // If there's no definition (not even in progress), return what we have. 3539 return decl; 3540 } 3541 3542 TagDecl *TagType::getDecl() const { 3543 return getInterestingTagDecl(decl); 3544 } 3545 3546 bool TagType::isBeingDefined() const { 3547 return getDecl()->isBeingDefined(); 3548 } 3549 3550 bool RecordType::hasConstFields() const { 3551 std::vector<const RecordType*> RecordTypeList; 3552 RecordTypeList.push_back(this); 3553 unsigned NextToCheckIndex = 0; 3554 3555 while (RecordTypeList.size() > NextToCheckIndex) { 3556 for (FieldDecl *FD : 3557 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 3558 QualType FieldTy = FD->getType(); 3559 if (FieldTy.isConstQualified()) 3560 return true; 3561 FieldTy = FieldTy.getCanonicalType(); 3562 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 3563 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 3564 RecordTypeList.push_back(FieldRecTy); 3565 } 3566 } 3567 ++NextToCheckIndex; 3568 } 3569 return false; 3570 } 3571 3572 bool AttributedType::isQualifier() const { 3573 // FIXME: Generate this with TableGen. 3574 switch (getAttrKind()) { 3575 // These are type qualifiers in the traditional C sense: they annotate 3576 // something about a specific value/variable of a type. (They aren't 3577 // always part of the canonical type, though.) 3578 case attr::ObjCGC: 3579 case attr::ObjCOwnership: 3580 case attr::ObjCInertUnsafeUnretained: 3581 case attr::TypeNonNull: 3582 case attr::TypeNullable: 3583 case attr::TypeNullableResult: 3584 case attr::TypeNullUnspecified: 3585 case attr::LifetimeBound: 3586 case attr::AddressSpace: 3587 return true; 3588 3589 // All other type attributes aren't qualifiers; they rewrite the modified 3590 // type to be a semantically different type. 3591 default: 3592 return false; 3593 } 3594 } 3595 3596 bool AttributedType::isMSTypeSpec() const { 3597 // FIXME: Generate this with TableGen? 3598 switch (getAttrKind()) { 3599 default: return false; 3600 case attr::Ptr32: 3601 case attr::Ptr64: 3602 case attr::SPtr: 3603 case attr::UPtr: 3604 return true; 3605 } 3606 llvm_unreachable("invalid attr kind"); 3607 } 3608 3609 bool AttributedType::isCallingConv() const { 3610 // FIXME: Generate this with TableGen. 3611 switch (getAttrKind()) { 3612 default: return false; 3613 case attr::Pcs: 3614 case attr::CDecl: 3615 case attr::FastCall: 3616 case attr::StdCall: 3617 case attr::ThisCall: 3618 case attr::RegCall: 3619 case attr::SwiftCall: 3620 case attr::SwiftAsyncCall: 3621 case attr::VectorCall: 3622 case attr::AArch64VectorPcs: 3623 case attr::Pascal: 3624 case attr::MSABI: 3625 case attr::SysVABI: 3626 case attr::IntelOclBicc: 3627 case attr::PreserveMost: 3628 case attr::PreserveAll: 3629 return true; 3630 } 3631 llvm_unreachable("invalid attr kind"); 3632 } 3633 3634 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3635 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3636 } 3637 3638 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3639 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3640 } 3641 3642 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType( 3643 const TemplateTypeParmType *Param, QualType Canon, 3644 const TemplateArgument &ArgPack) 3645 : Type(SubstTemplateTypeParmPack, Canon, 3646 TypeDependence::DependentInstantiation | 3647 TypeDependence::UnexpandedPack), 3648 Replaced(Param), Arguments(ArgPack.pack_begin()) { 3649 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size(); 3650 } 3651 3652 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3653 return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs())); 3654 } 3655 3656 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3657 Profile(ID, getReplacedParameter(), getArgumentPack()); 3658 } 3659 3660 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3661 const TemplateTypeParmType *Replaced, 3662 const TemplateArgument &ArgPack) { 3663 ID.AddPointer(Replaced); 3664 ID.AddInteger(ArgPack.pack_size()); 3665 for (const auto &P : ArgPack.pack_elements()) 3666 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3667 } 3668 3669 bool TemplateSpecializationType::anyDependentTemplateArguments( 3670 const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) { 3671 return anyDependentTemplateArguments(Args.arguments(), Converted); 3672 } 3673 3674 bool TemplateSpecializationType::anyDependentTemplateArguments( 3675 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) { 3676 for (const TemplateArgument &Arg : Converted) 3677 if (Arg.isDependent()) 3678 return true; 3679 return false; 3680 } 3681 3682 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 3683 ArrayRef<TemplateArgumentLoc> Args) { 3684 for (const TemplateArgumentLoc &ArgLoc : Args) { 3685 if (ArgLoc.getArgument().isInstantiationDependent()) 3686 return true; 3687 } 3688 return false; 3689 } 3690 3691 TemplateSpecializationType::TemplateSpecializationType( 3692 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon, 3693 QualType AliasedType) 3694 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon, 3695 (Canon.isNull() 3696 ? TypeDependence::DependentInstantiation 3697 : toSemanticDependence(Canon->getDependence())) | 3698 (toTypeDependence(T.getDependence()) & 3699 TypeDependence::UnexpandedPack)), 3700 Template(T) { 3701 TemplateSpecializationTypeBits.NumArgs = Args.size(); 3702 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull(); 3703 3704 assert(!T.getAsDependentTemplateName() && 3705 "Use DependentTemplateSpecializationType for dependent template-name"); 3706 assert((T.getKind() == TemplateName::Template || 3707 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3708 T.getKind() == TemplateName::SubstTemplateTemplateParmPack || 3709 T.getKind() == TemplateName::UsingTemplate) && 3710 "Unexpected template name for TemplateSpecializationType"); 3711 3712 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); 3713 for (const TemplateArgument &Arg : Args) { 3714 // Update instantiation-dependent, variably-modified, and error bits. 3715 // If the canonical type exists and is non-dependent, the template 3716 // specialization type can be non-dependent even if one of the type 3717 // arguments is. Given: 3718 // template<typename T> using U = int; 3719 // U<T> is always non-dependent, irrespective of the type T. 3720 // However, U<Ts> contains an unexpanded parameter pack, even though 3721 // its expansion (and thus its desugared type) doesn't. 3722 addDependence(toTypeDependence(Arg.getDependence()) & 3723 ~TypeDependence::Dependent); 3724 if (Arg.getKind() == TemplateArgument::Type) 3725 addDependence(Arg.getAsType()->getDependence() & 3726 TypeDependence::VariablyModified); 3727 new (TemplateArgs++) TemplateArgument(Arg); 3728 } 3729 3730 // Store the aliased type if this is a type alias template specialization. 3731 if (isTypeAlias()) { 3732 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3733 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3734 } 3735 } 3736 3737 void 3738 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3739 TemplateName T, 3740 ArrayRef<TemplateArgument> Args, 3741 const ASTContext &Context) { 3742 T.Profile(ID); 3743 for (const TemplateArgument &Arg : Args) 3744 Arg.Profile(ID, Context); 3745 } 3746 3747 QualType 3748 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3749 if (!hasNonFastQualifiers()) 3750 return QT.withFastQualifiers(getFastQualifiers()); 3751 3752 return Context.getQualifiedType(QT, *this); 3753 } 3754 3755 QualType 3756 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3757 if (!hasNonFastQualifiers()) 3758 return QualType(T, getFastQualifiers()); 3759 3760 return Context.getQualifiedType(T, *this); 3761 } 3762 3763 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3764 QualType BaseType, 3765 ArrayRef<QualType> typeArgs, 3766 ArrayRef<ObjCProtocolDecl *> protocols, 3767 bool isKindOf) { 3768 ID.AddPointer(BaseType.getAsOpaquePtr()); 3769 ID.AddInteger(typeArgs.size()); 3770 for (auto typeArg : typeArgs) 3771 ID.AddPointer(typeArg.getAsOpaquePtr()); 3772 ID.AddInteger(protocols.size()); 3773 for (auto proto : protocols) 3774 ID.AddPointer(proto); 3775 ID.AddBoolean(isKindOf); 3776 } 3777 3778 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3779 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3780 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3781 isKindOfTypeAsWritten()); 3782 } 3783 3784 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID, 3785 const ObjCTypeParamDecl *OTPDecl, 3786 QualType CanonicalType, 3787 ArrayRef<ObjCProtocolDecl *> protocols) { 3788 ID.AddPointer(OTPDecl); 3789 ID.AddPointer(CanonicalType.getAsOpaquePtr()); 3790 ID.AddInteger(protocols.size()); 3791 for (auto proto : protocols) 3792 ID.AddPointer(proto); 3793 } 3794 3795 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) { 3796 Profile(ID, getDecl(), getCanonicalTypeInternal(), 3797 llvm::makeArrayRef(qual_begin(), getNumProtocols())); 3798 } 3799 3800 namespace { 3801 3802 /// The cached properties of a type. 3803 class CachedProperties { 3804 Linkage L; 3805 bool local; 3806 3807 public: 3808 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3809 3810 Linkage getLinkage() const { return L; } 3811 bool hasLocalOrUnnamedType() const { return local; } 3812 3813 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3814 Linkage MergedLinkage = minLinkage(L.L, R.L); 3815 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() || 3816 R.hasLocalOrUnnamedType()); 3817 } 3818 }; 3819 3820 } // namespace 3821 3822 static CachedProperties computeCachedProperties(const Type *T); 3823 3824 namespace clang { 3825 3826 /// The type-property cache. This is templated so as to be 3827 /// instantiated at an internal type to prevent unnecessary symbol 3828 /// leakage. 3829 template <class Private> class TypePropertyCache { 3830 public: 3831 static CachedProperties get(QualType T) { 3832 return get(T.getTypePtr()); 3833 } 3834 3835 static CachedProperties get(const Type *T) { 3836 ensure(T); 3837 return CachedProperties(T->TypeBits.getLinkage(), 3838 T->TypeBits.hasLocalOrUnnamedType()); 3839 } 3840 3841 static void ensure(const Type *T) { 3842 // If the cache is valid, we're okay. 3843 if (T->TypeBits.isCacheValid()) return; 3844 3845 // If this type is non-canonical, ask its canonical type for the 3846 // relevant information. 3847 if (!T->isCanonicalUnqualified()) { 3848 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3849 ensure(CT); 3850 T->TypeBits.CacheValid = true; 3851 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3852 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3853 return; 3854 } 3855 3856 // Compute the cached properties and then set the cache. 3857 CachedProperties Result = computeCachedProperties(T); 3858 T->TypeBits.CacheValid = true; 3859 T->TypeBits.CachedLinkage = Result.getLinkage(); 3860 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3861 } 3862 }; 3863 3864 } // namespace clang 3865 3866 // Instantiate the friend template at a private class. In a 3867 // reasonable implementation, these symbols will be internal. 3868 // It is terrible that this is the best way to accomplish this. 3869 namespace { 3870 3871 class Private {}; 3872 3873 } // namespace 3874 3875 using Cache = TypePropertyCache<Private>; 3876 3877 static CachedProperties computeCachedProperties(const Type *T) { 3878 switch (T->getTypeClass()) { 3879 #define TYPE(Class,Base) 3880 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3881 #include "clang/AST/TypeNodes.inc" 3882 llvm_unreachable("didn't expect a non-canonical type here"); 3883 3884 #define TYPE(Class,Base) 3885 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3886 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3887 #include "clang/AST/TypeNodes.inc" 3888 // Treat instantiation-dependent types as external. 3889 if (!T->isInstantiationDependentType()) T->dump(); 3890 assert(T->isInstantiationDependentType()); 3891 return CachedProperties(ExternalLinkage, false); 3892 3893 case Type::Auto: 3894 case Type::DeducedTemplateSpecialization: 3895 // Give non-deduced 'auto' types external linkage. We should only see them 3896 // here in error recovery. 3897 return CachedProperties(ExternalLinkage, false); 3898 3899 case Type::BitInt: 3900 case Type::Builtin: 3901 // C++ [basic.link]p8: 3902 // A type is said to have linkage if and only if: 3903 // - it is a fundamental type (3.9.1); or 3904 return CachedProperties(ExternalLinkage, false); 3905 3906 case Type::Record: 3907 case Type::Enum: { 3908 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3909 3910 // C++ [basic.link]p8: 3911 // - it is a class or enumeration type that is named (or has a name 3912 // for linkage purposes (7.1.3)) and the name has linkage; or 3913 // - it is a specialization of a class template (14); or 3914 Linkage L = Tag->getLinkageInternal(); 3915 bool IsLocalOrUnnamed = 3916 Tag->getDeclContext()->isFunctionOrMethod() || 3917 !Tag->hasNameForLinkage(); 3918 return CachedProperties(L, IsLocalOrUnnamed); 3919 } 3920 3921 // C++ [basic.link]p8: 3922 // - it is a compound type (3.9.2) other than a class or enumeration, 3923 // compounded exclusively from types that have linkage; or 3924 case Type::Complex: 3925 return Cache::get(cast<ComplexType>(T)->getElementType()); 3926 case Type::Pointer: 3927 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3928 case Type::BlockPointer: 3929 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3930 case Type::LValueReference: 3931 case Type::RValueReference: 3932 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3933 case Type::MemberPointer: { 3934 const auto *MPT = cast<MemberPointerType>(T); 3935 return merge(Cache::get(MPT->getClass()), 3936 Cache::get(MPT->getPointeeType())); 3937 } 3938 case Type::ConstantArray: 3939 case Type::IncompleteArray: 3940 case Type::VariableArray: 3941 return Cache::get(cast<ArrayType>(T)->getElementType()); 3942 case Type::Vector: 3943 case Type::ExtVector: 3944 return Cache::get(cast<VectorType>(T)->getElementType()); 3945 case Type::ConstantMatrix: 3946 return Cache::get(cast<ConstantMatrixType>(T)->getElementType()); 3947 case Type::FunctionNoProto: 3948 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3949 case Type::FunctionProto: { 3950 const auto *FPT = cast<FunctionProtoType>(T); 3951 CachedProperties result = Cache::get(FPT->getReturnType()); 3952 for (const auto &ai : FPT->param_types()) 3953 result = merge(result, Cache::get(ai)); 3954 return result; 3955 } 3956 case Type::ObjCInterface: { 3957 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3958 return CachedProperties(L, false); 3959 } 3960 case Type::ObjCObject: 3961 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3962 case Type::ObjCObjectPointer: 3963 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3964 case Type::Atomic: 3965 return Cache::get(cast<AtomicType>(T)->getValueType()); 3966 case Type::Pipe: 3967 return Cache::get(cast<PipeType>(T)->getElementType()); 3968 } 3969 3970 llvm_unreachable("unhandled type class"); 3971 } 3972 3973 /// Determine the linkage of this type. 3974 Linkage Type::getLinkage() const { 3975 Cache::ensure(this); 3976 return TypeBits.getLinkage(); 3977 } 3978 3979 bool Type::hasUnnamedOrLocalType() const { 3980 Cache::ensure(this); 3981 return TypeBits.hasLocalOrUnnamedType(); 3982 } 3983 3984 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { 3985 switch (T->getTypeClass()) { 3986 #define TYPE(Class,Base) 3987 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3988 #include "clang/AST/TypeNodes.inc" 3989 llvm_unreachable("didn't expect a non-canonical type here"); 3990 3991 #define TYPE(Class,Base) 3992 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3993 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3994 #include "clang/AST/TypeNodes.inc" 3995 // Treat instantiation-dependent types as external. 3996 assert(T->isInstantiationDependentType()); 3997 return LinkageInfo::external(); 3998 3999 case Type::BitInt: 4000 case Type::Builtin: 4001 return LinkageInfo::external(); 4002 4003 case Type::Auto: 4004 case Type::DeducedTemplateSpecialization: 4005 return LinkageInfo::external(); 4006 4007 case Type::Record: 4008 case Type::Enum: 4009 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl()); 4010 4011 case Type::Complex: 4012 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType()); 4013 case Type::Pointer: 4014 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 4015 case Type::BlockPointer: 4016 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 4017 case Type::LValueReference: 4018 case Type::RValueReference: 4019 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 4020 case Type::MemberPointer: { 4021 const auto *MPT = cast<MemberPointerType>(T); 4022 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass()); 4023 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); 4024 return LV; 4025 } 4026 case Type::ConstantArray: 4027 case Type::IncompleteArray: 4028 case Type::VariableArray: 4029 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType()); 4030 case Type::Vector: 4031 case Type::ExtVector: 4032 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType()); 4033 case Type::ConstantMatrix: 4034 return computeTypeLinkageInfo( 4035 cast<ConstantMatrixType>(T)->getElementType()); 4036 case Type::FunctionNoProto: 4037 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 4038 case Type::FunctionProto: { 4039 const auto *FPT = cast<FunctionProtoType>(T); 4040 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType()); 4041 for (const auto &ai : FPT->param_types()) 4042 LV.merge(computeTypeLinkageInfo(ai)); 4043 return LV; 4044 } 4045 case Type::ObjCInterface: 4046 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl()); 4047 case Type::ObjCObject: 4048 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 4049 case Type::ObjCObjectPointer: 4050 return computeTypeLinkageInfo( 4051 cast<ObjCObjectPointerType>(T)->getPointeeType()); 4052 case Type::Atomic: 4053 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType()); 4054 case Type::Pipe: 4055 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType()); 4056 } 4057 4058 llvm_unreachable("unhandled type class"); 4059 } 4060 4061 bool Type::isLinkageValid() const { 4062 if (!TypeBits.isCacheValid()) 4063 return true; 4064 4065 Linkage L = LinkageComputer{} 4066 .computeTypeLinkageInfo(getCanonicalTypeInternal()) 4067 .getLinkage(); 4068 return L == TypeBits.getLinkage(); 4069 } 4070 4071 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) { 4072 if (!T->isCanonicalUnqualified()) 4073 return computeTypeLinkageInfo(T->getCanonicalTypeInternal()); 4074 4075 LinkageInfo LV = computeTypeLinkageInfo(T); 4076 assert(LV.getLinkage() == T->getLinkage()); 4077 return LV; 4078 } 4079 4080 LinkageInfo Type::getLinkageAndVisibility() const { 4081 return LinkageComputer{}.getTypeLinkageAndVisibility(this); 4082 } 4083 4084 Optional<NullabilityKind> 4085 Type::getNullability(const ASTContext &Context) const { 4086 QualType Type(this, 0); 4087 while (const auto *AT = Type->getAs<AttributedType>()) { 4088 // Check whether this is an attributed type with nullability 4089 // information. 4090 if (auto Nullability = AT->getImmediateNullability()) 4091 return Nullability; 4092 4093 Type = AT->getEquivalentType(); 4094 } 4095 return None; 4096 } 4097 4098 bool Type::canHaveNullability(bool ResultIfUnknown) const { 4099 QualType type = getCanonicalTypeInternal(); 4100 4101 switch (type->getTypeClass()) { 4102 // We'll only see canonical types here. 4103 #define NON_CANONICAL_TYPE(Class, Parent) \ 4104 case Type::Class: \ 4105 llvm_unreachable("non-canonical type"); 4106 #define TYPE(Class, Parent) 4107 #include "clang/AST/TypeNodes.inc" 4108 4109 // Pointer types. 4110 case Type::Pointer: 4111 case Type::BlockPointer: 4112 case Type::MemberPointer: 4113 case Type::ObjCObjectPointer: 4114 return true; 4115 4116 // Dependent types that could instantiate to pointer types. 4117 case Type::UnresolvedUsing: 4118 case Type::TypeOfExpr: 4119 case Type::TypeOf: 4120 case Type::Decltype: 4121 case Type::UnaryTransform: 4122 case Type::TemplateTypeParm: 4123 case Type::SubstTemplateTypeParmPack: 4124 case Type::DependentName: 4125 case Type::DependentTemplateSpecialization: 4126 case Type::Auto: 4127 return ResultIfUnknown; 4128 4129 // Dependent template specializations can instantiate to pointer 4130 // types unless they're known to be specializations of a class 4131 // template. 4132 case Type::TemplateSpecialization: 4133 if (TemplateDecl *templateDecl 4134 = cast<TemplateSpecializationType>(type.getTypePtr()) 4135 ->getTemplateName().getAsTemplateDecl()) { 4136 if (isa<ClassTemplateDecl>(templateDecl)) 4137 return false; 4138 } 4139 return ResultIfUnknown; 4140 4141 case Type::Builtin: 4142 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 4143 // Signed, unsigned, and floating-point types cannot have nullability. 4144 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4145 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4146 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 4147 #define BUILTIN_TYPE(Id, SingletonId) 4148 #include "clang/AST/BuiltinTypes.def" 4149 return false; 4150 4151 // Dependent types that could instantiate to a pointer type. 4152 case BuiltinType::Dependent: 4153 case BuiltinType::Overload: 4154 case BuiltinType::BoundMember: 4155 case BuiltinType::PseudoObject: 4156 case BuiltinType::UnknownAny: 4157 case BuiltinType::ARCUnbridgedCast: 4158 return ResultIfUnknown; 4159 4160 case BuiltinType::Void: 4161 case BuiltinType::ObjCId: 4162 case BuiltinType::ObjCClass: 4163 case BuiltinType::ObjCSel: 4164 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4165 case BuiltinType::Id: 4166 #include "clang/Basic/OpenCLImageTypes.def" 4167 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 4168 case BuiltinType::Id: 4169 #include "clang/Basic/OpenCLExtensionTypes.def" 4170 case BuiltinType::OCLSampler: 4171 case BuiltinType::OCLEvent: 4172 case BuiltinType::OCLClkEvent: 4173 case BuiltinType::OCLQueue: 4174 case BuiltinType::OCLReserveID: 4175 #define SVE_TYPE(Name, Id, SingletonId) \ 4176 case BuiltinType::Id: 4177 #include "clang/Basic/AArch64SVEACLETypes.def" 4178 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 4179 case BuiltinType::Id: 4180 #include "clang/Basic/PPCTypes.def" 4181 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 4182 #include "clang/Basic/RISCVVTypes.def" 4183 case BuiltinType::BuiltinFn: 4184 case BuiltinType::NullPtr: 4185 case BuiltinType::IncompleteMatrixIdx: 4186 case BuiltinType::OMPArraySection: 4187 case BuiltinType::OMPArrayShaping: 4188 case BuiltinType::OMPIterator: 4189 return false; 4190 } 4191 llvm_unreachable("unknown builtin type"); 4192 4193 // Non-pointer types. 4194 case Type::Complex: 4195 case Type::LValueReference: 4196 case Type::RValueReference: 4197 case Type::ConstantArray: 4198 case Type::IncompleteArray: 4199 case Type::VariableArray: 4200 case Type::DependentSizedArray: 4201 case Type::DependentVector: 4202 case Type::DependentSizedExtVector: 4203 case Type::Vector: 4204 case Type::ExtVector: 4205 case Type::ConstantMatrix: 4206 case Type::DependentSizedMatrix: 4207 case Type::DependentAddressSpace: 4208 case Type::FunctionProto: 4209 case Type::FunctionNoProto: 4210 case Type::Record: 4211 case Type::DeducedTemplateSpecialization: 4212 case Type::Enum: 4213 case Type::InjectedClassName: 4214 case Type::PackExpansion: 4215 case Type::ObjCObject: 4216 case Type::ObjCInterface: 4217 case Type::Atomic: 4218 case Type::Pipe: 4219 case Type::BitInt: 4220 case Type::DependentBitInt: 4221 return false; 4222 } 4223 llvm_unreachable("bad type kind!"); 4224 } 4225 4226 llvm::Optional<NullabilityKind> 4227 AttributedType::getImmediateNullability() const { 4228 if (getAttrKind() == attr::TypeNonNull) 4229 return NullabilityKind::NonNull; 4230 if (getAttrKind() == attr::TypeNullable) 4231 return NullabilityKind::Nullable; 4232 if (getAttrKind() == attr::TypeNullUnspecified) 4233 return NullabilityKind::Unspecified; 4234 if (getAttrKind() == attr::TypeNullableResult) 4235 return NullabilityKind::NullableResult; 4236 return None; 4237 } 4238 4239 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 4240 QualType AttrTy = T; 4241 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T)) 4242 AttrTy = MacroTy->getUnderlyingType(); 4243 4244 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) { 4245 if (auto nullability = attributed->getImmediateNullability()) { 4246 T = attributed->getModifiedType(); 4247 return nullability; 4248 } 4249 } 4250 4251 return None; 4252 } 4253 4254 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 4255 const auto *objcPtr = getAs<ObjCObjectPointerType>(); 4256 if (!objcPtr) 4257 return false; 4258 4259 if (objcPtr->isObjCIdType()) { 4260 // id is always okay. 4261 return true; 4262 } 4263 4264 // Blocks are NSObjects. 4265 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 4266 if (iface->getIdentifier() != ctx.getNSObjectName()) 4267 return false; 4268 4269 // Continue to check qualifiers, below. 4270 } else if (objcPtr->isObjCQualifiedIdType()) { 4271 // Continue to check qualifiers, below. 4272 } else { 4273 return false; 4274 } 4275 4276 // Check protocol qualifiers. 4277 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 4278 // Blocks conform to NSObject and NSCopying. 4279 if (proto->getIdentifier() != ctx.getNSObjectName() && 4280 proto->getIdentifier() != ctx.getNSCopyingName()) 4281 return false; 4282 } 4283 4284 return true; 4285 } 4286 4287 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 4288 if (isObjCARCImplicitlyUnretainedType()) 4289 return Qualifiers::OCL_ExplicitNone; 4290 return Qualifiers::OCL_Strong; 4291 } 4292 4293 bool Type::isObjCARCImplicitlyUnretainedType() const { 4294 assert(isObjCLifetimeType() && 4295 "cannot query implicit lifetime for non-inferrable type"); 4296 4297 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 4298 4299 // Walk down to the base type. We don't care about qualifiers for this. 4300 while (const auto *array = dyn_cast<ArrayType>(canon)) 4301 canon = array->getElementType().getTypePtr(); 4302 4303 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) { 4304 // Class and Class<Protocol> don't require retention. 4305 if (opt->getObjectType()->isObjCClass()) 4306 return true; 4307 } 4308 4309 return false; 4310 } 4311 4312 bool Type::isObjCNSObjectType() const { 4313 const Type *cur = this; 4314 while (true) { 4315 if (const auto *typedefType = dyn_cast<TypedefType>(cur)) 4316 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 4317 4318 // Single-step desugar until we run out of sugar. 4319 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 4320 if (next.getTypePtr() == cur) return false; 4321 cur = next.getTypePtr(); 4322 } 4323 } 4324 4325 bool Type::isObjCIndependentClassType() const { 4326 if (const auto *typedefType = dyn_cast<TypedefType>(this)) 4327 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 4328 return false; 4329 } 4330 4331 bool Type::isObjCRetainableType() const { 4332 return isObjCObjectPointerType() || 4333 isBlockPointerType() || 4334 isObjCNSObjectType(); 4335 } 4336 4337 bool Type::isObjCIndirectLifetimeType() const { 4338 if (isObjCLifetimeType()) 4339 return true; 4340 if (const auto *OPT = getAs<PointerType>()) 4341 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 4342 if (const auto *Ref = getAs<ReferenceType>()) 4343 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 4344 if (const auto *MemPtr = getAs<MemberPointerType>()) 4345 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 4346 return false; 4347 } 4348 4349 /// Returns true if objects of this type have lifetime semantics under 4350 /// ARC. 4351 bool Type::isObjCLifetimeType() const { 4352 const Type *type = this; 4353 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 4354 type = array->getElementType().getTypePtr(); 4355 return type->isObjCRetainableType(); 4356 } 4357 4358 /// Determine whether the given type T is a "bridgable" Objective-C type, 4359 /// which is either an Objective-C object pointer type or an 4360 bool Type::isObjCARCBridgableType() const { 4361 return isObjCObjectPointerType() || isBlockPointerType(); 4362 } 4363 4364 /// Determine whether the given type T is a "bridgeable" C type. 4365 bool Type::isCARCBridgableType() const { 4366 const auto *Pointer = getAs<PointerType>(); 4367 if (!Pointer) 4368 return false; 4369 4370 QualType Pointee = Pointer->getPointeeType(); 4371 return Pointee->isVoidType() || Pointee->isRecordType(); 4372 } 4373 4374 /// Check if the specified type is the CUDA device builtin surface type. 4375 bool Type::isCUDADeviceBuiltinSurfaceType() const { 4376 if (const auto *RT = getAs<RecordType>()) 4377 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>(); 4378 return false; 4379 } 4380 4381 /// Check if the specified type is the CUDA device builtin texture type. 4382 bool Type::isCUDADeviceBuiltinTextureType() const { 4383 if (const auto *RT = getAs<RecordType>()) 4384 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>(); 4385 return false; 4386 } 4387 4388 bool Type::hasSizedVLAType() const { 4389 if (!isVariablyModifiedType()) return false; 4390 4391 if (const auto *ptr = getAs<PointerType>()) 4392 return ptr->getPointeeType()->hasSizedVLAType(); 4393 if (const auto *ref = getAs<ReferenceType>()) 4394 return ref->getPointeeType()->hasSizedVLAType(); 4395 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 4396 if (isa<VariableArrayType>(arr) && 4397 cast<VariableArrayType>(arr)->getSizeExpr()) 4398 return true; 4399 4400 return arr->getElementType()->hasSizedVLAType(); 4401 } 4402 4403 return false; 4404 } 4405 4406 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 4407 switch (type.getObjCLifetime()) { 4408 case Qualifiers::OCL_None: 4409 case Qualifiers::OCL_ExplicitNone: 4410 case Qualifiers::OCL_Autoreleasing: 4411 break; 4412 4413 case Qualifiers::OCL_Strong: 4414 return DK_objc_strong_lifetime; 4415 case Qualifiers::OCL_Weak: 4416 return DK_objc_weak_lifetime; 4417 } 4418 4419 if (const auto *RT = 4420 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 4421 const RecordDecl *RD = RT->getDecl(); 4422 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4423 /// Check if this is a C++ object with a non-trivial destructor. 4424 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor()) 4425 return DK_cxx_destructor; 4426 } else { 4427 /// Check if this is a C struct that is non-trivial to destroy or an array 4428 /// that contains such a struct. 4429 if (RD->isNonTrivialToPrimitiveDestroy()) 4430 return DK_nontrivial_c_struct; 4431 } 4432 } 4433 4434 return DK_none; 4435 } 4436 4437 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 4438 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl(); 4439 } 4440 4441 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str, 4442 llvm::APSInt Val, unsigned Scale) { 4443 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(), 4444 /*IsSaturated=*/false, 4445 /*HasUnsignedPadding=*/false); 4446 llvm::APFixedPoint(Val, FXSema).toString(Str); 4447 } 4448 4449 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 4450 TypeDependence ExtraDependence, QualType Canon, 4451 ConceptDecl *TypeConstraintConcept, 4452 ArrayRef<TemplateArgument> TypeConstraintArgs) 4453 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) { 4454 AutoTypeBits.Keyword = (unsigned)Keyword; 4455 AutoTypeBits.NumArgs = TypeConstraintArgs.size(); 4456 this->TypeConstraintConcept = TypeConstraintConcept; 4457 if (TypeConstraintConcept) { 4458 TemplateArgument *ArgBuffer = getArgBuffer(); 4459 for (const TemplateArgument &Arg : TypeConstraintArgs) { 4460 addDependence( 4461 toSyntacticDependence(toTypeDependence(Arg.getDependence()))); 4462 4463 new (ArgBuffer++) TemplateArgument(Arg); 4464 } 4465 } 4466 } 4467 4468 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4469 QualType Deduced, AutoTypeKeyword Keyword, 4470 bool IsDependent, ConceptDecl *CD, 4471 ArrayRef<TemplateArgument> Arguments) { 4472 ID.AddPointer(Deduced.getAsOpaquePtr()); 4473 ID.AddInteger((unsigned)Keyword); 4474 ID.AddBoolean(IsDependent); 4475 ID.AddPointer(CD); 4476 for (const TemplateArgument &Arg : Arguments) 4477 Arg.Profile(ID, Context); 4478 } 4479