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