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 Type::isVLST() const { 2322 if (!isVLSTBuiltinType()) 2323 return false; 2324 2325 return hasAttr(attr::ArmSveVectorBits); 2326 } 2327 2328 bool QualType::isPODType(const ASTContext &Context) const { 2329 // C++11 has a more relaxed definition of POD. 2330 if (Context.getLangOpts().CPlusPlus11) 2331 return isCXX11PODType(Context); 2332 2333 return isCXX98PODType(Context); 2334 } 2335 2336 bool QualType::isCXX98PODType(const ASTContext &Context) const { 2337 // The compiler shouldn't query this for incomplete types, but the user might. 2338 // We return false for that case. Except for incomplete arrays of PODs, which 2339 // are PODs according to the standard. 2340 if (isNull()) 2341 return false; 2342 2343 if ((*this)->isIncompleteArrayType()) 2344 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2345 2346 if ((*this)->isIncompleteType()) 2347 return false; 2348 2349 if (hasNonTrivialObjCLifetime()) 2350 return false; 2351 2352 QualType CanonicalType = getTypePtr()->CanonicalType; 2353 switch (CanonicalType->getTypeClass()) { 2354 // Everything not explicitly mentioned is not POD. 2355 default: return false; 2356 case Type::VariableArray: 2357 case Type::ConstantArray: 2358 // IncompleteArray is handled above. 2359 return Context.getBaseElementType(*this).isCXX98PODType(Context); 2360 2361 case Type::ObjCObjectPointer: 2362 case Type::BlockPointer: 2363 case Type::Builtin: 2364 case Type::Complex: 2365 case Type::Pointer: 2366 case Type::MemberPointer: 2367 case Type::Vector: 2368 case Type::ExtVector: 2369 case Type::ExtInt: 2370 return true; 2371 2372 case Type::Enum: 2373 return true; 2374 2375 case Type::Record: 2376 if (const auto *ClassDecl = 2377 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl())) 2378 return ClassDecl->isPOD(); 2379 2380 // C struct/union is POD. 2381 return true; 2382 } 2383 } 2384 2385 bool QualType::isTrivialType(const ASTContext &Context) const { 2386 // The compiler shouldn't query this for incomplete types, but the user might. 2387 // We return false for that case. Except for incomplete arrays of PODs, which 2388 // are PODs according to the standard. 2389 if (isNull()) 2390 return false; 2391 2392 if ((*this)->isArrayType()) 2393 return Context.getBaseElementType(*this).isTrivialType(Context); 2394 2395 if ((*this)->isSizelessBuiltinType()) 2396 return true; 2397 2398 // Return false for incomplete types after skipping any incomplete array 2399 // types which are expressly allowed by the standard and thus our API. 2400 if ((*this)->isIncompleteType()) 2401 return false; 2402 2403 if (hasNonTrivialObjCLifetime()) 2404 return false; 2405 2406 QualType CanonicalType = getTypePtr()->CanonicalType; 2407 if (CanonicalType->isDependentType()) 2408 return false; 2409 2410 // C++0x [basic.types]p9: 2411 // Scalar types, trivial class types, arrays of such types, and 2412 // cv-qualified versions of these types are collectively called trivial 2413 // types. 2414 2415 // As an extension, Clang treats vector types as Scalar types. 2416 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2417 return true; 2418 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2419 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2420 // C++11 [class]p6: 2421 // A trivial class is a class that has a default constructor, 2422 // has no non-trivial default constructors, and is trivially 2423 // copyable. 2424 return ClassDecl->hasDefaultConstructor() && 2425 !ClassDecl->hasNonTrivialDefaultConstructor() && 2426 ClassDecl->isTriviallyCopyable(); 2427 } 2428 2429 return true; 2430 } 2431 2432 // No other types can match. 2433 return false; 2434 } 2435 2436 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const { 2437 if ((*this)->isArrayType()) 2438 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context); 2439 2440 if (hasNonTrivialObjCLifetime()) 2441 return false; 2442 2443 // C++11 [basic.types]p9 - See Core 2094 2444 // Scalar types, trivially copyable class types, arrays of such types, and 2445 // cv-qualified versions of these types are collectively 2446 // called trivially copyable types. 2447 2448 QualType CanonicalType = getCanonicalType(); 2449 if (CanonicalType->isDependentType()) 2450 return false; 2451 2452 if (CanonicalType->isSizelessBuiltinType()) 2453 return true; 2454 2455 // Return false for incomplete types after skipping any incomplete array types 2456 // which are expressly allowed by the standard and thus our API. 2457 if (CanonicalType->isIncompleteType()) 2458 return false; 2459 2460 // As an extension, Clang treats vector types as Scalar types. 2461 if (CanonicalType->isScalarType() || CanonicalType->isVectorType()) 2462 return true; 2463 2464 if (const auto *RT = CanonicalType->getAs<RecordType>()) { 2465 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2466 if (!ClassDecl->isTriviallyCopyable()) return false; 2467 } 2468 2469 return true; 2470 } 2471 2472 // No other types can match. 2473 return false; 2474 } 2475 2476 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const { 2477 return !Context.getLangOpts().ObjCAutoRefCount && 2478 Context.getLangOpts().ObjCWeak && 2479 getObjCLifetime() != Qualifiers::OCL_Weak; 2480 } 2481 2482 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) { 2483 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion(); 2484 } 2485 2486 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) { 2487 return RD->hasNonTrivialToPrimitiveDestructCUnion(); 2488 } 2489 2490 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) { 2491 return RD->hasNonTrivialToPrimitiveCopyCUnion(); 2492 } 2493 2494 QualType::PrimitiveDefaultInitializeKind 2495 QualType::isNonTrivialToPrimitiveDefaultInitialize() const { 2496 if (const auto *RT = 2497 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2498 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) 2499 return PDIK_Struct; 2500 2501 switch (getQualifiers().getObjCLifetime()) { 2502 case Qualifiers::OCL_Strong: 2503 return PDIK_ARCStrong; 2504 case Qualifiers::OCL_Weak: 2505 return PDIK_ARCWeak; 2506 default: 2507 return PDIK_Trivial; 2508 } 2509 } 2510 2511 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const { 2512 if (const auto *RT = 2513 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2514 if (RT->getDecl()->isNonTrivialToPrimitiveCopy()) 2515 return PCK_Struct; 2516 2517 Qualifiers Qs = getQualifiers(); 2518 switch (Qs.getObjCLifetime()) { 2519 case Qualifiers::OCL_Strong: 2520 return PCK_ARCStrong; 2521 case Qualifiers::OCL_Weak: 2522 return PCK_ARCWeak; 2523 default: 2524 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial; 2525 } 2526 } 2527 2528 QualType::PrimitiveCopyKind 2529 QualType::isNonTrivialToPrimitiveDestructiveMove() const { 2530 return isNonTrivialToPrimitiveCopy(); 2531 } 2532 2533 bool Type::isLiteralType(const ASTContext &Ctx) const { 2534 if (isDependentType()) 2535 return false; 2536 2537 // C++1y [basic.types]p10: 2538 // A type is a literal type if it is: 2539 // -- cv void; or 2540 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType()) 2541 return true; 2542 2543 // C++11 [basic.types]p10: 2544 // A type is a literal type if it is: 2545 // [...] 2546 // -- an array of literal type other than an array of runtime bound; or 2547 if (isVariableArrayType()) 2548 return false; 2549 const Type *BaseTy = getBaseElementTypeUnsafe(); 2550 assert(BaseTy && "NULL element type"); 2551 2552 // Return false for incomplete types after skipping any incomplete array 2553 // types; those are expressly allowed by the standard and thus our API. 2554 if (BaseTy->isIncompleteType()) 2555 return false; 2556 2557 // C++11 [basic.types]p10: 2558 // A type is a literal type if it is: 2559 // -- a scalar type; or 2560 // As an extension, Clang treats vector types and complex types as 2561 // literal types. 2562 if (BaseTy->isScalarType() || BaseTy->isVectorType() || 2563 BaseTy->isAnyComplexType()) 2564 return true; 2565 // -- a reference type; or 2566 if (BaseTy->isReferenceType()) 2567 return true; 2568 // -- a class type that has all of the following properties: 2569 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2570 // -- a trivial destructor, 2571 // -- every constructor call and full-expression in the 2572 // brace-or-equal-initializers for non-static data members (if any) 2573 // is a constant expression, 2574 // -- it is an aggregate type or has at least one constexpr 2575 // constructor or constructor template that is not a copy or move 2576 // constructor, and 2577 // -- all non-static data members and base classes of literal types 2578 // 2579 // We resolve DR1361 by ignoring the second bullet. 2580 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2581 return ClassDecl->isLiteral(); 2582 2583 return true; 2584 } 2585 2586 // We treat _Atomic T as a literal type if T is a literal type. 2587 if (const auto *AT = BaseTy->getAs<AtomicType>()) 2588 return AT->getValueType()->isLiteralType(Ctx); 2589 2590 // If this type hasn't been deduced yet, then conservatively assume that 2591 // it'll work out to be a literal type. 2592 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal())) 2593 return true; 2594 2595 return false; 2596 } 2597 2598 bool Type::isStandardLayoutType() const { 2599 if (isDependentType()) 2600 return false; 2601 2602 // C++0x [basic.types]p9: 2603 // Scalar types, standard-layout class types, arrays of such types, and 2604 // cv-qualified versions of these types are collectively called 2605 // standard-layout types. 2606 const Type *BaseTy = getBaseElementTypeUnsafe(); 2607 assert(BaseTy && "NULL element type"); 2608 2609 // Return false for incomplete types after skipping any incomplete array 2610 // types which are expressly allowed by the standard and thus our API. 2611 if (BaseTy->isIncompleteType()) 2612 return false; 2613 2614 // As an extension, Clang treats vector types as Scalar types. 2615 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2616 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2617 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2618 if (!ClassDecl->isStandardLayout()) 2619 return false; 2620 2621 // Default to 'true' for non-C++ class types. 2622 // FIXME: This is a bit dubious, but plain C structs should trivially meet 2623 // all the requirements of standard layout classes. 2624 return true; 2625 } 2626 2627 // No other types can match. 2628 return false; 2629 } 2630 2631 // This is effectively the intersection of isTrivialType and 2632 // isStandardLayoutType. We implement it directly to avoid redundant 2633 // conversions from a type to a CXXRecordDecl. 2634 bool QualType::isCXX11PODType(const ASTContext &Context) const { 2635 const Type *ty = getTypePtr(); 2636 if (ty->isDependentType()) 2637 return false; 2638 2639 if (hasNonTrivialObjCLifetime()) 2640 return false; 2641 2642 // C++11 [basic.types]p9: 2643 // Scalar types, POD classes, arrays of such types, and cv-qualified 2644 // versions of these types are collectively called trivial types. 2645 const Type *BaseTy = ty->getBaseElementTypeUnsafe(); 2646 assert(BaseTy && "NULL element type"); 2647 2648 if (BaseTy->isSizelessBuiltinType()) 2649 return true; 2650 2651 // Return false for incomplete types after skipping any incomplete array 2652 // types which are expressly allowed by the standard and thus our API. 2653 if (BaseTy->isIncompleteType()) 2654 return false; 2655 2656 // As an extension, Clang treats vector types as Scalar types. 2657 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true; 2658 if (const auto *RT = BaseTy->getAs<RecordType>()) { 2659 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 2660 // C++11 [class]p10: 2661 // A POD struct is a non-union class that is both a trivial class [...] 2662 if (!ClassDecl->isTrivial()) return false; 2663 2664 // C++11 [class]p10: 2665 // A POD struct is a non-union class that is both a trivial class and 2666 // a standard-layout class [...] 2667 if (!ClassDecl->isStandardLayout()) return false; 2668 2669 // C++11 [class]p10: 2670 // A POD struct is a non-union class that is both a trivial class and 2671 // a standard-layout class, and has no non-static data members of type 2672 // non-POD struct, non-POD union (or array of such types). [...] 2673 // 2674 // We don't directly query the recursive aspect as the requirements for 2675 // both standard-layout classes and trivial classes apply recursively 2676 // already. 2677 } 2678 2679 return true; 2680 } 2681 2682 // No other types can match. 2683 return false; 2684 } 2685 2686 bool Type::isNothrowT() const { 2687 if (const auto *RD = getAsCXXRecordDecl()) { 2688 IdentifierInfo *II = RD->getIdentifier(); 2689 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace()) 2690 return true; 2691 } 2692 return false; 2693 } 2694 2695 bool Type::isAlignValT() const { 2696 if (const auto *ET = getAs<EnumType>()) { 2697 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2698 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace()) 2699 return true; 2700 } 2701 return false; 2702 } 2703 2704 bool Type::isStdByteType() const { 2705 if (const auto *ET = getAs<EnumType>()) { 2706 IdentifierInfo *II = ET->getDecl()->getIdentifier(); 2707 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace()) 2708 return true; 2709 } 2710 return false; 2711 } 2712 2713 bool Type::isPromotableIntegerType() const { 2714 if (const auto *BT = getAs<BuiltinType>()) 2715 switch (BT->getKind()) { 2716 case BuiltinType::Bool: 2717 case BuiltinType::Char_S: 2718 case BuiltinType::Char_U: 2719 case BuiltinType::SChar: 2720 case BuiltinType::UChar: 2721 case BuiltinType::Short: 2722 case BuiltinType::UShort: 2723 case BuiltinType::WChar_S: 2724 case BuiltinType::WChar_U: 2725 case BuiltinType::Char8: 2726 case BuiltinType::Char16: 2727 case BuiltinType::Char32: 2728 return true; 2729 default: 2730 return false; 2731 } 2732 2733 // Enumerated types are promotable to their compatible integer types 2734 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2). 2735 if (const auto *ET = getAs<EnumType>()){ 2736 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull() 2737 || ET->getDecl()->isScoped()) 2738 return false; 2739 2740 return true; 2741 } 2742 2743 return false; 2744 } 2745 2746 bool Type::isSpecifierType() const { 2747 // Note that this intentionally does not use the canonical type. 2748 switch (getTypeClass()) { 2749 case Builtin: 2750 case Record: 2751 case Enum: 2752 case Typedef: 2753 case Complex: 2754 case TypeOfExpr: 2755 case TypeOf: 2756 case TemplateTypeParm: 2757 case SubstTemplateTypeParm: 2758 case TemplateSpecialization: 2759 case Elaborated: 2760 case DependentName: 2761 case DependentTemplateSpecialization: 2762 case ObjCInterface: 2763 case ObjCObject: 2764 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers 2765 return true; 2766 default: 2767 return false; 2768 } 2769 } 2770 2771 ElaboratedTypeKeyword 2772 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) { 2773 switch (TypeSpec) { 2774 default: return ETK_None; 2775 case TST_typename: return ETK_Typename; 2776 case TST_class: return ETK_Class; 2777 case TST_struct: return ETK_Struct; 2778 case TST_interface: return ETK_Interface; 2779 case TST_union: return ETK_Union; 2780 case TST_enum: return ETK_Enum; 2781 } 2782 } 2783 2784 TagTypeKind 2785 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) { 2786 switch(TypeSpec) { 2787 case TST_class: return TTK_Class; 2788 case TST_struct: return TTK_Struct; 2789 case TST_interface: return TTK_Interface; 2790 case TST_union: return TTK_Union; 2791 case TST_enum: return TTK_Enum; 2792 } 2793 2794 llvm_unreachable("Type specifier is not a tag type kind."); 2795 } 2796 2797 ElaboratedTypeKeyword 2798 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) { 2799 switch (Kind) { 2800 case TTK_Class: return ETK_Class; 2801 case TTK_Struct: return ETK_Struct; 2802 case TTK_Interface: return ETK_Interface; 2803 case TTK_Union: return ETK_Union; 2804 case TTK_Enum: return ETK_Enum; 2805 } 2806 llvm_unreachable("Unknown tag type kind."); 2807 } 2808 2809 TagTypeKind 2810 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) { 2811 switch (Keyword) { 2812 case ETK_Class: return TTK_Class; 2813 case ETK_Struct: return TTK_Struct; 2814 case ETK_Interface: return TTK_Interface; 2815 case ETK_Union: return TTK_Union; 2816 case ETK_Enum: return TTK_Enum; 2817 case ETK_None: // Fall through. 2818 case ETK_Typename: 2819 llvm_unreachable("Elaborated type keyword is not a tag type kind."); 2820 } 2821 llvm_unreachable("Unknown elaborated type keyword."); 2822 } 2823 2824 bool 2825 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) { 2826 switch (Keyword) { 2827 case ETK_None: 2828 case ETK_Typename: 2829 return false; 2830 case ETK_Class: 2831 case ETK_Struct: 2832 case ETK_Interface: 2833 case ETK_Union: 2834 case ETK_Enum: 2835 return true; 2836 } 2837 llvm_unreachable("Unknown elaborated type keyword."); 2838 } 2839 2840 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) { 2841 switch (Keyword) { 2842 case ETK_None: return {}; 2843 case ETK_Typename: return "typename"; 2844 case ETK_Class: return "class"; 2845 case ETK_Struct: return "struct"; 2846 case ETK_Interface: return "__interface"; 2847 case ETK_Union: return "union"; 2848 case ETK_Enum: return "enum"; 2849 } 2850 2851 llvm_unreachable("Unknown elaborated type keyword."); 2852 } 2853 2854 DependentTemplateSpecializationType::DependentTemplateSpecializationType( 2855 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 2856 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon) 2857 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, 2858 TypeDependence::DependentInstantiation | 2859 (NNS ? toTypeDependence(NNS->getDependence()) 2860 : TypeDependence::None)), 2861 NNS(NNS), Name(Name) { 2862 DependentTemplateSpecializationTypeBits.NumArgs = Args.size(); 2863 assert((!NNS || NNS->isDependent()) && 2864 "DependentTemplateSpecializatonType requires dependent qualifier"); 2865 TemplateArgument *ArgBuffer = getArgBuffer(); 2866 for (const TemplateArgument &Arg : Args) { 2867 addDependence(toTypeDependence(Arg.getDependence() & 2868 TemplateArgumentDependence::UnexpandedPack)); 2869 2870 new (ArgBuffer++) TemplateArgument(Arg); 2871 } 2872 } 2873 2874 void 2875 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 2876 const ASTContext &Context, 2877 ElaboratedTypeKeyword Keyword, 2878 NestedNameSpecifier *Qualifier, 2879 const IdentifierInfo *Name, 2880 ArrayRef<TemplateArgument> Args) { 2881 ID.AddInteger(Keyword); 2882 ID.AddPointer(Qualifier); 2883 ID.AddPointer(Name); 2884 for (const TemplateArgument &Arg : Args) 2885 Arg.Profile(ID, Context); 2886 } 2887 2888 bool Type::isElaboratedTypeSpecifier() const { 2889 ElaboratedTypeKeyword Keyword; 2890 if (const auto *Elab = dyn_cast<ElaboratedType>(this)) 2891 Keyword = Elab->getKeyword(); 2892 else if (const auto *DepName = dyn_cast<DependentNameType>(this)) 2893 Keyword = DepName->getKeyword(); 2894 else if (const auto *DepTST = 2895 dyn_cast<DependentTemplateSpecializationType>(this)) 2896 Keyword = DepTST->getKeyword(); 2897 else 2898 return false; 2899 2900 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword); 2901 } 2902 2903 const char *Type::getTypeClassName() const { 2904 switch (TypeBits.TC) { 2905 #define ABSTRACT_TYPE(Derived, Base) 2906 #define TYPE(Derived, Base) case Derived: return #Derived; 2907 #include "clang/AST/TypeNodes.inc" 2908 } 2909 2910 llvm_unreachable("Invalid type class."); 2911 } 2912 2913 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const { 2914 switch (getKind()) { 2915 case Void: 2916 return "void"; 2917 case Bool: 2918 return Policy.Bool ? "bool" : "_Bool"; 2919 case Char_S: 2920 return "char"; 2921 case Char_U: 2922 return "char"; 2923 case SChar: 2924 return "signed char"; 2925 case Short: 2926 return "short"; 2927 case Int: 2928 return "int"; 2929 case Long: 2930 return "long"; 2931 case LongLong: 2932 return "long long"; 2933 case Int128: 2934 return "__int128"; 2935 case UChar: 2936 return "unsigned char"; 2937 case UShort: 2938 return "unsigned short"; 2939 case UInt: 2940 return "unsigned int"; 2941 case ULong: 2942 return "unsigned long"; 2943 case ULongLong: 2944 return "unsigned long long"; 2945 case UInt128: 2946 return "unsigned __int128"; 2947 case Half: 2948 return Policy.Half ? "half" : "__fp16"; 2949 case BFloat16: 2950 return "__bf16"; 2951 case Float: 2952 return "float"; 2953 case Double: 2954 return "double"; 2955 case LongDouble: 2956 return "long double"; 2957 case ShortAccum: 2958 return "short _Accum"; 2959 case Accum: 2960 return "_Accum"; 2961 case LongAccum: 2962 return "long _Accum"; 2963 case UShortAccum: 2964 return "unsigned short _Accum"; 2965 case UAccum: 2966 return "unsigned _Accum"; 2967 case ULongAccum: 2968 return "unsigned long _Accum"; 2969 case BuiltinType::ShortFract: 2970 return "short _Fract"; 2971 case BuiltinType::Fract: 2972 return "_Fract"; 2973 case BuiltinType::LongFract: 2974 return "long _Fract"; 2975 case BuiltinType::UShortFract: 2976 return "unsigned short _Fract"; 2977 case BuiltinType::UFract: 2978 return "unsigned _Fract"; 2979 case BuiltinType::ULongFract: 2980 return "unsigned long _Fract"; 2981 case BuiltinType::SatShortAccum: 2982 return "_Sat short _Accum"; 2983 case BuiltinType::SatAccum: 2984 return "_Sat _Accum"; 2985 case BuiltinType::SatLongAccum: 2986 return "_Sat long _Accum"; 2987 case BuiltinType::SatUShortAccum: 2988 return "_Sat unsigned short _Accum"; 2989 case BuiltinType::SatUAccum: 2990 return "_Sat unsigned _Accum"; 2991 case BuiltinType::SatULongAccum: 2992 return "_Sat unsigned long _Accum"; 2993 case BuiltinType::SatShortFract: 2994 return "_Sat short _Fract"; 2995 case BuiltinType::SatFract: 2996 return "_Sat _Fract"; 2997 case BuiltinType::SatLongFract: 2998 return "_Sat long _Fract"; 2999 case BuiltinType::SatUShortFract: 3000 return "_Sat unsigned short _Fract"; 3001 case BuiltinType::SatUFract: 3002 return "_Sat unsigned _Fract"; 3003 case BuiltinType::SatULongFract: 3004 return "_Sat unsigned long _Fract"; 3005 case Float16: 3006 return "_Float16"; 3007 case Float128: 3008 return "__float128"; 3009 case WChar_S: 3010 case WChar_U: 3011 return Policy.MSWChar ? "__wchar_t" : "wchar_t"; 3012 case Char8: 3013 return "char8_t"; 3014 case Char16: 3015 return "char16_t"; 3016 case Char32: 3017 return "char32_t"; 3018 case NullPtr: 3019 return "nullptr_t"; 3020 case Overload: 3021 return "<overloaded function type>"; 3022 case BoundMember: 3023 return "<bound member function type>"; 3024 case PseudoObject: 3025 return "<pseudo-object type>"; 3026 case Dependent: 3027 return "<dependent type>"; 3028 case UnknownAny: 3029 return "<unknown type>"; 3030 case ARCUnbridgedCast: 3031 return "<ARC unbridged cast type>"; 3032 case BuiltinFn: 3033 return "<builtin fn type>"; 3034 case ObjCId: 3035 return "id"; 3036 case ObjCClass: 3037 return "Class"; 3038 case ObjCSel: 3039 return "SEL"; 3040 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3041 case Id: \ 3042 return "__" #Access " " #ImgType "_t"; 3043 #include "clang/Basic/OpenCLImageTypes.def" 3044 case OCLSampler: 3045 return "sampler_t"; 3046 case OCLEvent: 3047 return "event_t"; 3048 case OCLClkEvent: 3049 return "clk_event_t"; 3050 case OCLQueue: 3051 return "queue_t"; 3052 case OCLReserveID: 3053 return "reserve_id_t"; 3054 case IncompleteMatrixIdx: 3055 return "<incomplete matrix index type>"; 3056 case OMPArraySection: 3057 return "<OpenMP array section type>"; 3058 case OMPArrayShaping: 3059 return "<OpenMP array shaping type>"; 3060 case OMPIterator: 3061 return "<OpenMP iterator type>"; 3062 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3063 case Id: \ 3064 return #ExtType; 3065 #include "clang/Basic/OpenCLExtensionTypes.def" 3066 #define SVE_TYPE(Name, Id, SingletonId) \ 3067 case Id: \ 3068 return Name; 3069 #include "clang/Basic/AArch64SVEACLETypes.def" 3070 } 3071 3072 llvm_unreachable("Invalid builtin type."); 3073 } 3074 3075 QualType QualType::getNonPackExpansionType() const { 3076 // We never wrap type sugar around a PackExpansionType. 3077 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr())) 3078 return PET->getPattern(); 3079 return *this; 3080 } 3081 3082 QualType QualType::getNonLValueExprType(const ASTContext &Context) const { 3083 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>()) 3084 return RefType->getPointeeType(); 3085 3086 // C++0x [basic.lval]: 3087 // Class prvalues can have cv-qualified types; non-class prvalues always 3088 // have cv-unqualified types. 3089 // 3090 // See also C99 6.3.2.1p2. 3091 if (!Context.getLangOpts().CPlusPlus || 3092 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType())) 3093 return getUnqualifiedType(); 3094 3095 return *this; 3096 } 3097 3098 StringRef FunctionType::getNameForCallConv(CallingConv CC) { 3099 switch (CC) { 3100 case CC_C: return "cdecl"; 3101 case CC_X86StdCall: return "stdcall"; 3102 case CC_X86FastCall: return "fastcall"; 3103 case CC_X86ThisCall: return "thiscall"; 3104 case CC_X86Pascal: return "pascal"; 3105 case CC_X86VectorCall: return "vectorcall"; 3106 case CC_Win64: return "ms_abi"; 3107 case CC_X86_64SysV: return "sysv_abi"; 3108 case CC_X86RegCall : return "regcall"; 3109 case CC_AAPCS: return "aapcs"; 3110 case CC_AAPCS_VFP: return "aapcs-vfp"; 3111 case CC_AArch64VectorCall: return "aarch64_vector_pcs"; 3112 case CC_IntelOclBicc: return "intel_ocl_bicc"; 3113 case CC_SpirFunction: return "spir_function"; 3114 case CC_OpenCLKernel: return "opencl_kernel"; 3115 case CC_Swift: return "swiftcall"; 3116 case CC_PreserveMost: return "preserve_most"; 3117 case CC_PreserveAll: return "preserve_all"; 3118 } 3119 3120 llvm_unreachable("Invalid calling convention."); 3121 } 3122 3123 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params, 3124 QualType canonical, 3125 const ExtProtoInfo &epi) 3126 : FunctionType(FunctionProto, result, canonical, result->getDependence(), 3127 epi.ExtInfo) { 3128 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers(); 3129 FunctionTypeBits.RefQualifier = epi.RefQualifier; 3130 FunctionTypeBits.NumParams = params.size(); 3131 assert(getNumParams() == params.size() && "NumParams overflow!"); 3132 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type; 3133 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos; 3134 FunctionTypeBits.Variadic = epi.Variadic; 3135 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn; 3136 3137 // Fill in the extra trailing bitfields if present. 3138 if (hasExtraBitfields(epi.ExceptionSpec.Type)) { 3139 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>(); 3140 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size(); 3141 } 3142 3143 // Fill in the trailing argument array. 3144 auto *argSlot = getTrailingObjects<QualType>(); 3145 for (unsigned i = 0; i != getNumParams(); ++i) { 3146 addDependence(params[i]->getDependence() & 3147 ~TypeDependence::VariablyModified); 3148 argSlot[i] = params[i]; 3149 } 3150 3151 // Fill in the exception type array if present. 3152 if (getExceptionSpecType() == EST_Dynamic) { 3153 assert(hasExtraBitfields() && "missing trailing extra bitfields!"); 3154 auto *exnSlot = 3155 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>()); 3156 unsigned I = 0; 3157 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) { 3158 // Note that, before C++17, a dependent exception specification does 3159 // *not* make a type dependent; it's not even part of the C++ type 3160 // system. 3161 addDependence( 3162 ExceptionType->getDependence() & 3163 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3164 3165 exnSlot[I++] = ExceptionType; 3166 } 3167 } 3168 // Fill in the Expr * in the exception specification if present. 3169 else if (isComputedNoexcept(getExceptionSpecType())) { 3170 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr"); 3171 assert((getExceptionSpecType() == EST_DependentNoexcept) == 3172 epi.ExceptionSpec.NoexceptExpr->isValueDependent()); 3173 3174 // Store the noexcept expression and context. 3175 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr; 3176 3177 addDependence( 3178 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) & 3179 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack)); 3180 } 3181 // Fill in the FunctionDecl * in the exception specification if present. 3182 else if (getExceptionSpecType() == EST_Uninstantiated) { 3183 // Store the function decl from which we will resolve our 3184 // exception specification. 3185 auto **slot = getTrailingObjects<FunctionDecl *>(); 3186 slot[0] = epi.ExceptionSpec.SourceDecl; 3187 slot[1] = epi.ExceptionSpec.SourceTemplate; 3188 // This exception specification doesn't make the type dependent, because 3189 // it's not instantiated as part of instantiating the type. 3190 } else if (getExceptionSpecType() == EST_Unevaluated) { 3191 // Store the function decl from which we will resolve our 3192 // exception specification. 3193 auto **slot = getTrailingObjects<FunctionDecl *>(); 3194 slot[0] = epi.ExceptionSpec.SourceDecl; 3195 } 3196 3197 // If this is a canonical type, and its exception specification is dependent, 3198 // then it's a dependent type. This only happens in C++17 onwards. 3199 if (isCanonicalUnqualified()) { 3200 if (getExceptionSpecType() == EST_Dynamic || 3201 getExceptionSpecType() == EST_DependentNoexcept) { 3202 assert(hasDependentExceptionSpec() && "type should not be canonical"); 3203 addDependence(TypeDependence::DependentInstantiation); 3204 } 3205 } else if (getCanonicalTypeInternal()->isDependentType()) { 3206 // Ask our canonical type whether our exception specification was dependent. 3207 addDependence(TypeDependence::DependentInstantiation); 3208 } 3209 3210 // Fill in the extra parameter info if present. 3211 if (epi.ExtParameterInfos) { 3212 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>(); 3213 for (unsigned i = 0; i != getNumParams(); ++i) 3214 extParamInfos[i] = epi.ExtParameterInfos[i]; 3215 } 3216 3217 if (epi.TypeQuals.hasNonFastQualifiers()) { 3218 FunctionTypeBits.HasExtQuals = 1; 3219 *getTrailingObjects<Qualifiers>() = epi.TypeQuals; 3220 } else { 3221 FunctionTypeBits.HasExtQuals = 0; 3222 } 3223 3224 // Fill in the Ellipsis location info if present. 3225 if (epi.Variadic) { 3226 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>(); 3227 EllipsisLoc = epi.EllipsisLoc; 3228 } 3229 } 3230 3231 bool FunctionProtoType::hasDependentExceptionSpec() const { 3232 if (Expr *NE = getNoexceptExpr()) 3233 return NE->isValueDependent(); 3234 for (QualType ET : exceptions()) 3235 // A pack expansion with a non-dependent pattern is still dependent, 3236 // because we don't know whether the pattern is in the exception spec 3237 // or not (that depends on whether the pack has 0 expansions). 3238 if (ET->isDependentType() || ET->getAs<PackExpansionType>()) 3239 return true; 3240 return false; 3241 } 3242 3243 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const { 3244 if (Expr *NE = getNoexceptExpr()) 3245 return NE->isInstantiationDependent(); 3246 for (QualType ET : exceptions()) 3247 if (ET->isInstantiationDependentType()) 3248 return true; 3249 return false; 3250 } 3251 3252 CanThrowResult FunctionProtoType::canThrow() const { 3253 switch (getExceptionSpecType()) { 3254 case EST_Unparsed: 3255 case EST_Unevaluated: 3256 case EST_Uninstantiated: 3257 llvm_unreachable("should not call this with unresolved exception specs"); 3258 3259 case EST_DynamicNone: 3260 case EST_BasicNoexcept: 3261 case EST_NoexceptTrue: 3262 case EST_NoThrow: 3263 return CT_Cannot; 3264 3265 case EST_None: 3266 case EST_MSAny: 3267 case EST_NoexceptFalse: 3268 return CT_Can; 3269 3270 case EST_Dynamic: 3271 // A dynamic exception specification is throwing unless every exception 3272 // type is an (unexpanded) pack expansion type. 3273 for (unsigned I = 0; I != getNumExceptions(); ++I) 3274 if (!getExceptionType(I)->getAs<PackExpansionType>()) 3275 return CT_Can; 3276 return CT_Dependent; 3277 3278 case EST_DependentNoexcept: 3279 return CT_Dependent; 3280 } 3281 3282 llvm_unreachable("unexpected exception specification kind"); 3283 } 3284 3285 bool FunctionProtoType::isTemplateVariadic() const { 3286 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx) 3287 if (isa<PackExpansionType>(getParamType(ArgIdx - 1))) 3288 return true; 3289 3290 return false; 3291 } 3292 3293 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result, 3294 const QualType *ArgTys, unsigned NumParams, 3295 const ExtProtoInfo &epi, 3296 const ASTContext &Context, bool Canonical) { 3297 // We have to be careful not to get ambiguous profile encodings. 3298 // Note that valid type pointers are never ambiguous with anything else. 3299 // 3300 // The encoding grammar begins: 3301 // type type* bool int bool 3302 // If that final bool is true, then there is a section for the EH spec: 3303 // bool type* 3304 // This is followed by an optional "consumed argument" section of the 3305 // same length as the first type sequence: 3306 // bool* 3307 // Finally, we have the ext info and trailing return type flag: 3308 // int bool 3309 // 3310 // There is no ambiguity between the consumed arguments and an empty EH 3311 // spec because of the leading 'bool' which unambiguously indicates 3312 // whether the following bool is the EH spec or part of the arguments. 3313 3314 ID.AddPointer(Result.getAsOpaquePtr()); 3315 for (unsigned i = 0; i != NumParams; ++i) 3316 ID.AddPointer(ArgTys[i].getAsOpaquePtr()); 3317 // This method is relatively performance sensitive, so as a performance 3318 // shortcut, use one AddInteger call instead of four for the next four 3319 // fields. 3320 assert(!(unsigned(epi.Variadic) & ~1) && 3321 !(unsigned(epi.RefQualifier) & ~3) && 3322 !(unsigned(epi.ExceptionSpec.Type) & ~15) && 3323 "Values larger than expected."); 3324 ID.AddInteger(unsigned(epi.Variadic) + 3325 (epi.RefQualifier << 1) + 3326 (epi.ExceptionSpec.Type << 3)); 3327 ID.Add(epi.TypeQuals); 3328 if (epi.ExceptionSpec.Type == EST_Dynamic) { 3329 for (QualType Ex : epi.ExceptionSpec.Exceptions) 3330 ID.AddPointer(Ex.getAsOpaquePtr()); 3331 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) { 3332 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical); 3333 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated || 3334 epi.ExceptionSpec.Type == EST_Unevaluated) { 3335 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl()); 3336 } 3337 if (epi.ExtParameterInfos) { 3338 for (unsigned i = 0; i != NumParams; ++i) 3339 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue()); 3340 } 3341 epi.ExtInfo.Profile(ID); 3342 ID.AddBoolean(epi.HasTrailingReturn); 3343 } 3344 3345 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, 3346 const ASTContext &Ctx) { 3347 Profile(ID, getReturnType(), param_type_begin(), getNumParams(), 3348 getExtProtoInfo(), Ctx, isCanonicalUnqualified()); 3349 } 3350 3351 QualType TypedefType::desugar() const { 3352 return getDecl()->getUnderlyingType(); 3353 } 3354 3355 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); } 3356 3357 QualType MacroQualifiedType::getModifiedType() const { 3358 // Step over MacroQualifiedTypes from the same macro to find the type 3359 // ultimately qualified by the macro qualifier. 3360 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType(); 3361 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) { 3362 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier()) 3363 break; 3364 Inner = InnerMQT->getModifiedType(); 3365 } 3366 return Inner; 3367 } 3368 3369 TypeOfExprType::TypeOfExprType(Expr *E, QualType can) 3370 : Type(TypeOfExpr, can, 3371 toTypeDependence(E->getDependence()) | 3372 (E->getType()->getDependence() & 3373 TypeDependence::VariablyModified)), 3374 TOExpr(E) {} 3375 3376 bool TypeOfExprType::isSugared() const { 3377 return !TOExpr->isTypeDependent(); 3378 } 3379 3380 QualType TypeOfExprType::desugar() const { 3381 if (isSugared()) 3382 return getUnderlyingExpr()->getType(); 3383 3384 return QualType(this, 0); 3385 } 3386 3387 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID, 3388 const ASTContext &Context, Expr *E) { 3389 E->Profile(ID, Context, true); 3390 } 3391 3392 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can) 3393 // C++11 [temp.type]p2: "If an expression e involves a template parameter, 3394 // decltype(e) denotes a unique dependent type." Hence a decltype type is 3395 // type-dependent even if its expression is only instantiation-dependent. 3396 : Type(Decltype, can, 3397 toTypeDependence(E->getDependence()) | 3398 (E->isInstantiationDependent() ? TypeDependence::Dependent 3399 : TypeDependence::None) | 3400 (E->getType()->getDependence() & 3401 TypeDependence::VariablyModified)), 3402 E(E), UnderlyingType(underlyingType) {} 3403 3404 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); } 3405 3406 QualType DecltypeType::desugar() const { 3407 if (isSugared()) 3408 return getUnderlyingType(); 3409 3410 return QualType(this, 0); 3411 } 3412 3413 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E) 3414 : DecltypeType(E, Context.DependentTy), Context(Context) {} 3415 3416 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID, 3417 const ASTContext &Context, Expr *E) { 3418 E->Profile(ID, Context, true); 3419 } 3420 3421 UnaryTransformType::UnaryTransformType(QualType BaseType, 3422 QualType UnderlyingType, UTTKind UKind, 3423 QualType CanonicalType) 3424 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()), 3425 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {} 3426 3427 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C, 3428 QualType BaseType, 3429 UTTKind UKind) 3430 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {} 3431 3432 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can) 3433 : Type(TC, can, 3434 D->isDependentType() ? TypeDependence::DependentInstantiation 3435 : TypeDependence::None), 3436 decl(const_cast<TagDecl *>(D)) {} 3437 3438 static TagDecl *getInterestingTagDecl(TagDecl *decl) { 3439 for (auto I : decl->redecls()) { 3440 if (I->isCompleteDefinition() || I->isBeingDefined()) 3441 return I; 3442 } 3443 // If there's no definition (not even in progress), return what we have. 3444 return decl; 3445 } 3446 3447 TagDecl *TagType::getDecl() const { 3448 return getInterestingTagDecl(decl); 3449 } 3450 3451 bool TagType::isBeingDefined() const { 3452 return getDecl()->isBeingDefined(); 3453 } 3454 3455 bool RecordType::hasConstFields() const { 3456 std::vector<const RecordType*> RecordTypeList; 3457 RecordTypeList.push_back(this); 3458 unsigned NextToCheckIndex = 0; 3459 3460 while (RecordTypeList.size() > NextToCheckIndex) { 3461 for (FieldDecl *FD : 3462 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 3463 QualType FieldTy = FD->getType(); 3464 if (FieldTy.isConstQualified()) 3465 return true; 3466 FieldTy = FieldTy.getCanonicalType(); 3467 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 3468 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end()) 3469 RecordTypeList.push_back(FieldRecTy); 3470 } 3471 } 3472 ++NextToCheckIndex; 3473 } 3474 return false; 3475 } 3476 3477 bool AttributedType::isQualifier() const { 3478 // FIXME: Generate this with TableGen. 3479 switch (getAttrKind()) { 3480 // These are type qualifiers in the traditional C sense: they annotate 3481 // something about a specific value/variable of a type. (They aren't 3482 // always part of the canonical type, though.) 3483 case attr::ObjCGC: 3484 case attr::ObjCOwnership: 3485 case attr::ObjCInertUnsafeUnretained: 3486 case attr::TypeNonNull: 3487 case attr::TypeNullable: 3488 case attr::TypeNullUnspecified: 3489 case attr::LifetimeBound: 3490 case attr::AddressSpace: 3491 return true; 3492 3493 // All other type attributes aren't qualifiers; they rewrite the modified 3494 // type to be a semantically different type. 3495 default: 3496 return false; 3497 } 3498 } 3499 3500 bool AttributedType::isMSTypeSpec() const { 3501 // FIXME: Generate this with TableGen? 3502 switch (getAttrKind()) { 3503 default: return false; 3504 case attr::Ptr32: 3505 case attr::Ptr64: 3506 case attr::SPtr: 3507 case attr::UPtr: 3508 return true; 3509 } 3510 llvm_unreachable("invalid attr kind"); 3511 } 3512 3513 bool AttributedType::isCallingConv() const { 3514 // FIXME: Generate this with TableGen. 3515 switch (getAttrKind()) { 3516 default: return false; 3517 case attr::Pcs: 3518 case attr::CDecl: 3519 case attr::FastCall: 3520 case attr::StdCall: 3521 case attr::ThisCall: 3522 case attr::RegCall: 3523 case attr::SwiftCall: 3524 case attr::VectorCall: 3525 case attr::AArch64VectorPcs: 3526 case attr::Pascal: 3527 case attr::MSABI: 3528 case attr::SysVABI: 3529 case attr::IntelOclBicc: 3530 case attr::PreserveMost: 3531 case attr::PreserveAll: 3532 return true; 3533 } 3534 llvm_unreachable("invalid attr kind"); 3535 } 3536 3537 CXXRecordDecl *InjectedClassNameType::getDecl() const { 3538 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl)); 3539 } 3540 3541 IdentifierInfo *TemplateTypeParmType::getIdentifier() const { 3542 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier(); 3543 } 3544 3545 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType( 3546 const TemplateTypeParmType *Param, QualType Canon, 3547 const TemplateArgument &ArgPack) 3548 : Type(SubstTemplateTypeParmPack, Canon, 3549 TypeDependence::DependentInstantiation | 3550 TypeDependence::UnexpandedPack), 3551 Replaced(Param), Arguments(ArgPack.pack_begin()) { 3552 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size(); 3553 } 3554 3555 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const { 3556 return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs())); 3557 } 3558 3559 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) { 3560 Profile(ID, getReplacedParameter(), getArgumentPack()); 3561 } 3562 3563 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID, 3564 const TemplateTypeParmType *Replaced, 3565 const TemplateArgument &ArgPack) { 3566 ID.AddPointer(Replaced); 3567 ID.AddInteger(ArgPack.pack_size()); 3568 for (const auto &P : ArgPack.pack_elements()) 3569 ID.AddPointer(P.getAsType().getAsOpaquePtr()); 3570 } 3571 3572 bool TemplateSpecializationType:: 3573 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args, 3574 bool &InstantiationDependent) { 3575 return anyDependentTemplateArguments(Args.arguments(), 3576 InstantiationDependent); 3577 } 3578 3579 bool TemplateSpecializationType:: 3580 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 3581 bool &InstantiationDependent) { 3582 for (const TemplateArgumentLoc &ArgLoc : Args) { 3583 if (ArgLoc.getArgument().isDependent()) { 3584 InstantiationDependent = true; 3585 return true; 3586 } 3587 3588 if (ArgLoc.getArgument().isInstantiationDependent()) 3589 InstantiationDependent = true; 3590 } 3591 return false; 3592 } 3593 3594 TemplateSpecializationType::TemplateSpecializationType( 3595 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon, 3596 QualType AliasedType) 3597 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon, 3598 (Canon.isNull() 3599 ? TypeDependence::DependentInstantiation 3600 : Canon->getDependence() & ~(TypeDependence::VariablyModified | 3601 TypeDependence::UnexpandedPack)) | 3602 (toTypeDependence(T.getDependence()) & 3603 TypeDependence::UnexpandedPack)), 3604 Template(T) { 3605 TemplateSpecializationTypeBits.NumArgs = Args.size(); 3606 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull(); 3607 3608 assert(!T.getAsDependentTemplateName() && 3609 "Use DependentTemplateSpecializationType for dependent template-name"); 3610 assert((T.getKind() == TemplateName::Template || 3611 T.getKind() == TemplateName::SubstTemplateTemplateParm || 3612 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) && 3613 "Unexpected template name for TemplateSpecializationType"); 3614 3615 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1); 3616 for (const TemplateArgument &Arg : Args) { 3617 // Update instantiation-dependent, variably-modified, and error bits. 3618 // If the canonical type exists and is non-dependent, the template 3619 // specialization type can be non-dependent even if one of the type 3620 // arguments is. Given: 3621 // template<typename T> using U = int; 3622 // U<T> is always non-dependent, irrespective of the type T. 3623 // However, U<Ts> contains an unexpanded parameter pack, even though 3624 // its expansion (and thus its desugared type) doesn't. 3625 addDependence(toTypeDependence(Arg.getDependence()) & 3626 ~TypeDependence::Dependent); 3627 if (Arg.getKind() == TemplateArgument::Type) 3628 addDependence(Arg.getAsType()->getDependence() & 3629 TypeDependence::VariablyModified); 3630 new (TemplateArgs++) TemplateArgument(Arg); 3631 } 3632 3633 // Store the aliased type if this is a type alias template specialization. 3634 if (isTypeAlias()) { 3635 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1); 3636 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType; 3637 } 3638 } 3639 3640 void 3641 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID, 3642 TemplateName T, 3643 ArrayRef<TemplateArgument> Args, 3644 const ASTContext &Context) { 3645 T.Profile(ID); 3646 for (const TemplateArgument &Arg : Args) 3647 Arg.Profile(ID, Context); 3648 } 3649 3650 QualType 3651 QualifierCollector::apply(const ASTContext &Context, QualType QT) const { 3652 if (!hasNonFastQualifiers()) 3653 return QT.withFastQualifiers(getFastQualifiers()); 3654 3655 return Context.getQualifiedType(QT, *this); 3656 } 3657 3658 QualType 3659 QualifierCollector::apply(const ASTContext &Context, const Type *T) const { 3660 if (!hasNonFastQualifiers()) 3661 return QualType(T, getFastQualifiers()); 3662 3663 return Context.getQualifiedType(T, *this); 3664 } 3665 3666 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, 3667 QualType BaseType, 3668 ArrayRef<QualType> typeArgs, 3669 ArrayRef<ObjCProtocolDecl *> protocols, 3670 bool isKindOf) { 3671 ID.AddPointer(BaseType.getAsOpaquePtr()); 3672 ID.AddInteger(typeArgs.size()); 3673 for (auto typeArg : typeArgs) 3674 ID.AddPointer(typeArg.getAsOpaquePtr()); 3675 ID.AddInteger(protocols.size()); 3676 for (auto proto : protocols) 3677 ID.AddPointer(proto); 3678 ID.AddBoolean(isKindOf); 3679 } 3680 3681 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) { 3682 Profile(ID, getBaseType(), getTypeArgsAsWritten(), 3683 llvm::makeArrayRef(qual_begin(), getNumProtocols()), 3684 isKindOfTypeAsWritten()); 3685 } 3686 3687 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID, 3688 const ObjCTypeParamDecl *OTPDecl, 3689 QualType CanonicalType, 3690 ArrayRef<ObjCProtocolDecl *> protocols) { 3691 ID.AddPointer(OTPDecl); 3692 ID.AddPointer(CanonicalType.getAsOpaquePtr()); 3693 ID.AddInteger(protocols.size()); 3694 for (auto proto : protocols) 3695 ID.AddPointer(proto); 3696 } 3697 3698 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) { 3699 Profile(ID, getDecl(), getCanonicalTypeInternal(), 3700 llvm::makeArrayRef(qual_begin(), getNumProtocols())); 3701 } 3702 3703 namespace { 3704 3705 /// The cached properties of a type. 3706 class CachedProperties { 3707 Linkage L; 3708 bool local; 3709 3710 public: 3711 CachedProperties(Linkage L, bool local) : L(L), local(local) {} 3712 3713 Linkage getLinkage() const { return L; } 3714 bool hasLocalOrUnnamedType() const { return local; } 3715 3716 friend CachedProperties merge(CachedProperties L, CachedProperties R) { 3717 Linkage MergedLinkage = minLinkage(L.L, R.L); 3718 return CachedProperties(MergedLinkage, 3719 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType()); 3720 } 3721 }; 3722 3723 } // namespace 3724 3725 static CachedProperties computeCachedProperties(const Type *T); 3726 3727 namespace clang { 3728 3729 /// The type-property cache. This is templated so as to be 3730 /// instantiated at an internal type to prevent unnecessary symbol 3731 /// leakage. 3732 template <class Private> class TypePropertyCache { 3733 public: 3734 static CachedProperties get(QualType T) { 3735 return get(T.getTypePtr()); 3736 } 3737 3738 static CachedProperties get(const Type *T) { 3739 ensure(T); 3740 return CachedProperties(T->TypeBits.getLinkage(), 3741 T->TypeBits.hasLocalOrUnnamedType()); 3742 } 3743 3744 static void ensure(const Type *T) { 3745 // If the cache is valid, we're okay. 3746 if (T->TypeBits.isCacheValid()) return; 3747 3748 // If this type is non-canonical, ask its canonical type for the 3749 // relevant information. 3750 if (!T->isCanonicalUnqualified()) { 3751 const Type *CT = T->getCanonicalTypeInternal().getTypePtr(); 3752 ensure(CT); 3753 T->TypeBits.CacheValid = true; 3754 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage; 3755 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed; 3756 return; 3757 } 3758 3759 // Compute the cached properties and then set the cache. 3760 CachedProperties Result = computeCachedProperties(T); 3761 T->TypeBits.CacheValid = true; 3762 T->TypeBits.CachedLinkage = Result.getLinkage(); 3763 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType(); 3764 } 3765 }; 3766 3767 } // namespace clang 3768 3769 // Instantiate the friend template at a private class. In a 3770 // reasonable implementation, these symbols will be internal. 3771 // It is terrible that this is the best way to accomplish this. 3772 namespace { 3773 3774 class Private {}; 3775 3776 } // namespace 3777 3778 using Cache = TypePropertyCache<Private>; 3779 3780 static CachedProperties computeCachedProperties(const Type *T) { 3781 switch (T->getTypeClass()) { 3782 #define TYPE(Class,Base) 3783 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3784 #include "clang/AST/TypeNodes.inc" 3785 llvm_unreachable("didn't expect a non-canonical type here"); 3786 3787 #define TYPE(Class,Base) 3788 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3789 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3790 #include "clang/AST/TypeNodes.inc" 3791 // Treat instantiation-dependent types as external. 3792 if (!T->isInstantiationDependentType()) T->dump(); 3793 assert(T->isInstantiationDependentType()); 3794 return CachedProperties(ExternalLinkage, false); 3795 3796 case Type::Auto: 3797 case Type::DeducedTemplateSpecialization: 3798 // Give non-deduced 'auto' types external linkage. We should only see them 3799 // here in error recovery. 3800 return CachedProperties(ExternalLinkage, false); 3801 3802 case Type::ExtInt: 3803 case Type::Builtin: 3804 // C++ [basic.link]p8: 3805 // A type is said to have linkage if and only if: 3806 // - it is a fundamental type (3.9.1); or 3807 return CachedProperties(ExternalLinkage, false); 3808 3809 case Type::Record: 3810 case Type::Enum: { 3811 const TagDecl *Tag = cast<TagType>(T)->getDecl(); 3812 3813 // C++ [basic.link]p8: 3814 // - it is a class or enumeration type that is named (or has a name 3815 // for linkage purposes (7.1.3)) and the name has linkage; or 3816 // - it is a specialization of a class template (14); or 3817 Linkage L = Tag->getLinkageInternal(); 3818 bool IsLocalOrUnnamed = 3819 Tag->getDeclContext()->isFunctionOrMethod() || 3820 !Tag->hasNameForLinkage(); 3821 return CachedProperties(L, IsLocalOrUnnamed); 3822 } 3823 3824 // C++ [basic.link]p8: 3825 // - it is a compound type (3.9.2) other than a class or enumeration, 3826 // compounded exclusively from types that have linkage; or 3827 case Type::Complex: 3828 return Cache::get(cast<ComplexType>(T)->getElementType()); 3829 case Type::Pointer: 3830 return Cache::get(cast<PointerType>(T)->getPointeeType()); 3831 case Type::BlockPointer: 3832 return Cache::get(cast<BlockPointerType>(T)->getPointeeType()); 3833 case Type::LValueReference: 3834 case Type::RValueReference: 3835 return Cache::get(cast<ReferenceType>(T)->getPointeeType()); 3836 case Type::MemberPointer: { 3837 const auto *MPT = cast<MemberPointerType>(T); 3838 return merge(Cache::get(MPT->getClass()), 3839 Cache::get(MPT->getPointeeType())); 3840 } 3841 case Type::ConstantArray: 3842 case Type::IncompleteArray: 3843 case Type::VariableArray: 3844 return Cache::get(cast<ArrayType>(T)->getElementType()); 3845 case Type::Vector: 3846 case Type::ExtVector: 3847 return Cache::get(cast<VectorType>(T)->getElementType()); 3848 case Type::ConstantMatrix: 3849 return Cache::get(cast<ConstantMatrixType>(T)->getElementType()); 3850 case Type::FunctionNoProto: 3851 return Cache::get(cast<FunctionType>(T)->getReturnType()); 3852 case Type::FunctionProto: { 3853 const auto *FPT = cast<FunctionProtoType>(T); 3854 CachedProperties result = Cache::get(FPT->getReturnType()); 3855 for (const auto &ai : FPT->param_types()) 3856 result = merge(result, Cache::get(ai)); 3857 return result; 3858 } 3859 case Type::ObjCInterface: { 3860 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal(); 3861 return CachedProperties(L, false); 3862 } 3863 case Type::ObjCObject: 3864 return Cache::get(cast<ObjCObjectType>(T)->getBaseType()); 3865 case Type::ObjCObjectPointer: 3866 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType()); 3867 case Type::Atomic: 3868 return Cache::get(cast<AtomicType>(T)->getValueType()); 3869 case Type::Pipe: 3870 return Cache::get(cast<PipeType>(T)->getElementType()); 3871 } 3872 3873 llvm_unreachable("unhandled type class"); 3874 } 3875 3876 /// Determine the linkage of this type. 3877 Linkage Type::getLinkage() const { 3878 Cache::ensure(this); 3879 return TypeBits.getLinkage(); 3880 } 3881 3882 bool Type::hasUnnamedOrLocalType() const { 3883 Cache::ensure(this); 3884 return TypeBits.hasLocalOrUnnamedType(); 3885 } 3886 3887 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) { 3888 switch (T->getTypeClass()) { 3889 #define TYPE(Class,Base) 3890 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class: 3891 #include "clang/AST/TypeNodes.inc" 3892 llvm_unreachable("didn't expect a non-canonical type here"); 3893 3894 #define TYPE(Class,Base) 3895 #define DEPENDENT_TYPE(Class,Base) case Type::Class: 3896 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class: 3897 #include "clang/AST/TypeNodes.inc" 3898 // Treat instantiation-dependent types as external. 3899 assert(T->isInstantiationDependentType()); 3900 return LinkageInfo::external(); 3901 3902 case Type::ExtInt: 3903 case Type::Builtin: 3904 return LinkageInfo::external(); 3905 3906 case Type::Auto: 3907 case Type::DeducedTemplateSpecialization: 3908 return LinkageInfo::external(); 3909 3910 case Type::Record: 3911 case Type::Enum: 3912 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl()); 3913 3914 case Type::Complex: 3915 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType()); 3916 case Type::Pointer: 3917 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType()); 3918 case Type::BlockPointer: 3919 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType()); 3920 case Type::LValueReference: 3921 case Type::RValueReference: 3922 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType()); 3923 case Type::MemberPointer: { 3924 const auto *MPT = cast<MemberPointerType>(T); 3925 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass()); 3926 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType())); 3927 return LV; 3928 } 3929 case Type::ConstantArray: 3930 case Type::IncompleteArray: 3931 case Type::VariableArray: 3932 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType()); 3933 case Type::Vector: 3934 case Type::ExtVector: 3935 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType()); 3936 case Type::ConstantMatrix: 3937 return computeTypeLinkageInfo( 3938 cast<ConstantMatrixType>(T)->getElementType()); 3939 case Type::FunctionNoProto: 3940 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType()); 3941 case Type::FunctionProto: { 3942 const auto *FPT = cast<FunctionProtoType>(T); 3943 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType()); 3944 for (const auto &ai : FPT->param_types()) 3945 LV.merge(computeTypeLinkageInfo(ai)); 3946 return LV; 3947 } 3948 case Type::ObjCInterface: 3949 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl()); 3950 case Type::ObjCObject: 3951 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType()); 3952 case Type::ObjCObjectPointer: 3953 return computeTypeLinkageInfo( 3954 cast<ObjCObjectPointerType>(T)->getPointeeType()); 3955 case Type::Atomic: 3956 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType()); 3957 case Type::Pipe: 3958 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType()); 3959 } 3960 3961 llvm_unreachable("unhandled type class"); 3962 } 3963 3964 bool Type::isLinkageValid() const { 3965 if (!TypeBits.isCacheValid()) 3966 return true; 3967 3968 Linkage L = LinkageComputer{} 3969 .computeTypeLinkageInfo(getCanonicalTypeInternal()) 3970 .getLinkage(); 3971 return L == TypeBits.getLinkage(); 3972 } 3973 3974 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) { 3975 if (!T->isCanonicalUnqualified()) 3976 return computeTypeLinkageInfo(T->getCanonicalTypeInternal()); 3977 3978 LinkageInfo LV = computeTypeLinkageInfo(T); 3979 assert(LV.getLinkage() == T->getLinkage()); 3980 return LV; 3981 } 3982 3983 LinkageInfo Type::getLinkageAndVisibility() const { 3984 return LinkageComputer{}.getTypeLinkageAndVisibility(this); 3985 } 3986 3987 Optional<NullabilityKind> 3988 Type::getNullability(const ASTContext &Context) const { 3989 QualType Type(this, 0); 3990 while (const auto *AT = Type->getAs<AttributedType>()) { 3991 // Check whether this is an attributed type with nullability 3992 // information. 3993 if (auto Nullability = AT->getImmediateNullability()) 3994 return Nullability; 3995 3996 Type = AT->getEquivalentType(); 3997 } 3998 return None; 3999 } 4000 4001 bool Type::canHaveNullability(bool ResultIfUnknown) const { 4002 QualType type = getCanonicalTypeInternal(); 4003 4004 switch (type->getTypeClass()) { 4005 // We'll only see canonical types here. 4006 #define NON_CANONICAL_TYPE(Class, Parent) \ 4007 case Type::Class: \ 4008 llvm_unreachable("non-canonical type"); 4009 #define TYPE(Class, Parent) 4010 #include "clang/AST/TypeNodes.inc" 4011 4012 // Pointer types. 4013 case Type::Pointer: 4014 case Type::BlockPointer: 4015 case Type::MemberPointer: 4016 case Type::ObjCObjectPointer: 4017 return true; 4018 4019 // Dependent types that could instantiate to pointer types. 4020 case Type::UnresolvedUsing: 4021 case Type::TypeOfExpr: 4022 case Type::TypeOf: 4023 case Type::Decltype: 4024 case Type::UnaryTransform: 4025 case Type::TemplateTypeParm: 4026 case Type::SubstTemplateTypeParmPack: 4027 case Type::DependentName: 4028 case Type::DependentTemplateSpecialization: 4029 case Type::Auto: 4030 return ResultIfUnknown; 4031 4032 // Dependent template specializations can instantiate to pointer 4033 // types unless they're known to be specializations of a class 4034 // template. 4035 case Type::TemplateSpecialization: 4036 if (TemplateDecl *templateDecl 4037 = cast<TemplateSpecializationType>(type.getTypePtr()) 4038 ->getTemplateName().getAsTemplateDecl()) { 4039 if (isa<ClassTemplateDecl>(templateDecl)) 4040 return false; 4041 } 4042 return ResultIfUnknown; 4043 4044 case Type::Builtin: 4045 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) { 4046 // Signed, unsigned, and floating-point types cannot have nullability. 4047 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4048 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id: 4049 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id: 4050 #define BUILTIN_TYPE(Id, SingletonId) 4051 #include "clang/AST/BuiltinTypes.def" 4052 return false; 4053 4054 // Dependent types that could instantiate to a pointer type. 4055 case BuiltinType::Dependent: 4056 case BuiltinType::Overload: 4057 case BuiltinType::BoundMember: 4058 case BuiltinType::PseudoObject: 4059 case BuiltinType::UnknownAny: 4060 case BuiltinType::ARCUnbridgedCast: 4061 return ResultIfUnknown; 4062 4063 case BuiltinType::Void: 4064 case BuiltinType::ObjCId: 4065 case BuiltinType::ObjCClass: 4066 case BuiltinType::ObjCSel: 4067 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 4068 case BuiltinType::Id: 4069 #include "clang/Basic/OpenCLImageTypes.def" 4070 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 4071 case BuiltinType::Id: 4072 #include "clang/Basic/OpenCLExtensionTypes.def" 4073 case BuiltinType::OCLSampler: 4074 case BuiltinType::OCLEvent: 4075 case BuiltinType::OCLClkEvent: 4076 case BuiltinType::OCLQueue: 4077 case BuiltinType::OCLReserveID: 4078 #define SVE_TYPE(Name, Id, SingletonId) \ 4079 case BuiltinType::Id: 4080 #include "clang/Basic/AArch64SVEACLETypes.def" 4081 case BuiltinType::BuiltinFn: 4082 case BuiltinType::NullPtr: 4083 case BuiltinType::IncompleteMatrixIdx: 4084 case BuiltinType::OMPArraySection: 4085 case BuiltinType::OMPArrayShaping: 4086 case BuiltinType::OMPIterator: 4087 return false; 4088 } 4089 llvm_unreachable("unknown builtin type"); 4090 4091 // Non-pointer types. 4092 case Type::Complex: 4093 case Type::LValueReference: 4094 case Type::RValueReference: 4095 case Type::ConstantArray: 4096 case Type::IncompleteArray: 4097 case Type::VariableArray: 4098 case Type::DependentSizedArray: 4099 case Type::DependentVector: 4100 case Type::DependentSizedExtVector: 4101 case Type::Vector: 4102 case Type::ExtVector: 4103 case Type::ConstantMatrix: 4104 case Type::DependentSizedMatrix: 4105 case Type::DependentAddressSpace: 4106 case Type::FunctionProto: 4107 case Type::FunctionNoProto: 4108 case Type::Record: 4109 case Type::DeducedTemplateSpecialization: 4110 case Type::Enum: 4111 case Type::InjectedClassName: 4112 case Type::PackExpansion: 4113 case Type::ObjCObject: 4114 case Type::ObjCInterface: 4115 case Type::Atomic: 4116 case Type::Pipe: 4117 case Type::ExtInt: 4118 case Type::DependentExtInt: 4119 return false; 4120 } 4121 llvm_unreachable("bad type kind!"); 4122 } 4123 4124 llvm::Optional<NullabilityKind> 4125 AttributedType::getImmediateNullability() const { 4126 if (getAttrKind() == attr::TypeNonNull) 4127 return NullabilityKind::NonNull; 4128 if (getAttrKind() == attr::TypeNullable) 4129 return NullabilityKind::Nullable; 4130 if (getAttrKind() == attr::TypeNullUnspecified) 4131 return NullabilityKind::Unspecified; 4132 return None; 4133 } 4134 4135 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) { 4136 QualType AttrTy = T; 4137 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T)) 4138 AttrTy = MacroTy->getUnderlyingType(); 4139 4140 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) { 4141 if (auto nullability = attributed->getImmediateNullability()) { 4142 T = attributed->getModifiedType(); 4143 return nullability; 4144 } 4145 } 4146 4147 return None; 4148 } 4149 4150 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const { 4151 const auto *objcPtr = getAs<ObjCObjectPointerType>(); 4152 if (!objcPtr) 4153 return false; 4154 4155 if (objcPtr->isObjCIdType()) { 4156 // id is always okay. 4157 return true; 4158 } 4159 4160 // Blocks are NSObjects. 4161 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) { 4162 if (iface->getIdentifier() != ctx.getNSObjectName()) 4163 return false; 4164 4165 // Continue to check qualifiers, below. 4166 } else if (objcPtr->isObjCQualifiedIdType()) { 4167 // Continue to check qualifiers, below. 4168 } else { 4169 return false; 4170 } 4171 4172 // Check protocol qualifiers. 4173 for (ObjCProtocolDecl *proto : objcPtr->quals()) { 4174 // Blocks conform to NSObject and NSCopying. 4175 if (proto->getIdentifier() != ctx.getNSObjectName() && 4176 proto->getIdentifier() != ctx.getNSCopyingName()) 4177 return false; 4178 } 4179 4180 return true; 4181 } 4182 4183 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const { 4184 if (isObjCARCImplicitlyUnretainedType()) 4185 return Qualifiers::OCL_ExplicitNone; 4186 return Qualifiers::OCL_Strong; 4187 } 4188 4189 bool Type::isObjCARCImplicitlyUnretainedType() const { 4190 assert(isObjCLifetimeType() && 4191 "cannot query implicit lifetime for non-inferrable type"); 4192 4193 const Type *canon = getCanonicalTypeInternal().getTypePtr(); 4194 4195 // Walk down to the base type. We don't care about qualifiers for this. 4196 while (const auto *array = dyn_cast<ArrayType>(canon)) 4197 canon = array->getElementType().getTypePtr(); 4198 4199 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) { 4200 // Class and Class<Protocol> don't require retention. 4201 if (opt->getObjectType()->isObjCClass()) 4202 return true; 4203 } 4204 4205 return false; 4206 } 4207 4208 bool Type::isObjCNSObjectType() const { 4209 const Type *cur = this; 4210 while (true) { 4211 if (const auto *typedefType = dyn_cast<TypedefType>(cur)) 4212 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>(); 4213 4214 // Single-step desugar until we run out of sugar. 4215 QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType(); 4216 if (next.getTypePtr() == cur) return false; 4217 cur = next.getTypePtr(); 4218 } 4219 } 4220 4221 bool Type::isObjCIndependentClassType() const { 4222 if (const auto *typedefType = dyn_cast<TypedefType>(this)) 4223 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>(); 4224 return false; 4225 } 4226 4227 bool Type::isObjCRetainableType() const { 4228 return isObjCObjectPointerType() || 4229 isBlockPointerType() || 4230 isObjCNSObjectType(); 4231 } 4232 4233 bool Type::isObjCIndirectLifetimeType() const { 4234 if (isObjCLifetimeType()) 4235 return true; 4236 if (const auto *OPT = getAs<PointerType>()) 4237 return OPT->getPointeeType()->isObjCIndirectLifetimeType(); 4238 if (const auto *Ref = getAs<ReferenceType>()) 4239 return Ref->getPointeeType()->isObjCIndirectLifetimeType(); 4240 if (const auto *MemPtr = getAs<MemberPointerType>()) 4241 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType(); 4242 return false; 4243 } 4244 4245 /// Returns true if objects of this type have lifetime semantics under 4246 /// ARC. 4247 bool Type::isObjCLifetimeType() const { 4248 const Type *type = this; 4249 while (const ArrayType *array = type->getAsArrayTypeUnsafe()) 4250 type = array->getElementType().getTypePtr(); 4251 return type->isObjCRetainableType(); 4252 } 4253 4254 /// Determine whether the given type T is a "bridgable" Objective-C type, 4255 /// which is either an Objective-C object pointer type or an 4256 bool Type::isObjCARCBridgableType() const { 4257 return isObjCObjectPointerType() || isBlockPointerType(); 4258 } 4259 4260 /// Determine whether the given type T is a "bridgeable" C type. 4261 bool Type::isCARCBridgableType() const { 4262 const auto *Pointer = getAs<PointerType>(); 4263 if (!Pointer) 4264 return false; 4265 4266 QualType Pointee = Pointer->getPointeeType(); 4267 return Pointee->isVoidType() || Pointee->isRecordType(); 4268 } 4269 4270 /// Check if the specified type is the CUDA device builtin surface type. 4271 bool Type::isCUDADeviceBuiltinSurfaceType() const { 4272 if (const auto *RT = getAs<RecordType>()) 4273 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>(); 4274 return false; 4275 } 4276 4277 /// Check if the specified type is the CUDA device builtin texture type. 4278 bool Type::isCUDADeviceBuiltinTextureType() const { 4279 if (const auto *RT = getAs<RecordType>()) 4280 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>(); 4281 return false; 4282 } 4283 4284 bool Type::hasSizedVLAType() const { 4285 if (!isVariablyModifiedType()) return false; 4286 4287 if (const auto *ptr = getAs<PointerType>()) 4288 return ptr->getPointeeType()->hasSizedVLAType(); 4289 if (const auto *ref = getAs<ReferenceType>()) 4290 return ref->getPointeeType()->hasSizedVLAType(); 4291 if (const ArrayType *arr = getAsArrayTypeUnsafe()) { 4292 if (isa<VariableArrayType>(arr) && 4293 cast<VariableArrayType>(arr)->getSizeExpr()) 4294 return true; 4295 4296 return arr->getElementType()->hasSizedVLAType(); 4297 } 4298 4299 return false; 4300 } 4301 4302 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) { 4303 switch (type.getObjCLifetime()) { 4304 case Qualifiers::OCL_None: 4305 case Qualifiers::OCL_ExplicitNone: 4306 case Qualifiers::OCL_Autoreleasing: 4307 break; 4308 4309 case Qualifiers::OCL_Strong: 4310 return DK_objc_strong_lifetime; 4311 case Qualifiers::OCL_Weak: 4312 return DK_objc_weak_lifetime; 4313 } 4314 4315 if (const auto *RT = 4316 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) { 4317 const RecordDecl *RD = RT->getDecl(); 4318 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4319 /// Check if this is a C++ object with a non-trivial destructor. 4320 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor()) 4321 return DK_cxx_destructor; 4322 } else { 4323 /// Check if this is a C struct that is non-trivial to destroy or an array 4324 /// that contains such a struct. 4325 if (RD->isNonTrivialToPrimitiveDestroy()) 4326 return DK_nontrivial_c_struct; 4327 } 4328 } 4329 4330 return DK_none; 4331 } 4332 4333 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const { 4334 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl(); 4335 } 4336 4337 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str, 4338 llvm::APSInt Val, unsigned Scale) { 4339 FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(), 4340 /*IsSaturated=*/false, 4341 /*HasUnsignedPadding=*/false); 4342 APFixedPoint(Val, FXSema).toString(Str); 4343 } 4344 4345 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 4346 TypeDependence ExtraDependence, 4347 ConceptDecl *TypeConstraintConcept, 4348 ArrayRef<TemplateArgument> TypeConstraintArgs) 4349 : DeducedType(Auto, DeducedAsType, ExtraDependence) { 4350 AutoTypeBits.Keyword = (unsigned)Keyword; 4351 AutoTypeBits.NumArgs = TypeConstraintArgs.size(); 4352 this->TypeConstraintConcept = TypeConstraintConcept; 4353 if (TypeConstraintConcept) { 4354 TemplateArgument *ArgBuffer = getArgBuffer(); 4355 for (const TemplateArgument &Arg : TypeConstraintArgs) { 4356 addDependence(toTypeDependence( 4357 Arg.getDependence() & TemplateArgumentDependence::UnexpandedPack)); 4358 4359 new (ArgBuffer++) TemplateArgument(Arg); 4360 } 4361 } 4362 } 4363 4364 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4365 QualType Deduced, AutoTypeKeyword Keyword, 4366 bool IsDependent, ConceptDecl *CD, 4367 ArrayRef<TemplateArgument> Arguments) { 4368 ID.AddPointer(Deduced.getAsOpaquePtr()); 4369 ID.AddInteger((unsigned)Keyword); 4370 ID.AddBoolean(IsDependent); 4371 ID.AddPointer(CD); 4372 for (const TemplateArgument &Arg : Arguments) 4373 Arg.Profile(ID, Context); 4374 } 4375