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