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