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