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