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