1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// C Language Family Type Representation 11 /// 12 /// This file defines the clang::Type interface and subclasses, used to 13 /// represent types for languages in the C family. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_CLANG_AST_TYPE_H 18 #define LLVM_CLANG_AST_TYPE_H 19 20 #include "clang/AST/DependenceFlags.h" 21 #include "clang/AST/NestedNameSpecifier.h" 22 #include "clang/AST/TemplateName.h" 23 #include "clang/Basic/AddressSpaces.h" 24 #include "clang/Basic/AttrKinds.h" 25 #include "clang/Basic/Diagnostic.h" 26 #include "clang/Basic/ExceptionSpecificationType.h" 27 #include "clang/Basic/LLVM.h" 28 #include "clang/Basic/Linkage.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceLocation.h" 31 #include "clang/Basic/Specifiers.h" 32 #include "clang/Basic/Visibility.h" 33 #include "llvm/ADT/APInt.h" 34 #include "llvm/ADT/APSInt.h" 35 #include "llvm/ADT/ArrayRef.h" 36 #include "llvm/ADT/FoldingSet.h" 37 #include "llvm/ADT/None.h" 38 #include "llvm/ADT/Optional.h" 39 #include "llvm/ADT/PointerIntPair.h" 40 #include "llvm/ADT/PointerUnion.h" 41 #include "llvm/ADT/StringRef.h" 42 #include "llvm/ADT/Twine.h" 43 #include "llvm/ADT/iterator_range.h" 44 #include "llvm/Support/Casting.h" 45 #include "llvm/Support/Compiler.h" 46 #include "llvm/Support/ErrorHandling.h" 47 #include "llvm/Support/PointerLikeTypeTraits.h" 48 #include "llvm/Support/TrailingObjects.h" 49 #include "llvm/Support/type_traits.h" 50 #include <cassert> 51 #include <cstddef> 52 #include <cstdint> 53 #include <cstring> 54 #include <string> 55 #include <type_traits> 56 #include <utility> 57 58 namespace clang { 59 60 class BTFTypeTagAttr; 61 class ExtQuals; 62 class QualType; 63 class ConceptDecl; 64 class TagDecl; 65 class TemplateParameterList; 66 class Type; 67 68 enum { 69 TypeAlignmentInBits = 4, 70 TypeAlignment = 1 << TypeAlignmentInBits 71 }; 72 73 namespace serialization { 74 template <class T> class AbstractTypeReader; 75 template <class T> class AbstractTypeWriter; 76 } 77 78 } // namespace clang 79 80 namespace llvm { 81 82 template <typename T> 83 struct PointerLikeTypeTraits; 84 template<> 85 struct PointerLikeTypeTraits< ::clang::Type*> { 86 static inline void *getAsVoidPointer(::clang::Type *P) { return P; } 87 88 static inline ::clang::Type *getFromVoidPointer(void *P) { 89 return static_cast< ::clang::Type*>(P); 90 } 91 92 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; 93 }; 94 95 template<> 96 struct PointerLikeTypeTraits< ::clang::ExtQuals*> { 97 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } 98 99 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { 100 return static_cast< ::clang::ExtQuals*>(P); 101 } 102 103 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits; 104 }; 105 106 } // namespace llvm 107 108 namespace clang { 109 110 class ASTContext; 111 template <typename> class CanQual; 112 class CXXRecordDecl; 113 class DeclContext; 114 class EnumDecl; 115 class Expr; 116 class ExtQualsTypeCommonBase; 117 class FunctionDecl; 118 class IdentifierInfo; 119 class NamedDecl; 120 class ObjCInterfaceDecl; 121 class ObjCProtocolDecl; 122 class ObjCTypeParamDecl; 123 struct PrintingPolicy; 124 class RecordDecl; 125 class Stmt; 126 class TagDecl; 127 class TemplateArgument; 128 class TemplateArgumentListInfo; 129 class TemplateArgumentLoc; 130 class TemplateTypeParmDecl; 131 class TypedefNameDecl; 132 class UnresolvedUsingTypenameDecl; 133 class UsingShadowDecl; 134 135 using CanQualType = CanQual<Type>; 136 137 // Provide forward declarations for all of the *Type classes. 138 #define TYPE(Class, Base) class Class##Type; 139 #include "clang/AST/TypeNodes.inc" 140 141 /// The collection of all-type qualifiers we support. 142 /// Clang supports five independent qualifiers: 143 /// * C99: const, volatile, and restrict 144 /// * MS: __unaligned 145 /// * Embedded C (TR18037): address spaces 146 /// * Objective C: the GC attributes (none, weak, or strong) 147 class Qualifiers { 148 public: 149 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. 150 Const = 0x1, 151 Restrict = 0x2, 152 Volatile = 0x4, 153 CVRMask = Const | Volatile | Restrict 154 }; 155 156 enum GC { 157 GCNone = 0, 158 Weak, 159 Strong 160 }; 161 162 enum ObjCLifetime { 163 /// There is no lifetime qualification on this type. 164 OCL_None, 165 166 /// This object can be modified without requiring retains or 167 /// releases. 168 OCL_ExplicitNone, 169 170 /// Assigning into this object requires the old value to be 171 /// released and the new value to be retained. The timing of the 172 /// release of the old value is inexact: it may be moved to 173 /// immediately after the last known point where the value is 174 /// live. 175 OCL_Strong, 176 177 /// Reading or writing from this object requires a barrier call. 178 OCL_Weak, 179 180 /// Assigning into this object requires a lifetime extension. 181 OCL_Autoreleasing 182 }; 183 184 enum { 185 /// The maximum supported address space number. 186 /// 23 bits should be enough for anyone. 187 MaxAddressSpace = 0x7fffffu, 188 189 /// The width of the "fast" qualifier mask. 190 FastWidth = 3, 191 192 /// The fast qualifier mask. 193 FastMask = (1 << FastWidth) - 1 194 }; 195 196 /// Returns the common set of qualifiers while removing them from 197 /// the given sets. 198 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { 199 // If both are only CVR-qualified, bit operations are sufficient. 200 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { 201 Qualifiers Q; 202 Q.Mask = L.Mask & R.Mask; 203 L.Mask &= ~Q.Mask; 204 R.Mask &= ~Q.Mask; 205 return Q; 206 } 207 208 Qualifiers Q; 209 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); 210 Q.addCVRQualifiers(CommonCRV); 211 L.removeCVRQualifiers(CommonCRV); 212 R.removeCVRQualifiers(CommonCRV); 213 214 if (L.getObjCGCAttr() == R.getObjCGCAttr()) { 215 Q.setObjCGCAttr(L.getObjCGCAttr()); 216 L.removeObjCGCAttr(); 217 R.removeObjCGCAttr(); 218 } 219 220 if (L.getObjCLifetime() == R.getObjCLifetime()) { 221 Q.setObjCLifetime(L.getObjCLifetime()); 222 L.removeObjCLifetime(); 223 R.removeObjCLifetime(); 224 } 225 226 if (L.getAddressSpace() == R.getAddressSpace()) { 227 Q.setAddressSpace(L.getAddressSpace()); 228 L.removeAddressSpace(); 229 R.removeAddressSpace(); 230 } 231 return Q; 232 } 233 234 static Qualifiers fromFastMask(unsigned Mask) { 235 Qualifiers Qs; 236 Qs.addFastQualifiers(Mask); 237 return Qs; 238 } 239 240 static Qualifiers fromCVRMask(unsigned CVR) { 241 Qualifiers Qs; 242 Qs.addCVRQualifiers(CVR); 243 return Qs; 244 } 245 246 static Qualifiers fromCVRUMask(unsigned CVRU) { 247 Qualifiers Qs; 248 Qs.addCVRUQualifiers(CVRU); 249 return Qs; 250 } 251 252 // Deserialize qualifiers from an opaque representation. 253 static Qualifiers fromOpaqueValue(unsigned opaque) { 254 Qualifiers Qs; 255 Qs.Mask = opaque; 256 return Qs; 257 } 258 259 // Serialize these qualifiers into an opaque representation. 260 unsigned getAsOpaqueValue() const { 261 return Mask; 262 } 263 264 bool hasConst() const { return Mask & Const; } 265 bool hasOnlyConst() const { return Mask == Const; } 266 void removeConst() { Mask &= ~Const; } 267 void addConst() { Mask |= Const; } 268 Qualifiers withConst() const { 269 Qualifiers Qs = *this; 270 Qs.addConst(); 271 return Qs; 272 } 273 274 bool hasVolatile() const { return Mask & Volatile; } 275 bool hasOnlyVolatile() const { return Mask == Volatile; } 276 void removeVolatile() { Mask &= ~Volatile; } 277 void addVolatile() { Mask |= Volatile; } 278 Qualifiers withVolatile() const { 279 Qualifiers Qs = *this; 280 Qs.addVolatile(); 281 return Qs; 282 } 283 284 bool hasRestrict() const { return Mask & Restrict; } 285 bool hasOnlyRestrict() const { return Mask == Restrict; } 286 void removeRestrict() { Mask &= ~Restrict; } 287 void addRestrict() { Mask |= Restrict; } 288 Qualifiers withRestrict() const { 289 Qualifiers Qs = *this; 290 Qs.addRestrict(); 291 return Qs; 292 } 293 294 bool hasCVRQualifiers() const { return getCVRQualifiers(); } 295 unsigned getCVRQualifiers() const { return Mask & CVRMask; } 296 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } 297 298 void setCVRQualifiers(unsigned mask) { 299 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 300 Mask = (Mask & ~CVRMask) | mask; 301 } 302 void removeCVRQualifiers(unsigned mask) { 303 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 304 Mask &= ~mask; 305 } 306 void removeCVRQualifiers() { 307 removeCVRQualifiers(CVRMask); 308 } 309 void addCVRQualifiers(unsigned mask) { 310 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits"); 311 Mask |= mask; 312 } 313 void addCVRUQualifiers(unsigned mask) { 314 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"); 315 Mask |= mask; 316 } 317 318 bool hasUnaligned() const { return Mask & UMask; } 319 void setUnaligned(bool flag) { 320 Mask = (Mask & ~UMask) | (flag ? UMask : 0); 321 } 322 void removeUnaligned() { Mask &= ~UMask; } 323 void addUnaligned() { Mask |= UMask; } 324 325 bool hasObjCGCAttr() const { return Mask & GCAttrMask; } 326 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } 327 void setObjCGCAttr(GC type) { 328 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); 329 } 330 void removeObjCGCAttr() { setObjCGCAttr(GCNone); } 331 void addObjCGCAttr(GC type) { 332 assert(type); 333 setObjCGCAttr(type); 334 } 335 Qualifiers withoutObjCGCAttr() const { 336 Qualifiers qs = *this; 337 qs.removeObjCGCAttr(); 338 return qs; 339 } 340 Qualifiers withoutObjCLifetime() const { 341 Qualifiers qs = *this; 342 qs.removeObjCLifetime(); 343 return qs; 344 } 345 Qualifiers withoutAddressSpace() const { 346 Qualifiers qs = *this; 347 qs.removeAddressSpace(); 348 return qs; 349 } 350 351 bool hasObjCLifetime() const { return Mask & LifetimeMask; } 352 ObjCLifetime getObjCLifetime() const { 353 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); 354 } 355 void setObjCLifetime(ObjCLifetime type) { 356 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); 357 } 358 void removeObjCLifetime() { setObjCLifetime(OCL_None); } 359 void addObjCLifetime(ObjCLifetime type) { 360 assert(type); 361 assert(!hasObjCLifetime()); 362 Mask |= (type << LifetimeShift); 363 } 364 365 /// True if the lifetime is neither None or ExplicitNone. 366 bool hasNonTrivialObjCLifetime() const { 367 ObjCLifetime lifetime = getObjCLifetime(); 368 return (lifetime > OCL_ExplicitNone); 369 } 370 371 /// True if the lifetime is either strong or weak. 372 bool hasStrongOrWeakObjCLifetime() const { 373 ObjCLifetime lifetime = getObjCLifetime(); 374 return (lifetime == OCL_Strong || lifetime == OCL_Weak); 375 } 376 377 bool hasAddressSpace() const { return Mask & AddressSpaceMask; } 378 LangAS getAddressSpace() const { 379 return static_cast<LangAS>(Mask >> AddressSpaceShift); 380 } 381 bool hasTargetSpecificAddressSpace() const { 382 return isTargetAddressSpace(getAddressSpace()); 383 } 384 /// Get the address space attribute value to be printed by diagnostics. 385 unsigned getAddressSpaceAttributePrintValue() const { 386 auto Addr = getAddressSpace(); 387 // This function is not supposed to be used with language specific 388 // address spaces. If that happens, the diagnostic message should consider 389 // printing the QualType instead of the address space value. 390 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace()); 391 if (Addr != LangAS::Default) 392 return toTargetAddressSpace(Addr); 393 // TODO: The diagnostic messages where Addr may be 0 should be fixed 394 // since it cannot differentiate the situation where 0 denotes the default 395 // address space or user specified __attribute__((address_space(0))). 396 return 0; 397 } 398 void setAddressSpace(LangAS space) { 399 assert((unsigned)space <= MaxAddressSpace); 400 Mask = (Mask & ~AddressSpaceMask) 401 | (((uint32_t) space) << AddressSpaceShift); 402 } 403 void removeAddressSpace() { setAddressSpace(LangAS::Default); } 404 void addAddressSpace(LangAS space) { 405 assert(space != LangAS::Default); 406 setAddressSpace(space); 407 } 408 409 // Fast qualifiers are those that can be allocated directly 410 // on a QualType object. 411 bool hasFastQualifiers() const { return getFastQualifiers(); } 412 unsigned getFastQualifiers() const { return Mask & FastMask; } 413 void setFastQualifiers(unsigned mask) { 414 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 415 Mask = (Mask & ~FastMask) | mask; 416 } 417 void removeFastQualifiers(unsigned mask) { 418 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 419 Mask &= ~mask; 420 } 421 void removeFastQualifiers() { 422 removeFastQualifiers(FastMask); 423 } 424 void addFastQualifiers(unsigned mask) { 425 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"); 426 Mask |= mask; 427 } 428 429 /// Return true if the set contains any qualifiers which require an ExtQuals 430 /// node to be allocated. 431 bool hasNonFastQualifiers() const { return Mask & ~FastMask; } 432 Qualifiers getNonFastQualifiers() const { 433 Qualifiers Quals = *this; 434 Quals.setFastQualifiers(0); 435 return Quals; 436 } 437 438 /// Return true if the set contains any qualifiers. 439 bool hasQualifiers() const { return Mask; } 440 bool empty() const { return !Mask; } 441 442 /// Add the qualifiers from the given set to this set. 443 void addQualifiers(Qualifiers Q) { 444 // If the other set doesn't have any non-boolean qualifiers, just 445 // bit-or it in. 446 if (!(Q.Mask & ~CVRMask)) 447 Mask |= Q.Mask; 448 else { 449 Mask |= (Q.Mask & CVRMask); 450 if (Q.hasAddressSpace()) 451 addAddressSpace(Q.getAddressSpace()); 452 if (Q.hasObjCGCAttr()) 453 addObjCGCAttr(Q.getObjCGCAttr()); 454 if (Q.hasObjCLifetime()) 455 addObjCLifetime(Q.getObjCLifetime()); 456 } 457 } 458 459 /// Remove the qualifiers from the given set from this set. 460 void removeQualifiers(Qualifiers Q) { 461 // If the other set doesn't have any non-boolean qualifiers, just 462 // bit-and the inverse in. 463 if (!(Q.Mask & ~CVRMask)) 464 Mask &= ~Q.Mask; 465 else { 466 Mask &= ~(Q.Mask & CVRMask); 467 if (getObjCGCAttr() == Q.getObjCGCAttr()) 468 removeObjCGCAttr(); 469 if (getObjCLifetime() == Q.getObjCLifetime()) 470 removeObjCLifetime(); 471 if (getAddressSpace() == Q.getAddressSpace()) 472 removeAddressSpace(); 473 } 474 } 475 476 /// Add the qualifiers from the given set to this set, given that 477 /// they don't conflict. 478 void addConsistentQualifiers(Qualifiers qs) { 479 assert(getAddressSpace() == qs.getAddressSpace() || 480 !hasAddressSpace() || !qs.hasAddressSpace()); 481 assert(getObjCGCAttr() == qs.getObjCGCAttr() || 482 !hasObjCGCAttr() || !qs.hasObjCGCAttr()); 483 assert(getObjCLifetime() == qs.getObjCLifetime() || 484 !hasObjCLifetime() || !qs.hasObjCLifetime()); 485 Mask |= qs.Mask; 486 } 487 488 /// Returns true if address space A is equal to or a superset of B. 489 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of 490 /// overlapping address spaces. 491 /// CL1.1 or CL1.2: 492 /// every address space is a superset of itself. 493 /// CL2.0 adds: 494 /// __generic is a superset of any address space except for __constant. 495 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { 496 // Address spaces must match exactly. 497 return A == B || 498 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except 499 // for __constant can be used as __generic. 500 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) || 501 // We also define global_device and global_host address spaces, 502 // to distinguish global pointers allocated on host from pointers 503 // allocated on device, which are a subset of __global. 504 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device || 505 B == LangAS::opencl_global_host)) || 506 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device || 507 B == LangAS::sycl_global_host)) || 508 // Consider pointer size address spaces to be equivalent to default. 509 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) && 510 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) || 511 // Default is a superset of SYCL address spaces. 512 (A == LangAS::Default && 513 (B == LangAS::sycl_private || B == LangAS::sycl_local || 514 B == LangAS::sycl_global || B == LangAS::sycl_global_device || 515 B == LangAS::sycl_global_host)) || 516 // In HIP device compilation, any cuda address space is allowed 517 // to implicitly cast into the default address space. 518 (A == LangAS::Default && 519 (B == LangAS::cuda_constant || B == LangAS::cuda_device || 520 B == LangAS::cuda_shared)); 521 } 522 523 /// Returns true if the address space in these qualifiers is equal to or 524 /// a superset of the address space in the argument qualifiers. 525 bool isAddressSpaceSupersetOf(Qualifiers other) const { 526 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); 527 } 528 529 /// Determines if these qualifiers compatibly include another set. 530 /// Generally this answers the question of whether an object with the other 531 /// qualifiers can be safely used as an object with these qualifiers. 532 bool compatiblyIncludes(Qualifiers other) const { 533 return isAddressSpaceSupersetOf(other) && 534 // ObjC GC qualifiers can match, be added, or be removed, but can't 535 // be changed. 536 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || 537 !other.hasObjCGCAttr()) && 538 // ObjC lifetime qualifiers must match exactly. 539 getObjCLifetime() == other.getObjCLifetime() && 540 // CVR qualifiers may subset. 541 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && 542 // U qualifier may superset. 543 (!other.hasUnaligned() || hasUnaligned()); 544 } 545 546 /// Determines if these qualifiers compatibly include another set of 547 /// qualifiers from the narrow perspective of Objective-C ARC lifetime. 548 /// 549 /// One set of Objective-C lifetime qualifiers compatibly includes the other 550 /// if the lifetime qualifiers match, or if both are non-__weak and the 551 /// including set also contains the 'const' qualifier, or both are non-__weak 552 /// and one is None (which can only happen in non-ARC modes). 553 bool compatiblyIncludesObjCLifetime(Qualifiers other) const { 554 if (getObjCLifetime() == other.getObjCLifetime()) 555 return true; 556 557 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) 558 return false; 559 560 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) 561 return true; 562 563 return hasConst(); 564 } 565 566 /// Determine whether this set of qualifiers is a strict superset of 567 /// another set of qualifiers, not considering qualifier compatibility. 568 bool isStrictSupersetOf(Qualifiers Other) const; 569 570 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } 571 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } 572 573 explicit operator bool() const { return hasQualifiers(); } 574 575 Qualifiers &operator+=(Qualifiers R) { 576 addQualifiers(R); 577 return *this; 578 } 579 580 // Union two qualifier sets. If an enumerated qualifier appears 581 // in both sets, use the one from the right. 582 friend Qualifiers operator+(Qualifiers L, Qualifiers R) { 583 L += R; 584 return L; 585 } 586 587 Qualifiers &operator-=(Qualifiers R) { 588 removeQualifiers(R); 589 return *this; 590 } 591 592 /// Compute the difference between two qualifier sets. 593 friend Qualifiers operator-(Qualifiers L, Qualifiers R) { 594 L -= R; 595 return L; 596 } 597 598 std::string getAsString() const; 599 std::string getAsString(const PrintingPolicy &Policy) const; 600 601 static std::string getAddrSpaceAsString(LangAS AS); 602 603 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; 604 void print(raw_ostream &OS, const PrintingPolicy &Policy, 605 bool appendSpaceIfNonEmpty = false) const; 606 607 void Profile(llvm::FoldingSetNodeID &ID) const { 608 ID.AddInteger(Mask); 609 } 610 611 private: 612 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| 613 // |C R V|U|GCAttr|Lifetime|AddressSpace| 614 uint32_t Mask = 0; 615 616 static const uint32_t UMask = 0x8; 617 static const uint32_t UShift = 3; 618 static const uint32_t GCAttrMask = 0x30; 619 static const uint32_t GCAttrShift = 4; 620 static const uint32_t LifetimeMask = 0x1C0; 621 static const uint32_t LifetimeShift = 6; 622 static const uint32_t AddressSpaceMask = 623 ~(CVRMask | UMask | GCAttrMask | LifetimeMask); 624 static const uint32_t AddressSpaceShift = 9; 625 }; 626 627 class QualifiersAndAtomic { 628 Qualifiers Quals; 629 bool HasAtomic; 630 631 public: 632 QualifiersAndAtomic() : HasAtomic(false) {} 633 QualifiersAndAtomic(Qualifiers Quals, bool HasAtomic) 634 : Quals(Quals), HasAtomic(HasAtomic) {} 635 636 operator Qualifiers() const { return Quals; } 637 638 bool hasVolatile() const { return Quals.hasVolatile(); } 639 bool hasConst() const { return Quals.hasConst(); } 640 bool hasRestrict() const { return Quals.hasRestrict(); } 641 bool hasAtomic() const { return HasAtomic; } 642 643 void addVolatile() { Quals.addVolatile(); } 644 void addConst() { Quals.addConst(); } 645 void addRestrict() { Quals.addRestrict(); } 646 void addAtomic() { HasAtomic = true; } 647 648 void removeVolatile() { Quals.removeVolatile(); } 649 void removeConst() { Quals.removeConst(); } 650 void removeRestrict() { Quals.removeRestrict(); } 651 void removeAtomic() { HasAtomic = false; } 652 653 QualifiersAndAtomic withVolatile() { 654 return {Quals.withVolatile(), HasAtomic}; 655 } 656 QualifiersAndAtomic withConst() { return {Quals.withConst(), HasAtomic}; } 657 QualifiersAndAtomic withRestrict() { 658 return {Quals.withRestrict(), HasAtomic}; 659 } 660 QualifiersAndAtomic withAtomic() { return {Quals, true}; } 661 662 QualifiersAndAtomic &operator+=(Qualifiers RHS) { 663 Quals += RHS; 664 return *this; 665 } 666 }; 667 668 /// A std::pair-like structure for storing a qualified type split 669 /// into its local qualifiers and its locally-unqualified type. 670 struct SplitQualType { 671 /// The locally-unqualified type. 672 const Type *Ty = nullptr; 673 674 /// The local qualifiers. 675 Qualifiers Quals; 676 677 SplitQualType() = default; 678 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} 679 680 SplitQualType getSingleStepDesugaredType() const; // end of this file 681 682 // Make std::tie work. 683 std::pair<const Type *,Qualifiers> asPair() const { 684 return std::pair<const Type *, Qualifiers>(Ty, Quals); 685 } 686 687 friend bool operator==(SplitQualType a, SplitQualType b) { 688 return a.Ty == b.Ty && a.Quals == b.Quals; 689 } 690 friend bool operator!=(SplitQualType a, SplitQualType b) { 691 return a.Ty != b.Ty || a.Quals != b.Quals; 692 } 693 }; 694 695 /// The kind of type we are substituting Objective-C type arguments into. 696 /// 697 /// The kind of substitution affects the replacement of type parameters when 698 /// no concrete type information is provided, e.g., when dealing with an 699 /// unspecialized type. 700 enum class ObjCSubstitutionContext { 701 /// An ordinary type. 702 Ordinary, 703 704 /// The result type of a method or function. 705 Result, 706 707 /// The parameter type of a method or function. 708 Parameter, 709 710 /// The type of a property. 711 Property, 712 713 /// The superclass of a type. 714 Superclass, 715 }; 716 717 /// A (possibly-)qualified type. 718 /// 719 /// For efficiency, we don't store CV-qualified types as nodes on their 720 /// own: instead each reference to a type stores the qualifiers. This 721 /// greatly reduces the number of nodes we need to allocate for types (for 722 /// example we only need one for 'int', 'const int', 'volatile int', 723 /// 'const volatile int', etc). 724 /// 725 /// As an added efficiency bonus, instead of making this a pair, we 726 /// just store the two bits we care about in the low bits of the 727 /// pointer. To handle the packing/unpacking, we make QualType be a 728 /// simple wrapper class that acts like a smart pointer. A third bit 729 /// indicates whether there are extended qualifiers present, in which 730 /// case the pointer points to a special structure. 731 class QualType { 732 friend class QualifierCollector; 733 734 // Thankfully, these are efficiently composable. 735 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, 736 Qualifiers::FastWidth> Value; 737 738 const ExtQuals *getExtQualsUnsafe() const { 739 return Value.getPointer().get<const ExtQuals*>(); 740 } 741 742 const Type *getTypePtrUnsafe() const { 743 return Value.getPointer().get<const Type*>(); 744 } 745 746 const ExtQualsTypeCommonBase *getCommonPtr() const { 747 assert(!isNull() && "Cannot retrieve a NULL type pointer"); 748 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); 749 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); 750 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); 751 } 752 753 public: 754 QualType() = default; 755 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} 756 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} 757 758 unsigned getLocalFastQualifiers() const { return Value.getInt(); } 759 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } 760 761 /// Retrieves a pointer to the underlying (unqualified) type. 762 /// 763 /// This function requires that the type not be NULL. If the type might be 764 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). 765 const Type *getTypePtr() const; 766 767 const Type *getTypePtrOrNull() const; 768 769 /// Retrieves a pointer to the name of the base type. 770 const IdentifierInfo *getBaseTypeIdentifier() const; 771 772 /// Divides a QualType into its unqualified type and a set of local 773 /// qualifiers. 774 SplitQualType split() const; 775 776 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } 777 778 static QualType getFromOpaquePtr(const void *Ptr) { 779 QualType T; 780 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); 781 return T; 782 } 783 784 const Type &operator*() const { 785 return *getTypePtr(); 786 } 787 788 const Type *operator->() const { 789 return getTypePtr(); 790 } 791 792 bool isCanonical() const; 793 bool isCanonicalAsParam() const; 794 795 /// Return true if this QualType doesn't point to a type yet. 796 bool isNull() const { 797 return Value.getPointer().isNull(); 798 } 799 800 /// Determine whether this particular QualType instance has the 801 /// "const" qualifier set, without looking through typedefs that may have 802 /// added "const" at a different level. 803 bool isLocalConstQualified() const { 804 return (getLocalFastQualifiers() & Qualifiers::Const); 805 } 806 807 /// Determine whether this type is const-qualified. 808 bool isConstQualified() const; 809 810 /// Determine whether this particular QualType instance has the 811 /// "restrict" qualifier set, without looking through typedefs that may have 812 /// added "restrict" at a different level. 813 bool isLocalRestrictQualified() const { 814 return (getLocalFastQualifiers() & Qualifiers::Restrict); 815 } 816 817 /// Determine whether this type is restrict-qualified. 818 bool isRestrictQualified() const; 819 820 /// Determine whether this particular QualType instance has the 821 /// "volatile" qualifier set, without looking through typedefs that may have 822 /// added "volatile" at a different level. 823 bool isLocalVolatileQualified() const { 824 return (getLocalFastQualifiers() & Qualifiers::Volatile); 825 } 826 827 /// Determine whether this type is volatile-qualified. 828 bool isVolatileQualified() const; 829 830 /// Determine whether this particular QualType instance has any 831 /// qualifiers, without looking through any typedefs that might add 832 /// qualifiers at a different level. 833 bool hasLocalQualifiers() const { 834 return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); 835 } 836 837 /// Determine whether this type has any qualifiers. 838 bool hasQualifiers() const; 839 840 /// Determine whether this particular QualType instance has any 841 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType 842 /// instance. 843 bool hasLocalNonFastQualifiers() const { 844 return Value.getPointer().is<const ExtQuals*>(); 845 } 846 847 /// Retrieve the set of qualifiers local to this particular QualType 848 /// instance, not including any qualifiers acquired through typedefs or 849 /// other sugar. 850 Qualifiers getLocalQualifiers() const; 851 852 /// Retrieve the set of qualifiers applied to this type. 853 Qualifiers getQualifiers() const; 854 855 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers 856 /// local to this particular QualType instance, not including any qualifiers 857 /// acquired through typedefs or other sugar. 858 unsigned getLocalCVRQualifiers() const { 859 return getLocalFastQualifiers(); 860 } 861 862 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers 863 /// applied to this type. 864 unsigned getCVRQualifiers() const; 865 866 bool isConstant(const ASTContext& Ctx) const { 867 return QualType::isConstant(*this, Ctx); 868 } 869 870 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). 871 bool isPODType(const ASTContext &Context) const; 872 873 /// Return true if this is a POD type according to the rules of the C++98 874 /// standard, regardless of the current compilation's language. 875 bool isCXX98PODType(const ASTContext &Context) const; 876 877 /// Return true if this is a POD type according to the more relaxed rules 878 /// of the C++11 standard, regardless of the current compilation's language. 879 /// (C++0x [basic.types]p9). Note that, unlike 880 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. 881 bool isCXX11PODType(const ASTContext &Context) const; 882 883 /// Return true if this is a trivial type per (C++0x [basic.types]p9) 884 bool isTrivialType(const ASTContext &Context) const; 885 886 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) 887 bool isTriviallyCopyableType(const ASTContext &Context) const; 888 889 /// Return true if this is a trivially relocatable type. 890 bool isTriviallyRelocatableType(const ASTContext &Context) const; 891 892 /// Returns true if it is a class and it might be dynamic. 893 bool mayBeDynamicClass() const; 894 895 /// Returns true if it is not a class or if the class might not be dynamic. 896 bool mayBeNotDynamicClass() const; 897 898 // Don't promise in the API that anything besides 'const' can be 899 // easily added. 900 901 /// Add the `const` type qualifier to this QualType. 902 void addConst() { 903 addFastQualifiers(Qualifiers::Const); 904 } 905 QualType withConst() const { 906 return withFastQualifiers(Qualifiers::Const); 907 } 908 909 /// Add the `volatile` type qualifier to this QualType. 910 void addVolatile() { 911 addFastQualifiers(Qualifiers::Volatile); 912 } 913 QualType withVolatile() const { 914 return withFastQualifiers(Qualifiers::Volatile); 915 } 916 917 /// Add the `restrict` qualifier to this QualType. 918 void addRestrict() { 919 addFastQualifiers(Qualifiers::Restrict); 920 } 921 QualType withRestrict() const { 922 return withFastQualifiers(Qualifiers::Restrict); 923 } 924 925 QualType withCVRQualifiers(unsigned CVR) const { 926 return withFastQualifiers(CVR); 927 } 928 929 void addFastQualifiers(unsigned TQs) { 930 assert(!(TQs & ~Qualifiers::FastMask) 931 && "non-fast qualifier bits set in mask!"); 932 Value.setInt(Value.getInt() | TQs); 933 } 934 935 void removeLocalConst(); 936 void removeLocalVolatile(); 937 void removeLocalRestrict(); 938 void removeLocalCVRQualifiers(unsigned Mask); 939 940 void removeLocalFastQualifiers() { Value.setInt(0); } 941 void removeLocalFastQualifiers(unsigned Mask) { 942 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"); 943 Value.setInt(Value.getInt() & ~Mask); 944 } 945 946 // Creates a type with the given qualifiers in addition to any 947 // qualifiers already on this type. 948 QualType withFastQualifiers(unsigned TQs) const { 949 QualType T = *this; 950 T.addFastQualifiers(TQs); 951 return T; 952 } 953 954 // Creates a type with exactly the given fast qualifiers, removing 955 // any existing fast qualifiers. 956 QualType withExactLocalFastQualifiers(unsigned TQs) const { 957 return withoutLocalFastQualifiers().withFastQualifiers(TQs); 958 } 959 960 // Removes fast qualifiers, but leaves any extended qualifiers in place. 961 QualType withoutLocalFastQualifiers() const { 962 QualType T = *this; 963 T.removeLocalFastQualifiers(); 964 return T; 965 } 966 967 QualType getCanonicalType() const; 968 969 /// Return this type with all of the instance-specific qualifiers 970 /// removed, but without removing any qualifiers that may have been applied 971 /// through typedefs. 972 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } 973 974 /// Retrieve the unqualified variant of the given type, 975 /// removing as little sugar as possible. 976 /// 977 /// This routine looks through various kinds of sugar to find the 978 /// least-desugared type that is unqualified. For example, given: 979 /// 980 /// \code 981 /// typedef int Integer; 982 /// typedef const Integer CInteger; 983 /// typedef CInteger DifferenceType; 984 /// \endcode 985 /// 986 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will 987 /// desugar until we hit the type \c Integer, which has no qualifiers on it. 988 /// 989 /// The resulting type might still be qualified if it's sugar for an array 990 /// type. To strip qualifiers even from within a sugared array type, use 991 /// ASTContext::getUnqualifiedArrayType. 992 /// 993 /// Note: In C, the _Atomic qualifier is special (see C2x 6.2.5p29 for 994 /// details), and it is not stripped by this function. Use 995 /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic. 996 inline QualType getUnqualifiedType() const; 997 998 /// Retrieve the unqualified variant of the given type, removing as little 999 /// sugar as possible. 1000 /// 1001 /// Like getUnqualifiedType(), but also returns the set of 1002 /// qualifiers that were built up. 1003 /// 1004 /// The resulting type might still be qualified if it's sugar for an array 1005 /// type. To strip qualifiers even from within a sugared array type, use 1006 /// ASTContext::getUnqualifiedArrayType. 1007 inline SplitQualType getSplitUnqualifiedType() const; 1008 1009 /// Determine whether this type is more qualified than the other 1010 /// given type, requiring exact equality for non-CVR qualifiers. 1011 bool isMoreQualifiedThan(QualType Other) const; 1012 1013 /// Determine whether this type is at least as qualified as the other 1014 /// given type, requiring exact equality for non-CVR qualifiers. 1015 bool isAtLeastAsQualifiedAs(QualType Other) const; 1016 1017 QualType getNonReferenceType() const; 1018 1019 /// Determine the type of a (typically non-lvalue) expression with the 1020 /// specified result type. 1021 /// 1022 /// This routine should be used for expressions for which the return type is 1023 /// explicitly specified (e.g., in a cast or call) and isn't necessarily 1024 /// an lvalue. It removes a top-level reference (since there are no 1025 /// expressions of reference type) and deletes top-level cvr-qualifiers 1026 /// from non-class types (in C++) or all types (in C). 1027 QualType getNonLValueExprType(const ASTContext &Context) const; 1028 1029 /// Remove an outer pack expansion type (if any) from this type. Used as part 1030 /// of converting the type of a declaration to the type of an expression that 1031 /// references that expression. It's meaningless for an expression to have a 1032 /// pack expansion type. 1033 QualType getNonPackExpansionType() const; 1034 1035 /// Return the specified type with any "sugar" removed from 1036 /// the type. This takes off typedefs, typeof's etc. If the outer level of 1037 /// the type is already concrete, it returns it unmodified. This is similar 1038 /// to getting the canonical type, but it doesn't remove *all* typedefs. For 1039 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is 1040 /// concrete. 1041 /// 1042 /// Qualifiers are left in place. 1043 QualType getDesugaredType(const ASTContext &Context) const { 1044 return getDesugaredType(*this, Context); 1045 } 1046 1047 SplitQualType getSplitDesugaredType() const { 1048 return getSplitDesugaredType(*this); 1049 } 1050 1051 /// Return the specified type with one level of "sugar" removed from 1052 /// the type. 1053 /// 1054 /// This routine takes off the first typedef, typeof, etc. If the outer level 1055 /// of the type is already concrete, it returns it unmodified. 1056 QualType getSingleStepDesugaredType(const ASTContext &Context) const { 1057 return getSingleStepDesugaredTypeImpl(*this, Context); 1058 } 1059 1060 /// Returns the specified type after dropping any 1061 /// outer-level parentheses. 1062 QualType IgnoreParens() const { 1063 if (isa<ParenType>(*this)) 1064 return QualType::IgnoreParens(*this); 1065 return *this; 1066 } 1067 1068 /// Indicate whether the specified types and qualifiers are identical. 1069 friend bool operator==(const QualType &LHS, const QualType &RHS) { 1070 return LHS.Value == RHS.Value; 1071 } 1072 friend bool operator!=(const QualType &LHS, const QualType &RHS) { 1073 return LHS.Value != RHS.Value; 1074 } 1075 friend bool operator<(const QualType &LHS, const QualType &RHS) { 1076 return LHS.Value < RHS.Value; 1077 } 1078 1079 static std::string getAsString(SplitQualType split, 1080 const PrintingPolicy &Policy) { 1081 return getAsString(split.Ty, split.Quals, Policy); 1082 } 1083 static std::string getAsString(const Type *ty, Qualifiers qs, 1084 const PrintingPolicy &Policy); 1085 1086 std::string getAsString() const; 1087 std::string getAsString(const PrintingPolicy &Policy) const; 1088 1089 void print(raw_ostream &OS, const PrintingPolicy &Policy, 1090 const Twine &PlaceHolder = Twine(), 1091 unsigned Indentation = 0) const; 1092 1093 static void print(SplitQualType split, raw_ostream &OS, 1094 const PrintingPolicy &policy, const Twine &PlaceHolder, 1095 unsigned Indentation = 0) { 1096 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); 1097 } 1098 1099 static void print(const Type *ty, Qualifiers qs, 1100 raw_ostream &OS, const PrintingPolicy &policy, 1101 const Twine &PlaceHolder, 1102 unsigned Indentation = 0); 1103 1104 void getAsStringInternal(std::string &Str, 1105 const PrintingPolicy &Policy) const; 1106 1107 static void getAsStringInternal(SplitQualType split, std::string &out, 1108 const PrintingPolicy &policy) { 1109 return getAsStringInternal(split.Ty, split.Quals, out, policy); 1110 } 1111 1112 static void getAsStringInternal(const Type *ty, Qualifiers qs, 1113 std::string &out, 1114 const PrintingPolicy &policy); 1115 1116 class StreamedQualTypeHelper { 1117 const QualType &T; 1118 const PrintingPolicy &Policy; 1119 const Twine &PlaceHolder; 1120 unsigned Indentation; 1121 1122 public: 1123 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, 1124 const Twine &PlaceHolder, unsigned Indentation) 1125 : T(T), Policy(Policy), PlaceHolder(PlaceHolder), 1126 Indentation(Indentation) {} 1127 1128 friend raw_ostream &operator<<(raw_ostream &OS, 1129 const StreamedQualTypeHelper &SQT) { 1130 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); 1131 return OS; 1132 } 1133 }; 1134 1135 StreamedQualTypeHelper stream(const PrintingPolicy &Policy, 1136 const Twine &PlaceHolder = Twine(), 1137 unsigned Indentation = 0) const { 1138 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); 1139 } 1140 1141 void dump(const char *s) const; 1142 void dump() const; 1143 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; 1144 1145 void Profile(llvm::FoldingSetNodeID &ID) const { 1146 ID.AddPointer(getAsOpaquePtr()); 1147 } 1148 1149 /// Check if this type has any address space qualifier. 1150 inline bool hasAddressSpace() const; 1151 1152 /// Return the address space of this type. 1153 inline LangAS getAddressSpace() const; 1154 1155 /// Returns true if address space qualifiers overlap with T address space 1156 /// qualifiers. 1157 /// OpenCL C defines conversion rules for pointers to different address spaces 1158 /// and notion of overlapping address spaces. 1159 /// CL1.1 or CL1.2: 1160 /// address spaces overlap iff they are they same. 1161 /// OpenCL C v2.0 s6.5.5 adds: 1162 /// __generic overlaps with any address space except for __constant. 1163 bool isAddressSpaceOverlapping(QualType T) const { 1164 Qualifiers Q = getQualifiers(); 1165 Qualifiers TQ = T.getQualifiers(); 1166 // Address spaces overlap if at least one of them is a superset of another 1167 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q); 1168 } 1169 1170 /// Returns gc attribute of this type. 1171 inline Qualifiers::GC getObjCGCAttr() const; 1172 1173 /// true when Type is objc's weak. 1174 bool isObjCGCWeak() const { 1175 return getObjCGCAttr() == Qualifiers::Weak; 1176 } 1177 1178 /// true when Type is objc's strong. 1179 bool isObjCGCStrong() const { 1180 return getObjCGCAttr() == Qualifiers::Strong; 1181 } 1182 1183 /// Returns lifetime attribute of this type. 1184 Qualifiers::ObjCLifetime getObjCLifetime() const { 1185 return getQualifiers().getObjCLifetime(); 1186 } 1187 1188 bool hasNonTrivialObjCLifetime() const { 1189 return getQualifiers().hasNonTrivialObjCLifetime(); 1190 } 1191 1192 bool hasStrongOrWeakObjCLifetime() const { 1193 return getQualifiers().hasStrongOrWeakObjCLifetime(); 1194 } 1195 1196 // true when Type is objc's weak and weak is enabled but ARC isn't. 1197 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; 1198 1199 enum PrimitiveDefaultInitializeKind { 1200 /// The type does not fall into any of the following categories. Note that 1201 /// this case is zero-valued so that values of this enum can be used as a 1202 /// boolean condition for non-triviality. 1203 PDIK_Trivial, 1204 1205 /// The type is an Objective-C retainable pointer type that is qualified 1206 /// with the ARC __strong qualifier. 1207 PDIK_ARCStrong, 1208 1209 /// The type is an Objective-C retainable pointer type that is qualified 1210 /// with the ARC __weak qualifier. 1211 PDIK_ARCWeak, 1212 1213 /// The type is a struct containing a field whose type is not PCK_Trivial. 1214 PDIK_Struct 1215 }; 1216 1217 /// Functions to query basic properties of non-trivial C struct types. 1218 1219 /// Check if this is a non-trivial type that would cause a C struct 1220 /// transitively containing this type to be non-trivial to default initialize 1221 /// and return the kind. 1222 PrimitiveDefaultInitializeKind 1223 isNonTrivialToPrimitiveDefaultInitialize() const; 1224 1225 enum PrimitiveCopyKind { 1226 /// The type does not fall into any of the following categories. Note that 1227 /// this case is zero-valued so that values of this enum can be used as a 1228 /// boolean condition for non-triviality. 1229 PCK_Trivial, 1230 1231 /// The type would be trivial except that it is volatile-qualified. Types 1232 /// that fall into one of the other non-trivial cases may additionally be 1233 /// volatile-qualified. 1234 PCK_VolatileTrivial, 1235 1236 /// The type is an Objective-C retainable pointer type that is qualified 1237 /// with the ARC __strong qualifier. 1238 PCK_ARCStrong, 1239 1240 /// The type is an Objective-C retainable pointer type that is qualified 1241 /// with the ARC __weak qualifier. 1242 PCK_ARCWeak, 1243 1244 /// The type is a struct containing a field whose type is neither 1245 /// PCK_Trivial nor PCK_VolatileTrivial. 1246 /// Note that a C++ struct type does not necessarily match this; C++ copying 1247 /// semantics are too complex to express here, in part because they depend 1248 /// on the exact constructor or assignment operator that is chosen by 1249 /// overload resolution to do the copy. 1250 PCK_Struct 1251 }; 1252 1253 /// Check if this is a non-trivial type that would cause a C struct 1254 /// transitively containing this type to be non-trivial to copy and return the 1255 /// kind. 1256 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; 1257 1258 /// Check if this is a non-trivial type that would cause a C struct 1259 /// transitively containing this type to be non-trivial to destructively 1260 /// move and return the kind. Destructive move in this context is a C++-style 1261 /// move in which the source object is placed in a valid but unspecified state 1262 /// after it is moved, as opposed to a truly destructive move in which the 1263 /// source object is placed in an uninitialized state. 1264 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; 1265 1266 enum DestructionKind { 1267 DK_none, 1268 DK_cxx_destructor, 1269 DK_objc_strong_lifetime, 1270 DK_objc_weak_lifetime, 1271 DK_nontrivial_c_struct 1272 }; 1273 1274 /// Returns a nonzero value if objects of this type require 1275 /// non-trivial work to clean up after. Non-zero because it's 1276 /// conceivable that qualifiers (objc_gc(weak)?) could make 1277 /// something require destruction. 1278 DestructionKind isDestructedType() const { 1279 return isDestructedTypeImpl(*this); 1280 } 1281 1282 /// Check if this is or contains a C union that is non-trivial to 1283 /// default-initialize, which is a union that has a member that is non-trivial 1284 /// to default-initialize. If this returns true, 1285 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. 1286 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; 1287 1288 /// Check if this is or contains a C union that is non-trivial to destruct, 1289 /// which is a union that has a member that is non-trivial to destruct. If 1290 /// this returns true, isDestructedType returns DK_nontrivial_c_struct. 1291 bool hasNonTrivialToPrimitiveDestructCUnion() const; 1292 1293 /// Check if this is or contains a C union that is non-trivial to copy, which 1294 /// is a union that has a member that is non-trivial to copy. If this returns 1295 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. 1296 bool hasNonTrivialToPrimitiveCopyCUnion() const; 1297 1298 /// Determine whether expressions of the given type are forbidden 1299 /// from being lvalues in C. 1300 /// 1301 /// The expression types that are forbidden to be lvalues are: 1302 /// - 'void', but not qualified void 1303 /// - function types 1304 /// 1305 /// The exact rule here is C99 6.3.2.1: 1306 /// An lvalue is an expression with an object type or an incomplete 1307 /// type other than void. 1308 bool isCForbiddenLValueType() const; 1309 1310 /// Substitute type arguments for the Objective-C type parameters used in the 1311 /// subject type. 1312 /// 1313 /// \param ctx ASTContext in which the type exists. 1314 /// 1315 /// \param typeArgs The type arguments that will be substituted for the 1316 /// Objective-C type parameters in the subject type, which are generally 1317 /// computed via \c Type::getObjCSubstitutions. If empty, the type 1318 /// parameters will be replaced with their bounds or id/Class, as appropriate 1319 /// for the context. 1320 /// 1321 /// \param context The context in which the subject type was written. 1322 /// 1323 /// \returns the resulting type. 1324 QualType substObjCTypeArgs(ASTContext &ctx, 1325 ArrayRef<QualType> typeArgs, 1326 ObjCSubstitutionContext context) const; 1327 1328 /// Substitute type arguments from an object type for the Objective-C type 1329 /// parameters used in the subject type. 1330 /// 1331 /// This operation combines the computation of type arguments for 1332 /// substitution (\c Type::getObjCSubstitutions) with the actual process of 1333 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of 1334 /// callers that need to perform a single substitution in isolation. 1335 /// 1336 /// \param objectType The type of the object whose member type we're 1337 /// substituting into. For example, this might be the receiver of a message 1338 /// or the base of a property access. 1339 /// 1340 /// \param dc The declaration context from which the subject type was 1341 /// retrieved, which indicates (for example) which type parameters should 1342 /// be substituted. 1343 /// 1344 /// \param context The context in which the subject type was written. 1345 /// 1346 /// \returns the subject type after replacing all of the Objective-C type 1347 /// parameters with their corresponding arguments. 1348 QualType substObjCMemberType(QualType objectType, 1349 const DeclContext *dc, 1350 ObjCSubstitutionContext context) const; 1351 1352 /// Strip Objective-C "__kindof" types from the given type. 1353 QualType stripObjCKindOfType(const ASTContext &ctx) const; 1354 1355 /// Remove all qualifiers including _Atomic. 1356 QualType getAtomicUnqualifiedType() const; 1357 1358 private: 1359 // These methods are implemented in a separate translation unit; 1360 // "static"-ize them to avoid creating temporary QualTypes in the 1361 // caller. 1362 static bool isConstant(QualType T, const ASTContext& Ctx); 1363 static QualType getDesugaredType(QualType T, const ASTContext &Context); 1364 static SplitQualType getSplitDesugaredType(QualType T); 1365 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); 1366 static QualType getSingleStepDesugaredTypeImpl(QualType type, 1367 const ASTContext &C); 1368 static QualType IgnoreParens(QualType T); 1369 static DestructionKind isDestructedTypeImpl(QualType type); 1370 1371 /// Check if \param RD is or contains a non-trivial C union. 1372 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); 1373 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); 1374 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); 1375 }; 1376 1377 raw_ostream &operator<<(raw_ostream &OS, QualType QT); 1378 1379 } // namespace clang 1380 1381 namespace llvm { 1382 1383 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType 1384 /// to a specific Type class. 1385 template<> struct simplify_type< ::clang::QualType> { 1386 using SimpleType = const ::clang::Type *; 1387 1388 static SimpleType getSimplifiedValue(::clang::QualType Val) { 1389 return Val.getTypePtr(); 1390 } 1391 }; 1392 1393 // Teach SmallPtrSet that QualType is "basically a pointer". 1394 template<> 1395 struct PointerLikeTypeTraits<clang::QualType> { 1396 static inline void *getAsVoidPointer(clang::QualType P) { 1397 return P.getAsOpaquePtr(); 1398 } 1399 1400 static inline clang::QualType getFromVoidPointer(void *P) { 1401 return clang::QualType::getFromOpaquePtr(P); 1402 } 1403 1404 // Various qualifiers go in low bits. 1405 static constexpr int NumLowBitsAvailable = 0; 1406 }; 1407 1408 } // namespace llvm 1409 1410 namespace clang { 1411 1412 /// Base class that is common to both the \c ExtQuals and \c Type 1413 /// classes, which allows \c QualType to access the common fields between the 1414 /// two. 1415 class ExtQualsTypeCommonBase { 1416 friend class ExtQuals; 1417 friend class QualType; 1418 friend class Type; 1419 1420 /// The "base" type of an extended qualifiers type (\c ExtQuals) or 1421 /// a self-referential pointer (for \c Type). 1422 /// 1423 /// This pointer allows an efficient mapping from a QualType to its 1424 /// underlying type pointer. 1425 const Type *const BaseType; 1426 1427 /// The canonical type of this type. A QualType. 1428 QualType CanonicalType; 1429 1430 ExtQualsTypeCommonBase(const Type *baseType, QualType canon) 1431 : BaseType(baseType), CanonicalType(canon) {} 1432 }; 1433 1434 /// We can encode up to four bits in the low bits of a 1435 /// type pointer, but there are many more type qualifiers that we want 1436 /// to be able to apply to an arbitrary type. Therefore we have this 1437 /// struct, intended to be heap-allocated and used by QualType to 1438 /// store qualifiers. 1439 /// 1440 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers 1441 /// in three low bits on the QualType pointer; a fourth bit records whether 1442 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, 1443 /// Objective-C GC attributes) are much more rare. 1444 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { 1445 // NOTE: changing the fast qualifiers should be straightforward as 1446 // long as you don't make 'const' non-fast. 1447 // 1. Qualifiers: 1448 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). 1449 // Fast qualifiers must occupy the low-order bits. 1450 // b) Update Qualifiers::FastWidth and FastMask. 1451 // 2. QualType: 1452 // a) Update is{Volatile,Restrict}Qualified(), defined inline. 1453 // b) Update remove{Volatile,Restrict}, defined near the end of 1454 // this header. 1455 // 3. ASTContext: 1456 // a) Update get{Volatile,Restrict}Type. 1457 1458 /// The immutable set of qualifiers applied by this node. Always contains 1459 /// extended qualifiers. 1460 Qualifiers Quals; 1461 1462 ExtQuals *this_() { return this; } 1463 1464 public: 1465 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) 1466 : ExtQualsTypeCommonBase(baseType, 1467 canon.isNull() ? QualType(this_(), 0) : canon), 1468 Quals(quals) { 1469 assert(Quals.hasNonFastQualifiers() 1470 && "ExtQuals created with no fast qualifiers"); 1471 assert(!Quals.hasFastQualifiers() 1472 && "ExtQuals created with fast qualifiers"); 1473 } 1474 1475 Qualifiers getQualifiers() const { return Quals; } 1476 1477 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } 1478 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } 1479 1480 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } 1481 Qualifiers::ObjCLifetime getObjCLifetime() const { 1482 return Quals.getObjCLifetime(); 1483 } 1484 1485 bool hasAddressSpace() const { return Quals.hasAddressSpace(); } 1486 LangAS getAddressSpace() const { return Quals.getAddressSpace(); } 1487 1488 const Type *getBaseType() const { return BaseType; } 1489 1490 public: 1491 void Profile(llvm::FoldingSetNodeID &ID) const { 1492 Profile(ID, getBaseType(), Quals); 1493 } 1494 1495 static void Profile(llvm::FoldingSetNodeID &ID, 1496 const Type *BaseType, 1497 Qualifiers Quals) { 1498 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"); 1499 ID.AddPointer(BaseType); 1500 Quals.Profile(ID); 1501 } 1502 }; 1503 1504 /// The kind of C++11 ref-qualifier associated with a function type. 1505 /// This determines whether a member function's "this" object can be an 1506 /// lvalue, rvalue, or neither. 1507 enum RefQualifierKind { 1508 /// No ref-qualifier was provided. 1509 RQ_None = 0, 1510 1511 /// An lvalue ref-qualifier was provided (\c &). 1512 RQ_LValue, 1513 1514 /// An rvalue ref-qualifier was provided (\c &&). 1515 RQ_RValue 1516 }; 1517 1518 /// Which keyword(s) were used to create an AutoType. 1519 enum class AutoTypeKeyword { 1520 /// auto 1521 Auto, 1522 1523 /// decltype(auto) 1524 DecltypeAuto, 1525 1526 /// __auto_type (GNU extension) 1527 GNUAutoType 1528 }; 1529 1530 /// The base class of the type hierarchy. 1531 /// 1532 /// A central concept with types is that each type always has a canonical 1533 /// type. A canonical type is the type with any typedef names stripped out 1534 /// of it or the types it references. For example, consider: 1535 /// 1536 /// typedef int foo; 1537 /// typedef foo* bar; 1538 /// 'int *' 'foo *' 'bar' 1539 /// 1540 /// There will be a Type object created for 'int'. Since int is canonical, its 1541 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a 1542 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next 1543 /// there is a PointerType that represents 'int*', which, like 'int', is 1544 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical 1545 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type 1546 /// is also 'int*'. 1547 /// 1548 /// Non-canonical types are useful for emitting diagnostics, without losing 1549 /// information about typedefs being used. Canonical types are useful for type 1550 /// comparisons (they allow by-pointer equality tests) and useful for reasoning 1551 /// about whether something has a particular form (e.g. is a function type), 1552 /// because they implicitly, recursively, strip all typedefs out of a type. 1553 /// 1554 /// Types, once created, are immutable. 1555 /// 1556 class alignas(8) Type : public ExtQualsTypeCommonBase { 1557 public: 1558 enum TypeClass { 1559 #define TYPE(Class, Base) Class, 1560 #define LAST_TYPE(Class) TypeLast = Class 1561 #define ABSTRACT_TYPE(Class, Base) 1562 #include "clang/AST/TypeNodes.inc" 1563 }; 1564 1565 private: 1566 /// Bitfields required by the Type class. 1567 class TypeBitfields { 1568 friend class Type; 1569 template <class T> friend class TypePropertyCache; 1570 1571 /// TypeClass bitfield - Enum that specifies what subclass this belongs to. 1572 unsigned TC : 8; 1573 1574 /// Store information on the type dependency. 1575 unsigned Dependence : llvm::BitWidth<TypeDependence>; 1576 1577 /// True if the cache (i.e. the bitfields here starting with 1578 /// 'Cache') is valid. 1579 mutable unsigned CacheValid : 1; 1580 1581 /// Linkage of this type. 1582 mutable unsigned CachedLinkage : 3; 1583 1584 /// Whether this type involves and local or unnamed types. 1585 mutable unsigned CachedLocalOrUnnamed : 1; 1586 1587 /// Whether this type comes from an AST file. 1588 mutable unsigned FromAST : 1; 1589 1590 bool isCacheValid() const { 1591 return CacheValid; 1592 } 1593 1594 Linkage getLinkage() const { 1595 assert(isCacheValid() && "getting linkage from invalid cache"); 1596 return static_cast<Linkage>(CachedLinkage); 1597 } 1598 1599 bool hasLocalOrUnnamedType() const { 1600 assert(isCacheValid() && "getting linkage from invalid cache"); 1601 return CachedLocalOrUnnamed; 1602 } 1603 }; 1604 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 }; 1605 1606 protected: 1607 // These classes allow subclasses to somewhat cleanly pack bitfields 1608 // into Type. 1609 1610 class ArrayTypeBitfields { 1611 friend class ArrayType; 1612 1613 unsigned : NumTypeBits; 1614 1615 /// CVR qualifiers from declarations like 1616 /// 'int X[static restrict 4]'. For function parameters only. 1617 unsigned IndexTypeQuals : 3; 1618 1619 /// Storage class qualifiers from declarations like 1620 /// 'int X[static restrict 4]'. For function parameters only. 1621 /// Actually an ArrayType::ArraySizeModifier. 1622 unsigned SizeModifier : 3; 1623 }; 1624 1625 class ConstantArrayTypeBitfields { 1626 friend class ConstantArrayType; 1627 1628 unsigned : NumTypeBits + 3 + 3; 1629 1630 /// Whether we have a stored size expression. 1631 unsigned HasStoredSizeExpr : 1; 1632 }; 1633 1634 class BuiltinTypeBitfields { 1635 friend class BuiltinType; 1636 1637 unsigned : NumTypeBits; 1638 1639 /// The kind (BuiltinType::Kind) of builtin type this is. 1640 unsigned Kind : 8; 1641 }; 1642 1643 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. 1644 /// Only common bits are stored here. Additional uncommon bits are stored 1645 /// in a trailing object after FunctionProtoType. 1646 class FunctionTypeBitfields { 1647 friend class FunctionProtoType; 1648 friend class FunctionType; 1649 1650 unsigned : NumTypeBits; 1651 1652 /// Extra information which affects how the function is called, like 1653 /// regparm and the calling convention. 1654 unsigned ExtInfo : 13; 1655 1656 /// The ref-qualifier associated with a \c FunctionProtoType. 1657 /// 1658 /// This is a value of type \c RefQualifierKind. 1659 unsigned RefQualifier : 2; 1660 1661 /// Used only by FunctionProtoType, put here to pack with the 1662 /// other bitfields. 1663 /// The qualifiers are part of FunctionProtoType because... 1664 /// 1665 /// C++ 8.3.5p4: The return type, the parameter type list and the 1666 /// cv-qualifier-seq, [...], are part of the function type. 1667 unsigned FastTypeQuals : Qualifiers::FastWidth; 1668 /// Whether this function has extended Qualifiers. 1669 unsigned HasExtQuals : 1; 1670 1671 /// The number of parameters this function has, not counting '...'. 1672 /// According to [implimits] 8 bits should be enough here but this is 1673 /// somewhat easy to exceed with metaprogramming and so we would like to 1674 /// keep NumParams as wide as reasonably possible. 1675 unsigned NumParams : 16; 1676 1677 /// The type of exception specification this function has. 1678 unsigned ExceptionSpecType : 4; 1679 1680 /// Whether this function has extended parameter information. 1681 unsigned HasExtParameterInfos : 1; 1682 1683 /// Whether this function has extra bitfields for the prototype. 1684 unsigned HasExtraBitfields : 1; 1685 1686 /// Whether the function is variadic. 1687 unsigned Variadic : 1; 1688 1689 /// Whether this function has a trailing return type. 1690 unsigned HasTrailingReturn : 1; 1691 }; 1692 1693 class ObjCObjectTypeBitfields { 1694 friend class ObjCObjectType; 1695 1696 unsigned : NumTypeBits; 1697 1698 /// The number of type arguments stored directly on this object type. 1699 unsigned NumTypeArgs : 7; 1700 1701 /// The number of protocols stored directly on this object type. 1702 unsigned NumProtocols : 6; 1703 1704 /// Whether this is a "kindof" type. 1705 unsigned IsKindOf : 1; 1706 }; 1707 1708 class ReferenceTypeBitfields { 1709 friend class ReferenceType; 1710 1711 unsigned : NumTypeBits; 1712 1713 /// True if the type was originally spelled with an lvalue sigil. 1714 /// This is never true of rvalue references but can also be false 1715 /// on lvalue references because of C++0x [dcl.typedef]p9, 1716 /// as follows: 1717 /// 1718 /// typedef int &ref; // lvalue, spelled lvalue 1719 /// typedef int &&rvref; // rvalue 1720 /// ref &a; // lvalue, inner ref, spelled lvalue 1721 /// ref &&a; // lvalue, inner ref 1722 /// rvref &a; // lvalue, inner ref, spelled lvalue 1723 /// rvref &&a; // rvalue, inner ref 1724 unsigned SpelledAsLValue : 1; 1725 1726 /// True if the inner type is a reference type. This only happens 1727 /// in non-canonical forms. 1728 unsigned InnerRef : 1; 1729 }; 1730 1731 class TypeWithKeywordBitfields { 1732 friend class TypeWithKeyword; 1733 1734 unsigned : NumTypeBits; 1735 1736 /// An ElaboratedTypeKeyword. 8 bits for efficient access. 1737 unsigned Keyword : 8; 1738 }; 1739 1740 enum { NumTypeWithKeywordBits = 8 }; 1741 1742 class ElaboratedTypeBitfields { 1743 friend class ElaboratedType; 1744 1745 unsigned : NumTypeBits; 1746 unsigned : NumTypeWithKeywordBits; 1747 1748 /// Whether the ElaboratedType has a trailing OwnedTagDecl. 1749 unsigned HasOwnedTagDecl : 1; 1750 }; 1751 1752 class VectorTypeBitfields { 1753 friend class VectorType; 1754 friend class DependentVectorType; 1755 1756 unsigned : NumTypeBits; 1757 1758 /// The kind of vector, either a generic vector type or some 1759 /// target-specific vector type such as for AltiVec or Neon. 1760 unsigned VecKind : 3; 1761 /// The number of elements in the vector. 1762 uint32_t NumElements; 1763 }; 1764 1765 class AttributedTypeBitfields { 1766 friend class AttributedType; 1767 1768 unsigned : NumTypeBits; 1769 1770 /// An AttributedType::Kind 1771 unsigned AttrKind : 32 - NumTypeBits; 1772 }; 1773 1774 class AutoTypeBitfields { 1775 friend class AutoType; 1776 1777 unsigned : NumTypeBits; 1778 1779 /// Was this placeholder type spelled as 'auto', 'decltype(auto)', 1780 /// or '__auto_type'? AutoTypeKeyword value. 1781 unsigned Keyword : 2; 1782 1783 /// The number of template arguments in the type-constraints, which is 1784 /// expected to be able to hold at least 1024 according to [implimits]. 1785 /// However as this limit is somewhat easy to hit with template 1786 /// metaprogramming we'd prefer to keep it as large as possible. 1787 /// At the moment it has been left as a non-bitfield since this type 1788 /// safely fits in 64 bits as an unsigned, so there is no reason to 1789 /// introduce the performance impact of a bitfield. 1790 unsigned NumArgs; 1791 }; 1792 1793 class SubstTemplateTypeParmPackTypeBitfields { 1794 friend class SubstTemplateTypeParmPackType; 1795 1796 unsigned : NumTypeBits; 1797 1798 /// The number of template arguments in \c Arguments, which is 1799 /// expected to be able to hold at least 1024 according to [implimits]. 1800 /// However as this limit is somewhat easy to hit with template 1801 /// metaprogramming we'd prefer to keep it as large as possible. 1802 /// At the moment it has been left as a non-bitfield since this type 1803 /// safely fits in 64 bits as an unsigned, so there is no reason to 1804 /// introduce the performance impact of a bitfield. 1805 unsigned NumArgs; 1806 }; 1807 1808 class TemplateSpecializationTypeBitfields { 1809 friend class TemplateSpecializationType; 1810 1811 unsigned : NumTypeBits; 1812 1813 /// Whether this template specialization type is a substituted type alias. 1814 unsigned TypeAlias : 1; 1815 1816 /// The number of template arguments named in this class template 1817 /// specialization, which is expected to be able to hold at least 1024 1818 /// according to [implimits]. However, as this limit is somewhat easy to 1819 /// hit with template metaprogramming we'd prefer to keep it as large 1820 /// as possible. At the moment it has been left as a non-bitfield since 1821 /// this type safely fits in 64 bits as an unsigned, so there is no reason 1822 /// to introduce the performance impact of a bitfield. 1823 unsigned NumArgs; 1824 }; 1825 1826 class DependentTemplateSpecializationTypeBitfields { 1827 friend class DependentTemplateSpecializationType; 1828 1829 unsigned : NumTypeBits; 1830 unsigned : NumTypeWithKeywordBits; 1831 1832 /// The number of template arguments named in this class template 1833 /// specialization, which is expected to be able to hold at least 1024 1834 /// according to [implimits]. However, as this limit is somewhat easy to 1835 /// hit with template metaprogramming we'd prefer to keep it as large 1836 /// as possible. At the moment it has been left as a non-bitfield since 1837 /// this type safely fits in 64 bits as an unsigned, so there is no reason 1838 /// to introduce the performance impact of a bitfield. 1839 unsigned NumArgs; 1840 }; 1841 1842 class PackExpansionTypeBitfields { 1843 friend class PackExpansionType; 1844 1845 unsigned : NumTypeBits; 1846 1847 /// The number of expansions that this pack expansion will 1848 /// generate when substituted (+1), which is expected to be able to 1849 /// hold at least 1024 according to [implimits]. However, as this limit 1850 /// is somewhat easy to hit with template metaprogramming we'd prefer to 1851 /// keep it as large as possible. At the moment it has been left as a 1852 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so 1853 /// there is no reason to introduce the performance impact of a bitfield. 1854 /// 1855 /// This field will only have a non-zero value when some of the parameter 1856 /// packs that occur within the pattern have been substituted but others 1857 /// have not. 1858 unsigned NumExpansions; 1859 }; 1860 1861 union { 1862 TypeBitfields TypeBits; 1863 ArrayTypeBitfields ArrayTypeBits; 1864 ConstantArrayTypeBitfields ConstantArrayTypeBits; 1865 AttributedTypeBitfields AttributedTypeBits; 1866 AutoTypeBitfields AutoTypeBits; 1867 BuiltinTypeBitfields BuiltinTypeBits; 1868 FunctionTypeBitfields FunctionTypeBits; 1869 ObjCObjectTypeBitfields ObjCObjectTypeBits; 1870 ReferenceTypeBitfields ReferenceTypeBits; 1871 TypeWithKeywordBitfields TypeWithKeywordBits; 1872 ElaboratedTypeBitfields ElaboratedTypeBits; 1873 VectorTypeBitfields VectorTypeBits; 1874 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; 1875 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; 1876 DependentTemplateSpecializationTypeBitfields 1877 DependentTemplateSpecializationTypeBits; 1878 PackExpansionTypeBitfields PackExpansionTypeBits; 1879 }; 1880 1881 private: 1882 template <class T> friend class TypePropertyCache; 1883 1884 /// Set whether this type comes from an AST file. 1885 void setFromAST(bool V = true) const { 1886 TypeBits.FromAST = V; 1887 } 1888 1889 protected: 1890 friend class ASTContext; 1891 1892 Type(TypeClass tc, QualType canon, TypeDependence Dependence) 1893 : ExtQualsTypeCommonBase(this, 1894 canon.isNull() ? QualType(this_(), 0) : canon) { 1895 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase), 1896 "changing bitfields changed sizeof(Type)!"); 1897 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0, 1898 "Insufficient alignment!"); 1899 TypeBits.TC = tc; 1900 TypeBits.Dependence = static_cast<unsigned>(Dependence); 1901 TypeBits.CacheValid = false; 1902 TypeBits.CachedLocalOrUnnamed = false; 1903 TypeBits.CachedLinkage = NoLinkage; 1904 TypeBits.FromAST = false; 1905 } 1906 1907 // silence VC++ warning C4355: 'this' : used in base member initializer list 1908 Type *this_() { return this; } 1909 1910 void setDependence(TypeDependence D) { 1911 TypeBits.Dependence = static_cast<unsigned>(D); 1912 } 1913 1914 void addDependence(TypeDependence D) { setDependence(getDependence() | D); } 1915 1916 public: 1917 friend class ASTReader; 1918 friend class ASTWriter; 1919 template <class T> friend class serialization::AbstractTypeReader; 1920 template <class T> friend class serialization::AbstractTypeWriter; 1921 1922 Type(const Type &) = delete; 1923 Type(Type &&) = delete; 1924 Type &operator=(const Type &) = delete; 1925 Type &operator=(Type &&) = delete; 1926 1927 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } 1928 1929 /// Whether this type comes from an AST file. 1930 bool isFromAST() const { return TypeBits.FromAST; } 1931 1932 /// Whether this type is or contains an unexpanded parameter 1933 /// pack, used to support C++0x variadic templates. 1934 /// 1935 /// A type that contains a parameter pack shall be expanded by the 1936 /// ellipsis operator at some point. For example, the typedef in the 1937 /// following example contains an unexpanded parameter pack 'T': 1938 /// 1939 /// \code 1940 /// template<typename ...T> 1941 /// struct X { 1942 /// typedef T* pointer_types; // ill-formed; T is a parameter pack. 1943 /// }; 1944 /// \endcode 1945 /// 1946 /// Note that this routine does not specify which 1947 bool containsUnexpandedParameterPack() const { 1948 return getDependence() & TypeDependence::UnexpandedPack; 1949 } 1950 1951 /// Determines if this type would be canonical if it had no further 1952 /// qualification. 1953 bool isCanonicalUnqualified() const { 1954 return CanonicalType == QualType(this, 0); 1955 } 1956 1957 /// Pull a single level of sugar off of this locally-unqualified type. 1958 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() 1959 /// or QualType::getSingleStepDesugaredType(const ASTContext&). 1960 QualType getLocallyUnqualifiedSingleStepDesugaredType() const; 1961 1962 /// As an extension, we classify types as one of "sized" or "sizeless"; 1963 /// every type is one or the other. Standard types are all sized; 1964 /// sizeless types are purely an extension. 1965 /// 1966 /// Sizeless types contain data with no specified size, alignment, 1967 /// or layout. 1968 bool isSizelessType() const; 1969 bool isSizelessBuiltinType() const; 1970 1971 /// Determines if this is a sizeless type supported by the 1972 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single 1973 /// SVE vector or predicate, excluding tuple types such as svint32x4_t. 1974 bool isVLSTBuiltinType() const; 1975 1976 /// Returns the representative type for the element of an SVE builtin type. 1977 /// This is used to represent fixed-length SVE vectors created with the 1978 /// 'arm_sve_vector_bits' type attribute as VectorType. 1979 QualType getSveEltType(const ASTContext &Ctx) const; 1980 1981 /// Types are partitioned into 3 broad categories (C99 6.2.5p1): 1982 /// object types, function types, and incomplete types. 1983 1984 /// Return true if this is an incomplete type. 1985 /// A type that can describe objects, but which lacks information needed to 1986 /// determine its size (e.g. void, or a fwd declared struct). Clients of this 1987 /// routine will need to determine if the size is actually required. 1988 /// 1989 /// Def If non-null, and the type refers to some kind of declaration 1990 /// that can be completed (such as a C struct, C++ class, or Objective-C 1991 /// class), will be set to the declaration. 1992 bool isIncompleteType(NamedDecl **Def = nullptr) const; 1993 1994 /// Return true if this is an incomplete or object 1995 /// type, in other words, not a function type. 1996 bool isIncompleteOrObjectType() const { 1997 return !isFunctionType(); 1998 } 1999 2000 /// Determine whether this type is an object type. 2001 bool isObjectType() const { 2002 // C++ [basic.types]p8: 2003 // An object type is a (possibly cv-qualified) type that is not a 2004 // function type, not a reference type, and not a void type. 2005 return !isReferenceType() && !isFunctionType() && !isVoidType(); 2006 } 2007 2008 /// Return true if this is a literal type 2009 /// (C++11 [basic.types]p10) 2010 bool isLiteralType(const ASTContext &Ctx) const; 2011 2012 /// Determine if this type is a structural type, per C++20 [temp.param]p7. 2013 bool isStructuralType() const; 2014 2015 /// Test if this type is a standard-layout type. 2016 /// (C++0x [basic.type]p9) 2017 bool isStandardLayoutType() const; 2018 2019 /// Helper methods to distinguish type categories. All type predicates 2020 /// operate on the canonical type, ignoring typedefs and qualifiers. 2021 2022 /// Returns true if the type is a builtin type. 2023 bool isBuiltinType() const; 2024 2025 /// Test for a particular builtin type. 2026 bool isSpecificBuiltinType(unsigned K) const; 2027 2028 /// Test for a type which does not represent an actual type-system type but 2029 /// is instead used as a placeholder for various convenient purposes within 2030 /// Clang. All such types are BuiltinTypes. 2031 bool isPlaceholderType() const; 2032 const BuiltinType *getAsPlaceholderType() const; 2033 2034 /// Test for a specific placeholder type. 2035 bool isSpecificPlaceholderType(unsigned K) const; 2036 2037 /// Test for a placeholder type other than Overload; see 2038 /// BuiltinType::isNonOverloadPlaceholderType. 2039 bool isNonOverloadPlaceholderType() const; 2040 2041 /// isIntegerType() does *not* include complex integers (a GCC extension). 2042 /// isComplexIntegerType() can be used to test for complex integers. 2043 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) 2044 bool isEnumeralType() const; 2045 2046 /// Determine whether this type is a scoped enumeration type. 2047 bool isScopedEnumeralType() const; 2048 bool isBooleanType() const; 2049 bool isCharType() const; 2050 bool isWideCharType() const; 2051 bool isChar8Type() const; 2052 bool isChar16Type() const; 2053 bool isChar32Type() const; 2054 bool isAnyCharacterType() const; 2055 bool isIntegralType(const ASTContext &Ctx) const; 2056 2057 /// Determine whether this type is an integral or enumeration type. 2058 bool isIntegralOrEnumerationType() const; 2059 2060 /// Determine whether this type is an integral or unscoped enumeration type. 2061 bool isIntegralOrUnscopedEnumerationType() const; 2062 bool isUnscopedEnumerationType() const; 2063 2064 /// Floating point categories. 2065 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) 2066 /// isComplexType() does *not* include complex integers (a GCC extension). 2067 /// isComplexIntegerType() can be used to test for complex integers. 2068 bool isComplexType() const; // C99 6.2.5p11 (complex) 2069 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. 2070 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) 2071 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) 2072 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 2073 bool isBFloat16Type() const; 2074 bool isFloat128Type() const; 2075 bool isIbm128Type() const; 2076 bool isRealType() const; // C99 6.2.5p17 (real floating + integer) 2077 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) 2078 bool isVoidType() const; // C99 6.2.5p19 2079 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) 2080 bool isAggregateType() const; 2081 bool isFundamentalType() const; 2082 bool isCompoundType() const; 2083 2084 // Type Predicates: Check to see if this type is structurally the specified 2085 // type, ignoring typedefs and qualifiers. 2086 bool isFunctionType() const; 2087 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } 2088 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } 2089 bool isPointerType() const; 2090 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer 2091 bool isBlockPointerType() const; 2092 bool isVoidPointerType() const; 2093 bool isReferenceType() const; 2094 bool isLValueReferenceType() const; 2095 bool isRValueReferenceType() const; 2096 bool isObjectPointerType() const; 2097 bool isFunctionPointerType() const; 2098 bool isFunctionReferenceType() const; 2099 bool isMemberPointerType() const; 2100 bool isMemberFunctionPointerType() const; 2101 bool isMemberDataPointerType() const; 2102 bool isArrayType() const; 2103 bool isConstantArrayType() const; 2104 bool isIncompleteArrayType() const; 2105 bool isVariableArrayType() const; 2106 bool isDependentSizedArrayType() const; 2107 bool isRecordType() const; 2108 bool isClassType() const; 2109 bool isStructureType() const; 2110 bool isObjCBoxableRecordType() const; 2111 bool isInterfaceType() const; 2112 bool isStructureOrClassType() const; 2113 bool isUnionType() const; 2114 bool isComplexIntegerType() const; // GCC _Complex integer type. 2115 bool isVectorType() const; // GCC vector type. 2116 bool isExtVectorType() const; // Extended vector type. 2117 bool isExtVectorBoolType() const; // Extended vector type with bool element. 2118 bool isMatrixType() const; // Matrix type. 2119 bool isConstantMatrixType() const; // Constant matrix type. 2120 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier 2121 bool isObjCObjectPointerType() const; // pointer to ObjC object 2122 bool isObjCRetainableType() const; // ObjC object or block pointer 2123 bool isObjCLifetimeType() const; // (array of)* retainable type 2124 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type 2125 bool isObjCNSObjectType() const; // __attribute__((NSObject)) 2126 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) 2127 // FIXME: change this to 'raw' interface type, so we can used 'interface' type 2128 // for the common case. 2129 bool isObjCObjectType() const; // NSString or typeof(*(id)0) 2130 bool isObjCQualifiedInterfaceType() const; // NSString<foo> 2131 bool isObjCQualifiedIdType() const; // id<foo> 2132 bool isObjCQualifiedClassType() const; // Class<foo> 2133 bool isObjCObjectOrInterfaceType() const; 2134 bool isObjCIdType() const; // id 2135 bool isDecltypeType() const; 2136 /// Was this type written with the special inert-in-ARC __unsafe_unretained 2137 /// qualifier? 2138 /// 2139 /// This approximates the answer to the following question: if this 2140 /// translation unit were compiled in ARC, would this type be qualified 2141 /// with __unsafe_unretained? 2142 bool isObjCInertUnsafeUnretainedType() const { 2143 return hasAttr(attr::ObjCInertUnsafeUnretained); 2144 } 2145 2146 /// Whether the type is Objective-C 'id' or a __kindof type of an 2147 /// object type, e.g., __kindof NSView * or __kindof id 2148 /// <NSCopying>. 2149 /// 2150 /// \param bound Will be set to the bound on non-id subtype types, 2151 /// which will be (possibly specialized) Objective-C class type, or 2152 /// null for 'id. 2153 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, 2154 const ObjCObjectType *&bound) const; 2155 2156 bool isObjCClassType() const; // Class 2157 2158 /// Whether the type is Objective-C 'Class' or a __kindof type of an 2159 /// Class type, e.g., __kindof Class <NSCopying>. 2160 /// 2161 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound 2162 /// here because Objective-C's type system cannot express "a class 2163 /// object for a subclass of NSFoo". 2164 bool isObjCClassOrClassKindOfType() const; 2165 2166 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; 2167 bool isObjCSelType() const; // Class 2168 bool isObjCBuiltinType() const; // 'id' or 'Class' 2169 bool isObjCARCBridgableType() const; 2170 bool isCARCBridgableType() const; 2171 bool isTemplateTypeParmType() const; // C++ template type parameter 2172 bool isNullPtrType() const; // C++11 std::nullptr_t 2173 bool isNothrowT() const; // C++ std::nothrow_t 2174 bool isAlignValT() const; // C++17 std::align_val_t 2175 bool isStdByteType() const; // C++17 std::byte 2176 bool isAtomicType() const; // C11 _Atomic() 2177 bool isUndeducedAutoType() const; // C++11 auto or 2178 // C++14 decltype(auto) 2179 bool isTypedefNameType() const; // typedef or alias template 2180 2181 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2182 bool is##Id##Type() const; 2183 #include "clang/Basic/OpenCLImageTypes.def" 2184 2185 bool isImageType() const; // Any OpenCL image type 2186 2187 bool isSamplerT() const; // OpenCL sampler_t 2188 bool isEventT() const; // OpenCL event_t 2189 bool isClkEventT() const; // OpenCL clk_event_t 2190 bool isQueueT() const; // OpenCL queue_t 2191 bool isReserveIDT() const; // OpenCL reserve_id_t 2192 2193 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2194 bool is##Id##Type() const; 2195 #include "clang/Basic/OpenCLExtensionTypes.def" 2196 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension 2197 bool isOCLIntelSubgroupAVCType() const; 2198 bool isOCLExtOpaqueType() const; // Any OpenCL extension type 2199 2200 bool isPipeType() const; // OpenCL pipe type 2201 bool isBitIntType() const; // Bit-precise integer type 2202 bool isOpenCLSpecificType() const; // Any OpenCL specific type 2203 2204 /// Determines if this type, which must satisfy 2205 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather 2206 /// than implicitly __strong. 2207 bool isObjCARCImplicitlyUnretainedType() const; 2208 2209 /// Check if the type is the CUDA device builtin surface type. 2210 bool isCUDADeviceBuiltinSurfaceType() const; 2211 /// Check if the type is the CUDA device builtin texture type. 2212 bool isCUDADeviceBuiltinTextureType() const; 2213 2214 /// Return the implicit lifetime for this type, which must not be dependent. 2215 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; 2216 2217 enum ScalarTypeKind { 2218 STK_CPointer, 2219 STK_BlockPointer, 2220 STK_ObjCObjectPointer, 2221 STK_MemberPointer, 2222 STK_Bool, 2223 STK_Integral, 2224 STK_Floating, 2225 STK_IntegralComplex, 2226 STK_FloatingComplex, 2227 STK_FixedPoint 2228 }; 2229 2230 /// Given that this is a scalar type, classify it. 2231 ScalarTypeKind getScalarTypeKind() const; 2232 2233 TypeDependence getDependence() const { 2234 return static_cast<TypeDependence>(TypeBits.Dependence); 2235 } 2236 2237 /// Whether this type is an error type. 2238 bool containsErrors() const { 2239 return getDependence() & TypeDependence::Error; 2240 } 2241 2242 /// Whether this type is a dependent type, meaning that its definition 2243 /// somehow depends on a template parameter (C++ [temp.dep.type]). 2244 bool isDependentType() const { 2245 return getDependence() & TypeDependence::Dependent; 2246 } 2247 2248 /// Determine whether this type is an instantiation-dependent type, 2249 /// meaning that the type involves a template parameter (even if the 2250 /// definition does not actually depend on the type substituted for that 2251 /// template parameter). 2252 bool isInstantiationDependentType() const { 2253 return getDependence() & TypeDependence::Instantiation; 2254 } 2255 2256 /// Determine whether this type is an undeduced type, meaning that 2257 /// it somehow involves a C++11 'auto' type or similar which has not yet been 2258 /// deduced. 2259 bool isUndeducedType() const; 2260 2261 /// Whether this type is a variably-modified type (C99 6.7.5). 2262 bool isVariablyModifiedType() const { 2263 return getDependence() & TypeDependence::VariablyModified; 2264 } 2265 2266 /// Whether this type involves a variable-length array type 2267 /// with a definite size. 2268 bool hasSizedVLAType() const; 2269 2270 /// Whether this type is or contains a local or unnamed type. 2271 bool hasUnnamedOrLocalType() const; 2272 2273 bool isOverloadableType() const; 2274 2275 /// Determine wither this type is a C++ elaborated-type-specifier. 2276 bool isElaboratedTypeSpecifier() const; 2277 2278 bool canDecayToPointerType() const; 2279 2280 /// Whether this type is represented natively as a pointer. This includes 2281 /// pointers, references, block pointers, and Objective-C interface, 2282 /// qualified id, and qualified interface types, as well as nullptr_t. 2283 bool hasPointerRepresentation() const; 2284 2285 /// Whether this type can represent an objective pointer type for the 2286 /// purpose of GC'ability 2287 bool hasObjCPointerRepresentation() const; 2288 2289 /// Determine whether this type has an integer representation 2290 /// of some sort, e.g., it is an integer type or a vector. 2291 bool hasIntegerRepresentation() const; 2292 2293 /// Determine whether this type has an signed integer representation 2294 /// of some sort, e.g., it is an signed integer type or a vector. 2295 bool hasSignedIntegerRepresentation() const; 2296 2297 /// Determine whether this type has an unsigned integer representation 2298 /// of some sort, e.g., it is an unsigned integer type or a vector. 2299 bool hasUnsignedIntegerRepresentation() const; 2300 2301 /// Determine whether this type has a floating-point representation 2302 /// of some sort, e.g., it is a floating-point type or a vector thereof. 2303 bool hasFloatingRepresentation() const; 2304 2305 // Type Checking Functions: Check to see if this type is structurally the 2306 // specified type, ignoring typedefs and qualifiers, and return a pointer to 2307 // the best type we can. 2308 const RecordType *getAsStructureType() const; 2309 /// NOTE: getAs*ArrayType are methods on ASTContext. 2310 const RecordType *getAsUnionType() const; 2311 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. 2312 const ObjCObjectType *getAsObjCInterfaceType() const; 2313 2314 // The following is a convenience method that returns an ObjCObjectPointerType 2315 // for object declared using an interface. 2316 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; 2317 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; 2318 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; 2319 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; 2320 2321 /// Retrieves the CXXRecordDecl that this type refers to, either 2322 /// because the type is a RecordType or because it is the injected-class-name 2323 /// type of a class template or class template partial specialization. 2324 CXXRecordDecl *getAsCXXRecordDecl() const; 2325 2326 /// Retrieves the RecordDecl this type refers to. 2327 RecordDecl *getAsRecordDecl() const; 2328 2329 /// Retrieves the TagDecl that this type refers to, either 2330 /// because the type is a TagType or because it is the injected-class-name 2331 /// type of a class template or class template partial specialization. 2332 TagDecl *getAsTagDecl() const; 2333 2334 /// If this is a pointer or reference to a RecordType, return the 2335 /// CXXRecordDecl that the type refers to. 2336 /// 2337 /// If this is not a pointer or reference, or the type being pointed to does 2338 /// not refer to a CXXRecordDecl, returns NULL. 2339 const CXXRecordDecl *getPointeeCXXRecordDecl() const; 2340 2341 /// Get the DeducedType whose type will be deduced for a variable with 2342 /// an initializer of this type. This looks through declarators like pointer 2343 /// types, but not through decltype or typedefs. 2344 DeducedType *getContainedDeducedType() const; 2345 2346 /// Get the AutoType whose type will be deduced for a variable with 2347 /// an initializer of this type. This looks through declarators like pointer 2348 /// types, but not through decltype or typedefs. 2349 AutoType *getContainedAutoType() const { 2350 return dyn_cast_or_null<AutoType>(getContainedDeducedType()); 2351 } 2352 2353 /// Determine whether this type was written with a leading 'auto' 2354 /// corresponding to a trailing return type (possibly for a nested 2355 /// function type within a pointer to function type or similar). 2356 bool hasAutoForTrailingReturnType() const; 2357 2358 /// Member-template getAs<specific type>'. Look through sugar for 2359 /// an instance of \<specific type>. This scheme will eventually 2360 /// replace the specific getAsXXXX methods above. 2361 /// 2362 /// There are some specializations of this member template listed 2363 /// immediately following this class. 2364 template <typename T> const T *getAs() const; 2365 2366 /// Member-template getAsAdjusted<specific type>. Look through specific kinds 2367 /// of sugar (parens, attributes, etc) for an instance of \<specific type>. 2368 /// This is used when you need to walk over sugar nodes that represent some 2369 /// kind of type adjustment from a type that was written as a \<specific type> 2370 /// to another type that is still canonically a \<specific type>. 2371 template <typename T> const T *getAsAdjusted() const; 2372 2373 /// A variant of getAs<> for array types which silently discards 2374 /// qualifiers from the outermost type. 2375 const ArrayType *getAsArrayTypeUnsafe() const; 2376 2377 /// Member-template castAs<specific type>. Look through sugar for 2378 /// the underlying instance of \<specific type>. 2379 /// 2380 /// This method has the same relationship to getAs<T> as cast<T> has 2381 /// to dyn_cast<T>; which is to say, the underlying type *must* 2382 /// have the intended type, and this method will never return null. 2383 template <typename T> const T *castAs() const; 2384 2385 /// A variant of castAs<> for array type which silently discards 2386 /// qualifiers from the outermost type. 2387 const ArrayType *castAsArrayTypeUnsafe() const; 2388 2389 /// Determine whether this type had the specified attribute applied to it 2390 /// (looking through top-level type sugar). 2391 bool hasAttr(attr::Kind AK) const; 2392 2393 /// Get the base element type of this type, potentially discarding type 2394 /// qualifiers. This should never be used when type qualifiers 2395 /// are meaningful. 2396 const Type *getBaseElementTypeUnsafe() const; 2397 2398 /// If this is an array type, return the element type of the array, 2399 /// potentially with type qualifiers missing. 2400 /// This should never be used when type qualifiers are meaningful. 2401 const Type *getArrayElementTypeNoTypeQual() const; 2402 2403 /// If this is a pointer type, return the pointee type. 2404 /// If this is an array type, return the array element type. 2405 /// This should never be used when type qualifiers are meaningful. 2406 const Type *getPointeeOrArrayElementType() const; 2407 2408 /// If this is a pointer, ObjC object pointer, or block 2409 /// pointer, this returns the respective pointee. 2410 QualType getPointeeType() const; 2411 2412 /// Return the specified type with any "sugar" removed from the type, 2413 /// removing any typedefs, typeofs, etc., as well as any qualifiers. 2414 const Type *getUnqualifiedDesugaredType() const; 2415 2416 /// More type predicates useful for type checking/promotion 2417 bool isPromotableIntegerType() const; // C99 6.3.1.1p2 2418 2419 /// Return true if this is an integer type that is 2420 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], 2421 /// or an enum decl which has a signed representation. 2422 bool isSignedIntegerType() const; 2423 2424 /// Return true if this is an integer type that is 2425 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], 2426 /// or an enum decl which has an unsigned representation. 2427 bool isUnsignedIntegerType() const; 2428 2429 /// Determines whether this is an integer type that is signed or an 2430 /// enumeration types whose underlying type is a signed integer type. 2431 bool isSignedIntegerOrEnumerationType() const; 2432 2433 /// Determines whether this is an integer type that is unsigned or an 2434 /// enumeration types whose underlying type is a unsigned integer type. 2435 bool isUnsignedIntegerOrEnumerationType() const; 2436 2437 /// Return true if this is a fixed point type according to 2438 /// ISO/IEC JTC1 SC22 WG14 N1169. 2439 bool isFixedPointType() const; 2440 2441 /// Return true if this is a fixed point or integer type. 2442 bool isFixedPointOrIntegerType() const; 2443 2444 /// Return true if this is a saturated fixed point type according to 2445 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. 2446 bool isSaturatedFixedPointType() const; 2447 2448 /// Return true if this is a saturated fixed point type according to 2449 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. 2450 bool isUnsaturatedFixedPointType() const; 2451 2452 /// Return true if this is a fixed point type that is signed according 2453 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. 2454 bool isSignedFixedPointType() const; 2455 2456 /// Return true if this is a fixed point type that is unsigned according 2457 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. 2458 bool isUnsignedFixedPointType() const; 2459 2460 /// Return true if this is not a variable sized type, 2461 /// according to the rules of C99 6.7.5p3. It is not legal to call this on 2462 /// incomplete types. 2463 bool isConstantSizeType() const; 2464 2465 /// Returns true if this type can be represented by some 2466 /// set of type specifiers. 2467 bool isSpecifierType() const; 2468 2469 /// Determine the linkage of this type. 2470 Linkage getLinkage() const; 2471 2472 /// Determine the visibility of this type. 2473 Visibility getVisibility() const { 2474 return getLinkageAndVisibility().getVisibility(); 2475 } 2476 2477 /// Return true if the visibility was explicitly set is the code. 2478 bool isVisibilityExplicit() const { 2479 return getLinkageAndVisibility().isVisibilityExplicit(); 2480 } 2481 2482 /// Determine the linkage and visibility of this type. 2483 LinkageInfo getLinkageAndVisibility() const; 2484 2485 /// True if the computed linkage is valid. Used for consistency 2486 /// checking. Should always return true. 2487 bool isLinkageValid() const; 2488 2489 /// Determine the nullability of the given type. 2490 /// 2491 /// Note that nullability is only captured as sugar within the type 2492 /// system, not as part of the canonical type, so nullability will 2493 /// be lost by canonicalization and desugaring. 2494 Optional<NullabilityKind> getNullability(const ASTContext &context) const; 2495 2496 /// Determine whether the given type can have a nullability 2497 /// specifier applied to it, i.e., if it is any kind of pointer type. 2498 /// 2499 /// \param ResultIfUnknown The value to return if we don't yet know whether 2500 /// this type can have nullability because it is dependent. 2501 bool canHaveNullability(bool ResultIfUnknown = true) const; 2502 2503 /// Retrieve the set of substitutions required when accessing a member 2504 /// of the Objective-C receiver type that is declared in the given context. 2505 /// 2506 /// \c *this is the type of the object we're operating on, e.g., the 2507 /// receiver for a message send or the base of a property access, and is 2508 /// expected to be of some object or object pointer type. 2509 /// 2510 /// \param dc The declaration context for which we are building up a 2511 /// substitution mapping, which should be an Objective-C class, extension, 2512 /// category, or method within. 2513 /// 2514 /// \returns an array of type arguments that can be substituted for 2515 /// the type parameters of the given declaration context in any type described 2516 /// within that context, or an empty optional to indicate that no 2517 /// substitution is required. 2518 Optional<ArrayRef<QualType>> 2519 getObjCSubstitutions(const DeclContext *dc) const; 2520 2521 /// Determines if this is an ObjC interface type that may accept type 2522 /// parameters. 2523 bool acceptsObjCTypeParams() const; 2524 2525 const char *getTypeClassName() const; 2526 2527 QualType getCanonicalTypeInternal() const { 2528 return CanonicalType; 2529 } 2530 2531 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h 2532 void dump() const; 2533 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const; 2534 }; 2535 2536 /// This will check for a TypedefType by removing any existing sugar 2537 /// until it reaches a TypedefType or a non-sugared type. 2538 template <> const TypedefType *Type::getAs() const; 2539 2540 /// This will check for a TemplateSpecializationType by removing any 2541 /// existing sugar until it reaches a TemplateSpecializationType or a 2542 /// non-sugared type. 2543 template <> const TemplateSpecializationType *Type::getAs() const; 2544 2545 /// This will check for an AttributedType by removing any existing sugar 2546 /// until it reaches an AttributedType or a non-sugared type. 2547 template <> const AttributedType *Type::getAs() const; 2548 2549 // We can do canonical leaf types faster, because we don't have to 2550 // worry about preserving child type decoration. 2551 #define TYPE(Class, Base) 2552 #define LEAF_TYPE(Class) \ 2553 template <> inline const Class##Type *Type::getAs() const { \ 2554 return dyn_cast<Class##Type>(CanonicalType); \ 2555 } \ 2556 template <> inline const Class##Type *Type::castAs() const { \ 2557 return cast<Class##Type>(CanonicalType); \ 2558 } 2559 #include "clang/AST/TypeNodes.inc" 2560 2561 /// This class is used for builtin types like 'int'. Builtin 2562 /// types are always canonical and have a literal name field. 2563 class BuiltinType : public Type { 2564 public: 2565 enum Kind { 2566 // OpenCL image types 2567 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, 2568 #include "clang/Basic/OpenCLImageTypes.def" 2569 // OpenCL extension types 2570 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, 2571 #include "clang/Basic/OpenCLExtensionTypes.def" 2572 // SVE Types 2573 #define SVE_TYPE(Name, Id, SingletonId) Id, 2574 #include "clang/Basic/AArch64SVEACLETypes.def" 2575 // PPC MMA Types 2576 #define PPC_VECTOR_TYPE(Name, Id, Size) Id, 2577 #include "clang/Basic/PPCTypes.def" 2578 // RVV Types 2579 #define RVV_TYPE(Name, Id, SingletonId) Id, 2580 #include "clang/Basic/RISCVVTypes.def" 2581 // All other builtin types 2582 #define BUILTIN_TYPE(Id, SingletonId) Id, 2583 #define LAST_BUILTIN_TYPE(Id) LastKind = Id 2584 #include "clang/AST/BuiltinTypes.def" 2585 }; 2586 2587 private: 2588 friend class ASTContext; // ASTContext creates these. 2589 2590 BuiltinType(Kind K) 2591 : Type(Builtin, QualType(), 2592 K == Dependent ? TypeDependence::DependentInstantiation 2593 : TypeDependence::None) { 2594 BuiltinTypeBits.Kind = K; 2595 } 2596 2597 public: 2598 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } 2599 StringRef getName(const PrintingPolicy &Policy) const; 2600 2601 const char *getNameAsCString(const PrintingPolicy &Policy) const { 2602 // The StringRef is null-terminated. 2603 StringRef str = getName(Policy); 2604 assert(!str.empty() && str.data()[str.size()] == '\0'); 2605 return str.data(); 2606 } 2607 2608 bool isSugared() const { return false; } 2609 QualType desugar() const { return QualType(this, 0); } 2610 2611 bool isInteger() const { 2612 return getKind() >= Bool && getKind() <= Int128; 2613 } 2614 2615 bool isSignedInteger() const { 2616 return getKind() >= Char_S && getKind() <= Int128; 2617 } 2618 2619 bool isUnsignedInteger() const { 2620 return getKind() >= Bool && getKind() <= UInt128; 2621 } 2622 2623 bool isFloatingPoint() const { 2624 return getKind() >= Half && getKind() <= Ibm128; 2625 } 2626 2627 bool isSVEBool() const { return getKind() == Kind::SveBool; } 2628 2629 /// Determines whether the given kind corresponds to a placeholder type. 2630 static bool isPlaceholderTypeKind(Kind K) { 2631 return K >= Overload; 2632 } 2633 2634 /// Determines whether this type is a placeholder type, i.e. a type 2635 /// which cannot appear in arbitrary positions in a fully-formed 2636 /// expression. 2637 bool isPlaceholderType() const { 2638 return isPlaceholderTypeKind(getKind()); 2639 } 2640 2641 /// Determines whether this type is a placeholder type other than 2642 /// Overload. Most placeholder types require only syntactic 2643 /// information about their context in order to be resolved (e.g. 2644 /// whether it is a call expression), which means they can (and 2645 /// should) be resolved in an earlier "phase" of analysis. 2646 /// Overload expressions sometimes pick up further information 2647 /// from their context, like whether the context expects a 2648 /// specific function-pointer type, and so frequently need 2649 /// special treatment. 2650 bool isNonOverloadPlaceholderType() const { 2651 return getKind() > Overload; 2652 } 2653 2654 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } 2655 }; 2656 2657 /// Complex values, per C99 6.2.5p11. This supports the C99 complex 2658 /// types (_Complex float etc) as well as the GCC integer complex extensions. 2659 class ComplexType : public Type, public llvm::FoldingSetNode { 2660 friend class ASTContext; // ASTContext creates these. 2661 2662 QualType ElementType; 2663 2664 ComplexType(QualType Element, QualType CanonicalPtr) 2665 : Type(Complex, CanonicalPtr, Element->getDependence()), 2666 ElementType(Element) {} 2667 2668 public: 2669 QualType getElementType() const { return ElementType; } 2670 2671 bool isSugared() const { return false; } 2672 QualType desugar() const { return QualType(this, 0); } 2673 2674 void Profile(llvm::FoldingSetNodeID &ID) { 2675 Profile(ID, getElementType()); 2676 } 2677 2678 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { 2679 ID.AddPointer(Element.getAsOpaquePtr()); 2680 } 2681 2682 static bool classof(const Type *T) { return T->getTypeClass() == Complex; } 2683 }; 2684 2685 /// Sugar for parentheses used when specifying types. 2686 class ParenType : public Type, public llvm::FoldingSetNode { 2687 friend class ASTContext; // ASTContext creates these. 2688 2689 QualType Inner; 2690 2691 ParenType(QualType InnerType, QualType CanonType) 2692 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {} 2693 2694 public: 2695 QualType getInnerType() const { return Inner; } 2696 2697 bool isSugared() const { return true; } 2698 QualType desugar() const { return getInnerType(); } 2699 2700 void Profile(llvm::FoldingSetNodeID &ID) { 2701 Profile(ID, getInnerType()); 2702 } 2703 2704 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { 2705 Inner.Profile(ID); 2706 } 2707 2708 static bool classof(const Type *T) { return T->getTypeClass() == Paren; } 2709 }; 2710 2711 /// PointerType - C99 6.7.5.1 - Pointer Declarators. 2712 class PointerType : public Type, public llvm::FoldingSetNode { 2713 friend class ASTContext; // ASTContext creates these. 2714 2715 QualType PointeeType; 2716 2717 PointerType(QualType Pointee, QualType CanonicalPtr) 2718 : Type(Pointer, CanonicalPtr, Pointee->getDependence()), 2719 PointeeType(Pointee) {} 2720 2721 public: 2722 QualType getPointeeType() const { return PointeeType; } 2723 2724 bool isSugared() const { return false; } 2725 QualType desugar() const { return QualType(this, 0); } 2726 2727 void Profile(llvm::FoldingSetNodeID &ID) { 2728 Profile(ID, getPointeeType()); 2729 } 2730 2731 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { 2732 ID.AddPointer(Pointee.getAsOpaquePtr()); 2733 } 2734 2735 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } 2736 }; 2737 2738 /// Represents a type which was implicitly adjusted by the semantic 2739 /// engine for arbitrary reasons. For example, array and function types can 2740 /// decay, and function types can have their calling conventions adjusted. 2741 class AdjustedType : public Type, public llvm::FoldingSetNode { 2742 QualType OriginalTy; 2743 QualType AdjustedTy; 2744 2745 protected: 2746 friend class ASTContext; // ASTContext creates these. 2747 2748 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, 2749 QualType CanonicalPtr) 2750 : Type(TC, CanonicalPtr, OriginalTy->getDependence()), 2751 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} 2752 2753 public: 2754 QualType getOriginalType() const { return OriginalTy; } 2755 QualType getAdjustedType() const { return AdjustedTy; } 2756 2757 bool isSugared() const { return true; } 2758 QualType desugar() const { return AdjustedTy; } 2759 2760 void Profile(llvm::FoldingSetNodeID &ID) { 2761 Profile(ID, OriginalTy, AdjustedTy); 2762 } 2763 2764 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { 2765 ID.AddPointer(Orig.getAsOpaquePtr()); 2766 ID.AddPointer(New.getAsOpaquePtr()); 2767 } 2768 2769 static bool classof(const Type *T) { 2770 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; 2771 } 2772 }; 2773 2774 /// Represents a pointer type decayed from an array or function type. 2775 class DecayedType : public AdjustedType { 2776 friend class ASTContext; // ASTContext creates these. 2777 2778 inline 2779 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); 2780 2781 public: 2782 QualType getDecayedType() const { return getAdjustedType(); } 2783 2784 inline QualType getPointeeType() const; 2785 2786 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } 2787 }; 2788 2789 /// Pointer to a block type. 2790 /// This type is to represent types syntactically represented as 2791 /// "void (^)(int)", etc. Pointee is required to always be a function type. 2792 class BlockPointerType : public Type, public llvm::FoldingSetNode { 2793 friend class ASTContext; // ASTContext creates these. 2794 2795 // Block is some kind of pointer type 2796 QualType PointeeType; 2797 2798 BlockPointerType(QualType Pointee, QualType CanonicalCls) 2799 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()), 2800 PointeeType(Pointee) {} 2801 2802 public: 2803 // Get the pointee type. Pointee is required to always be a function type. 2804 QualType getPointeeType() const { return PointeeType; } 2805 2806 bool isSugared() const { return false; } 2807 QualType desugar() const { return QualType(this, 0); } 2808 2809 void Profile(llvm::FoldingSetNodeID &ID) { 2810 Profile(ID, getPointeeType()); 2811 } 2812 2813 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { 2814 ID.AddPointer(Pointee.getAsOpaquePtr()); 2815 } 2816 2817 static bool classof(const Type *T) { 2818 return T->getTypeClass() == BlockPointer; 2819 } 2820 }; 2821 2822 /// Base for LValueReferenceType and RValueReferenceType 2823 class ReferenceType : public Type, public llvm::FoldingSetNode { 2824 QualType PointeeType; 2825 2826 protected: 2827 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, 2828 bool SpelledAsLValue) 2829 : Type(tc, CanonicalRef, Referencee->getDependence()), 2830 PointeeType(Referencee) { 2831 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; 2832 ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); 2833 } 2834 2835 public: 2836 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } 2837 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } 2838 2839 QualType getPointeeTypeAsWritten() const { return PointeeType; } 2840 2841 QualType getPointeeType() const { 2842 // FIXME: this might strip inner qualifiers; okay? 2843 const ReferenceType *T = this; 2844 while (T->isInnerRef()) 2845 T = T->PointeeType->castAs<ReferenceType>(); 2846 return T->PointeeType; 2847 } 2848 2849 void Profile(llvm::FoldingSetNodeID &ID) { 2850 Profile(ID, PointeeType, isSpelledAsLValue()); 2851 } 2852 2853 static void Profile(llvm::FoldingSetNodeID &ID, 2854 QualType Referencee, 2855 bool SpelledAsLValue) { 2856 ID.AddPointer(Referencee.getAsOpaquePtr()); 2857 ID.AddBoolean(SpelledAsLValue); 2858 } 2859 2860 static bool classof(const Type *T) { 2861 return T->getTypeClass() == LValueReference || 2862 T->getTypeClass() == RValueReference; 2863 } 2864 }; 2865 2866 /// An lvalue reference type, per C++11 [dcl.ref]. 2867 class LValueReferenceType : public ReferenceType { 2868 friend class ASTContext; // ASTContext creates these 2869 2870 LValueReferenceType(QualType Referencee, QualType CanonicalRef, 2871 bool SpelledAsLValue) 2872 : ReferenceType(LValueReference, Referencee, CanonicalRef, 2873 SpelledAsLValue) {} 2874 2875 public: 2876 bool isSugared() const { return false; } 2877 QualType desugar() const { return QualType(this, 0); } 2878 2879 static bool classof(const Type *T) { 2880 return T->getTypeClass() == LValueReference; 2881 } 2882 }; 2883 2884 /// An rvalue reference type, per C++11 [dcl.ref]. 2885 class RValueReferenceType : public ReferenceType { 2886 friend class ASTContext; // ASTContext creates these 2887 2888 RValueReferenceType(QualType Referencee, QualType CanonicalRef) 2889 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} 2890 2891 public: 2892 bool isSugared() const { return false; } 2893 QualType desugar() const { return QualType(this, 0); } 2894 2895 static bool classof(const Type *T) { 2896 return T->getTypeClass() == RValueReference; 2897 } 2898 }; 2899 2900 /// A pointer to member type per C++ 8.3.3 - Pointers to members. 2901 /// 2902 /// This includes both pointers to data members and pointer to member functions. 2903 class MemberPointerType : public Type, public llvm::FoldingSetNode { 2904 friend class ASTContext; // ASTContext creates these. 2905 2906 QualType PointeeType; 2907 2908 /// The class of which the pointee is a member. Must ultimately be a 2909 /// RecordType, but could be a typedef or a template parameter too. 2910 const Type *Class; 2911 2912 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) 2913 : Type(MemberPointer, CanonicalPtr, 2914 (Cls->getDependence() & ~TypeDependence::VariablyModified) | 2915 Pointee->getDependence()), 2916 PointeeType(Pointee), Class(Cls) {} 2917 2918 public: 2919 QualType getPointeeType() const { return PointeeType; } 2920 2921 /// Returns true if the member type (i.e. the pointee type) is a 2922 /// function type rather than a data-member type. 2923 bool isMemberFunctionPointer() const { 2924 return PointeeType->isFunctionProtoType(); 2925 } 2926 2927 /// Returns true if the member type (i.e. the pointee type) is a 2928 /// data type rather than a function type. 2929 bool isMemberDataPointer() const { 2930 return !PointeeType->isFunctionProtoType(); 2931 } 2932 2933 const Type *getClass() const { return Class; } 2934 CXXRecordDecl *getMostRecentCXXRecordDecl() const; 2935 2936 bool isSugared() const { return false; } 2937 QualType desugar() const { return QualType(this, 0); } 2938 2939 void Profile(llvm::FoldingSetNodeID &ID) { 2940 Profile(ID, getPointeeType(), getClass()); 2941 } 2942 2943 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, 2944 const Type *Class) { 2945 ID.AddPointer(Pointee.getAsOpaquePtr()); 2946 ID.AddPointer(Class); 2947 } 2948 2949 static bool classof(const Type *T) { 2950 return T->getTypeClass() == MemberPointer; 2951 } 2952 }; 2953 2954 /// Represents an array type, per C99 6.7.5.2 - Array Declarators. 2955 class ArrayType : public Type, public llvm::FoldingSetNode { 2956 public: 2957 /// Capture whether this is a normal array (e.g. int X[4]) 2958 /// an array with a static size (e.g. int X[static 4]), or an array 2959 /// with a star size (e.g. int X[*]). 2960 /// 'static' is only allowed on function parameters. 2961 enum ArraySizeModifier { 2962 Normal, Static, Star 2963 }; 2964 2965 private: 2966 /// The element type of the array. 2967 QualType ElementType; 2968 2969 protected: 2970 friend class ASTContext; // ASTContext creates these. 2971 2972 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, 2973 unsigned tq, const Expr *sz = nullptr); 2974 2975 public: 2976 QualType getElementType() const { return ElementType; } 2977 2978 ArraySizeModifier getSizeModifier() const { 2979 return ArraySizeModifier(ArrayTypeBits.SizeModifier); 2980 } 2981 2982 Qualifiers getIndexTypeQualifiers() const { 2983 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); 2984 } 2985 2986 unsigned getIndexTypeCVRQualifiers() const { 2987 return ArrayTypeBits.IndexTypeQuals; 2988 } 2989 2990 static bool classof(const Type *T) { 2991 return T->getTypeClass() == ConstantArray || 2992 T->getTypeClass() == VariableArray || 2993 T->getTypeClass() == IncompleteArray || 2994 T->getTypeClass() == DependentSizedArray; 2995 } 2996 }; 2997 2998 /// Represents the canonical version of C arrays with a specified constant size. 2999 /// For example, the canonical type for 'int A[4 + 4*100]' is a 3000 /// ConstantArrayType where the element type is 'int' and the size is 404. 3001 class ConstantArrayType final 3002 : public ArrayType, 3003 private llvm::TrailingObjects<ConstantArrayType, const Expr *> { 3004 friend class ASTContext; // ASTContext creates these. 3005 friend TrailingObjects; 3006 3007 llvm::APInt Size; // Allows us to unique the type. 3008 3009 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, 3010 const Expr *sz, ArraySizeModifier sm, unsigned tq) 3011 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) { 3012 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr; 3013 if (ConstantArrayTypeBits.HasStoredSizeExpr) { 3014 assert(!can.isNull() && "canonical constant array should not have size"); 3015 *getTrailingObjects<const Expr*>() = sz; 3016 } 3017 } 3018 3019 unsigned numTrailingObjects(OverloadToken<const Expr*>) const { 3020 return ConstantArrayTypeBits.HasStoredSizeExpr; 3021 } 3022 3023 public: 3024 const llvm::APInt &getSize() const { return Size; } 3025 const Expr *getSizeExpr() const { 3026 return ConstantArrayTypeBits.HasStoredSizeExpr 3027 ? *getTrailingObjects<const Expr *>() 3028 : nullptr; 3029 } 3030 bool isSugared() const { return false; } 3031 QualType desugar() const { return QualType(this, 0); } 3032 3033 /// Determine the number of bits required to address a member of 3034 // an array with the given element type and number of elements. 3035 static unsigned getNumAddressingBits(const ASTContext &Context, 3036 QualType ElementType, 3037 const llvm::APInt &NumElements); 3038 3039 /// Determine the maximum number of active bits that an array's size 3040 /// can require, which limits the maximum size of the array. 3041 static unsigned getMaxSizeBits(const ASTContext &Context); 3042 3043 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { 3044 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(), 3045 getSizeModifier(), getIndexTypeCVRQualifiers()); 3046 } 3047 3048 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx, 3049 QualType ET, const llvm::APInt &ArraySize, 3050 const Expr *SizeExpr, ArraySizeModifier SizeMod, 3051 unsigned TypeQuals); 3052 3053 static bool classof(const Type *T) { 3054 return T->getTypeClass() == ConstantArray; 3055 } 3056 }; 3057 3058 /// Represents a C array with an unspecified size. For example 'int A[]' has 3059 /// an IncompleteArrayType where the element type is 'int' and the size is 3060 /// unspecified. 3061 class IncompleteArrayType : public ArrayType { 3062 friend class ASTContext; // ASTContext creates these. 3063 3064 IncompleteArrayType(QualType et, QualType can, 3065 ArraySizeModifier sm, unsigned tq) 3066 : ArrayType(IncompleteArray, et, can, sm, tq) {} 3067 3068 public: 3069 friend class StmtIteratorBase; 3070 3071 bool isSugared() const { return false; } 3072 QualType desugar() const { return QualType(this, 0); } 3073 3074 static bool classof(const Type *T) { 3075 return T->getTypeClass() == IncompleteArray; 3076 } 3077 3078 void Profile(llvm::FoldingSetNodeID &ID) { 3079 Profile(ID, getElementType(), getSizeModifier(), 3080 getIndexTypeCVRQualifiers()); 3081 } 3082 3083 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, 3084 ArraySizeModifier SizeMod, unsigned TypeQuals) { 3085 ID.AddPointer(ET.getAsOpaquePtr()); 3086 ID.AddInteger(SizeMod); 3087 ID.AddInteger(TypeQuals); 3088 } 3089 }; 3090 3091 /// Represents a C array with a specified size that is not an 3092 /// integer-constant-expression. For example, 'int s[x+foo()]'. 3093 /// Since the size expression is an arbitrary expression, we store it as such. 3094 /// 3095 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and 3096 /// should not be: two lexically equivalent variable array types could mean 3097 /// different things, for example, these variables do not have the same type 3098 /// dynamically: 3099 /// 3100 /// void foo(int x) { 3101 /// int Y[x]; 3102 /// ++x; 3103 /// int Z[x]; 3104 /// } 3105 class VariableArrayType : public ArrayType { 3106 friend class ASTContext; // ASTContext creates these. 3107 3108 /// An assignment-expression. VLA's are only permitted within 3109 /// a function block. 3110 Stmt *SizeExpr; 3111 3112 /// The range spanned by the left and right array brackets. 3113 SourceRange Brackets; 3114 3115 VariableArrayType(QualType et, QualType can, Expr *e, 3116 ArraySizeModifier sm, unsigned tq, 3117 SourceRange brackets) 3118 : ArrayType(VariableArray, et, can, sm, tq, e), 3119 SizeExpr((Stmt*) e), Brackets(brackets) {} 3120 3121 public: 3122 friend class StmtIteratorBase; 3123 3124 Expr *getSizeExpr() const { 3125 // We use C-style casts instead of cast<> here because we do not wish 3126 // to have a dependency of Type.h on Stmt.h/Expr.h. 3127 return (Expr*) SizeExpr; 3128 } 3129 3130 SourceRange getBracketsRange() const { return Brackets; } 3131 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } 3132 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } 3133 3134 bool isSugared() const { return false; } 3135 QualType desugar() const { return QualType(this, 0); } 3136 3137 static bool classof(const Type *T) { 3138 return T->getTypeClass() == VariableArray; 3139 } 3140 3141 void Profile(llvm::FoldingSetNodeID &ID) { 3142 llvm_unreachable("Cannot unique VariableArrayTypes."); 3143 } 3144 }; 3145 3146 /// Represents an array type in C++ whose size is a value-dependent expression. 3147 /// 3148 /// For example: 3149 /// \code 3150 /// template<typename T, int Size> 3151 /// class array { 3152 /// T data[Size]; 3153 /// }; 3154 /// \endcode 3155 /// 3156 /// For these types, we won't actually know what the array bound is 3157 /// until template instantiation occurs, at which point this will 3158 /// become either a ConstantArrayType or a VariableArrayType. 3159 class DependentSizedArrayType : public ArrayType { 3160 friend class ASTContext; // ASTContext creates these. 3161 3162 const ASTContext &Context; 3163 3164 /// An assignment expression that will instantiate to the 3165 /// size of the array. 3166 /// 3167 /// The expression itself might be null, in which case the array 3168 /// type will have its size deduced from an initializer. 3169 Stmt *SizeExpr; 3170 3171 /// The range spanned by the left and right array brackets. 3172 SourceRange Brackets; 3173 3174 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, 3175 Expr *e, ArraySizeModifier sm, unsigned tq, 3176 SourceRange brackets); 3177 3178 public: 3179 friend class StmtIteratorBase; 3180 3181 Expr *getSizeExpr() const { 3182 // We use C-style casts instead of cast<> here because we do not wish 3183 // to have a dependency of Type.h on Stmt.h/Expr.h. 3184 return (Expr*) SizeExpr; 3185 } 3186 3187 SourceRange getBracketsRange() const { return Brackets; } 3188 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } 3189 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } 3190 3191 bool isSugared() const { return false; } 3192 QualType desugar() const { return QualType(this, 0); } 3193 3194 static bool classof(const Type *T) { 3195 return T->getTypeClass() == DependentSizedArray; 3196 } 3197 3198 void Profile(llvm::FoldingSetNodeID &ID) { 3199 Profile(ID, Context, getElementType(), 3200 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); 3201 } 3202 3203 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3204 QualType ET, ArraySizeModifier SizeMod, 3205 unsigned TypeQuals, Expr *E); 3206 }; 3207 3208 /// Represents an extended address space qualifier where the input address space 3209 /// value is dependent. Non-dependent address spaces are not represented with a 3210 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. 3211 /// 3212 /// For example: 3213 /// \code 3214 /// template<typename T, int AddrSpace> 3215 /// class AddressSpace { 3216 /// typedef T __attribute__((address_space(AddrSpace))) type; 3217 /// } 3218 /// \endcode 3219 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { 3220 friend class ASTContext; 3221 3222 const ASTContext &Context; 3223 Expr *AddrSpaceExpr; 3224 QualType PointeeType; 3225 SourceLocation loc; 3226 3227 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, 3228 QualType can, Expr *AddrSpaceExpr, 3229 SourceLocation loc); 3230 3231 public: 3232 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } 3233 QualType getPointeeType() const { return PointeeType; } 3234 SourceLocation getAttributeLoc() const { return loc; } 3235 3236 bool isSugared() const { return false; } 3237 QualType desugar() const { return QualType(this, 0); } 3238 3239 static bool classof(const Type *T) { 3240 return T->getTypeClass() == DependentAddressSpace; 3241 } 3242 3243 void Profile(llvm::FoldingSetNodeID &ID) { 3244 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); 3245 } 3246 3247 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3248 QualType PointeeType, Expr *AddrSpaceExpr); 3249 }; 3250 3251 /// Represents an extended vector type where either the type or size is 3252 /// dependent. 3253 /// 3254 /// For example: 3255 /// \code 3256 /// template<typename T, int Size> 3257 /// class vector { 3258 /// typedef T __attribute__((ext_vector_type(Size))) type; 3259 /// } 3260 /// \endcode 3261 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { 3262 friend class ASTContext; 3263 3264 const ASTContext &Context; 3265 Expr *SizeExpr; 3266 3267 /// The element type of the array. 3268 QualType ElementType; 3269 3270 SourceLocation loc; 3271 3272 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, 3273 QualType can, Expr *SizeExpr, SourceLocation loc); 3274 3275 public: 3276 Expr *getSizeExpr() const { return SizeExpr; } 3277 QualType getElementType() const { return ElementType; } 3278 SourceLocation getAttributeLoc() const { return loc; } 3279 3280 bool isSugared() const { return false; } 3281 QualType desugar() const { return QualType(this, 0); } 3282 3283 static bool classof(const Type *T) { 3284 return T->getTypeClass() == DependentSizedExtVector; 3285 } 3286 3287 void Profile(llvm::FoldingSetNodeID &ID) { 3288 Profile(ID, Context, getElementType(), getSizeExpr()); 3289 } 3290 3291 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3292 QualType ElementType, Expr *SizeExpr); 3293 }; 3294 3295 3296 /// Represents a GCC generic vector type. This type is created using 3297 /// __attribute__((vector_size(n)), where "n" specifies the vector size in 3298 /// bytes; or from an Altivec __vector or vector declaration. 3299 /// Since the constructor takes the number of vector elements, the 3300 /// client is responsible for converting the size into the number of elements. 3301 class VectorType : public Type, public llvm::FoldingSetNode { 3302 public: 3303 enum VectorKind { 3304 /// not a target-specific vector type 3305 GenericVector, 3306 3307 /// is AltiVec vector 3308 AltiVecVector, 3309 3310 /// is AltiVec 'vector Pixel' 3311 AltiVecPixel, 3312 3313 /// is AltiVec 'vector bool ...' 3314 AltiVecBool, 3315 3316 /// is ARM Neon vector 3317 NeonVector, 3318 3319 /// is ARM Neon polynomial vector 3320 NeonPolyVector, 3321 3322 /// is AArch64 SVE fixed-length data vector 3323 SveFixedLengthDataVector, 3324 3325 /// is AArch64 SVE fixed-length predicate vector 3326 SveFixedLengthPredicateVector 3327 }; 3328 3329 protected: 3330 friend class ASTContext; // ASTContext creates these. 3331 3332 /// The element type of the vector. 3333 QualType ElementType; 3334 3335 VectorType(QualType vecType, unsigned nElements, QualType canonType, 3336 VectorKind vecKind); 3337 3338 VectorType(TypeClass tc, QualType vecType, unsigned nElements, 3339 QualType canonType, VectorKind vecKind); 3340 3341 public: 3342 QualType getElementType() const { return ElementType; } 3343 unsigned getNumElements() const { return VectorTypeBits.NumElements; } 3344 3345 bool isSugared() const { return false; } 3346 QualType desugar() const { return QualType(this, 0); } 3347 3348 VectorKind getVectorKind() const { 3349 return VectorKind(VectorTypeBits.VecKind); 3350 } 3351 3352 void Profile(llvm::FoldingSetNodeID &ID) { 3353 Profile(ID, getElementType(), getNumElements(), 3354 getTypeClass(), getVectorKind()); 3355 } 3356 3357 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, 3358 unsigned NumElements, TypeClass TypeClass, 3359 VectorKind VecKind) { 3360 ID.AddPointer(ElementType.getAsOpaquePtr()); 3361 ID.AddInteger(NumElements); 3362 ID.AddInteger(TypeClass); 3363 ID.AddInteger(VecKind); 3364 } 3365 3366 static bool classof(const Type *T) { 3367 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; 3368 } 3369 }; 3370 3371 /// Represents a vector type where either the type or size is dependent. 3372 //// 3373 /// For example: 3374 /// \code 3375 /// template<typename T, int Size> 3376 /// class vector { 3377 /// typedef T __attribute__((vector_size(Size))) type; 3378 /// } 3379 /// \endcode 3380 class DependentVectorType : public Type, public llvm::FoldingSetNode { 3381 friend class ASTContext; 3382 3383 const ASTContext &Context; 3384 QualType ElementType; 3385 Expr *SizeExpr; 3386 SourceLocation Loc; 3387 3388 DependentVectorType(const ASTContext &Context, QualType ElementType, 3389 QualType CanonType, Expr *SizeExpr, 3390 SourceLocation Loc, VectorType::VectorKind vecKind); 3391 3392 public: 3393 Expr *getSizeExpr() const { return SizeExpr; } 3394 QualType getElementType() const { return ElementType; } 3395 SourceLocation getAttributeLoc() const { return Loc; } 3396 VectorType::VectorKind getVectorKind() const { 3397 return VectorType::VectorKind(VectorTypeBits.VecKind); 3398 } 3399 3400 bool isSugared() const { return false; } 3401 QualType desugar() const { return QualType(this, 0); } 3402 3403 static bool classof(const Type *T) { 3404 return T->getTypeClass() == DependentVector; 3405 } 3406 3407 void Profile(llvm::FoldingSetNodeID &ID) { 3408 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); 3409 } 3410 3411 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3412 QualType ElementType, const Expr *SizeExpr, 3413 VectorType::VectorKind VecKind); 3414 }; 3415 3416 /// ExtVectorType - Extended vector type. This type is created using 3417 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. 3418 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This 3419 /// class enables syntactic extensions, like Vector Components for accessing 3420 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL 3421 /// Shading Language). 3422 class ExtVectorType : public VectorType { 3423 friend class ASTContext; // ASTContext creates these. 3424 3425 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) 3426 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} 3427 3428 public: 3429 static int getPointAccessorIdx(char c) { 3430 switch (c) { 3431 default: return -1; 3432 case 'x': case 'r': return 0; 3433 case 'y': case 'g': return 1; 3434 case 'z': case 'b': return 2; 3435 case 'w': case 'a': return 3; 3436 } 3437 } 3438 3439 static int getNumericAccessorIdx(char c) { 3440 switch (c) { 3441 default: return -1; 3442 case '0': return 0; 3443 case '1': return 1; 3444 case '2': return 2; 3445 case '3': return 3; 3446 case '4': return 4; 3447 case '5': return 5; 3448 case '6': return 6; 3449 case '7': return 7; 3450 case '8': return 8; 3451 case '9': return 9; 3452 case 'A': 3453 case 'a': return 10; 3454 case 'B': 3455 case 'b': return 11; 3456 case 'C': 3457 case 'c': return 12; 3458 case 'D': 3459 case 'd': return 13; 3460 case 'E': 3461 case 'e': return 14; 3462 case 'F': 3463 case 'f': return 15; 3464 } 3465 } 3466 3467 static int getAccessorIdx(char c, bool isNumericAccessor) { 3468 if (isNumericAccessor) 3469 return getNumericAccessorIdx(c); 3470 else 3471 return getPointAccessorIdx(c); 3472 } 3473 3474 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { 3475 if (int idx = getAccessorIdx(c, isNumericAccessor)+1) 3476 return unsigned(idx-1) < getNumElements(); 3477 return false; 3478 } 3479 3480 bool isSugared() const { return false; } 3481 QualType desugar() const { return QualType(this, 0); } 3482 3483 static bool classof(const Type *T) { 3484 return T->getTypeClass() == ExtVector; 3485 } 3486 }; 3487 3488 /// Represents a matrix type, as defined in the Matrix Types clang extensions. 3489 /// __attribute__((matrix_type(rows, columns))), where "rows" specifies 3490 /// number of rows and "columns" specifies the number of columns. 3491 class MatrixType : public Type, public llvm::FoldingSetNode { 3492 protected: 3493 friend class ASTContext; 3494 3495 /// The element type of the matrix. 3496 QualType ElementType; 3497 3498 MatrixType(QualType ElementTy, QualType CanonElementTy); 3499 3500 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy, 3501 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr); 3502 3503 public: 3504 /// Returns type of the elements being stored in the matrix 3505 QualType getElementType() const { return ElementType; } 3506 3507 /// Valid elements types are the following: 3508 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types 3509 /// and _Bool 3510 /// * the standard floating types float or double 3511 /// * a half-precision floating point type, if one is supported on the target 3512 static bool isValidElementType(QualType T) { 3513 return T->isDependentType() || 3514 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType()); 3515 } 3516 3517 bool isSugared() const { return false; } 3518 QualType desugar() const { return QualType(this, 0); } 3519 3520 static bool classof(const Type *T) { 3521 return T->getTypeClass() == ConstantMatrix || 3522 T->getTypeClass() == DependentSizedMatrix; 3523 } 3524 }; 3525 3526 /// Represents a concrete matrix type with constant number of rows and columns 3527 class ConstantMatrixType final : public MatrixType { 3528 protected: 3529 friend class ASTContext; 3530 3531 /// Number of rows and columns. 3532 unsigned NumRows; 3533 unsigned NumColumns; 3534 3535 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1; 3536 3537 ConstantMatrixType(QualType MatrixElementType, unsigned NRows, 3538 unsigned NColumns, QualType CanonElementType); 3539 3540 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows, 3541 unsigned NColumns, QualType CanonElementType); 3542 3543 public: 3544 /// Returns the number of rows in the matrix. 3545 unsigned getNumRows() const { return NumRows; } 3546 3547 /// Returns the number of columns in the matrix. 3548 unsigned getNumColumns() const { return NumColumns; } 3549 3550 /// Returns the number of elements required to embed the matrix into a vector. 3551 unsigned getNumElementsFlattened() const { 3552 return getNumRows() * getNumColumns(); 3553 } 3554 3555 /// Returns true if \p NumElements is a valid matrix dimension. 3556 static constexpr bool isDimensionValid(size_t NumElements) { 3557 return NumElements > 0 && NumElements <= MaxElementsPerDimension; 3558 } 3559 3560 /// Returns the maximum number of elements per dimension. 3561 static constexpr unsigned getMaxElementsPerDimension() { 3562 return MaxElementsPerDimension; 3563 } 3564 3565 void Profile(llvm::FoldingSetNodeID &ID) { 3566 Profile(ID, getElementType(), getNumRows(), getNumColumns(), 3567 getTypeClass()); 3568 } 3569 3570 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, 3571 unsigned NumRows, unsigned NumColumns, 3572 TypeClass TypeClass) { 3573 ID.AddPointer(ElementType.getAsOpaquePtr()); 3574 ID.AddInteger(NumRows); 3575 ID.AddInteger(NumColumns); 3576 ID.AddInteger(TypeClass); 3577 } 3578 3579 static bool classof(const Type *T) { 3580 return T->getTypeClass() == ConstantMatrix; 3581 } 3582 }; 3583 3584 /// Represents a matrix type where the type and the number of rows and columns 3585 /// is dependent on a template. 3586 class DependentSizedMatrixType final : public MatrixType { 3587 friend class ASTContext; 3588 3589 const ASTContext &Context; 3590 Expr *RowExpr; 3591 Expr *ColumnExpr; 3592 3593 SourceLocation loc; 3594 3595 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType, 3596 QualType CanonicalType, Expr *RowExpr, 3597 Expr *ColumnExpr, SourceLocation loc); 3598 3599 public: 3600 Expr *getRowExpr() const { return RowExpr; } 3601 Expr *getColumnExpr() const { return ColumnExpr; } 3602 SourceLocation getAttributeLoc() const { return loc; } 3603 3604 static bool classof(const Type *T) { 3605 return T->getTypeClass() == DependentSizedMatrix; 3606 } 3607 3608 void Profile(llvm::FoldingSetNodeID &ID) { 3609 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr()); 3610 } 3611 3612 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 3613 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr); 3614 }; 3615 3616 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base 3617 /// class of FunctionNoProtoType and FunctionProtoType. 3618 class FunctionType : public Type { 3619 // The type returned by the function. 3620 QualType ResultType; 3621 3622 public: 3623 /// Interesting information about a specific parameter that can't simply 3624 /// be reflected in parameter's type. This is only used by FunctionProtoType 3625 /// but is in FunctionType to make this class available during the 3626 /// specification of the bases of FunctionProtoType. 3627 /// 3628 /// It makes sense to model language features this way when there's some 3629 /// sort of parameter-specific override (such as an attribute) that 3630 /// affects how the function is called. For example, the ARC ns_consumed 3631 /// attribute changes whether a parameter is passed at +0 (the default) 3632 /// or +1 (ns_consumed). This must be reflected in the function type, 3633 /// but isn't really a change to the parameter type. 3634 /// 3635 /// One serious disadvantage of modelling language features this way is 3636 /// that they generally do not work with language features that attempt 3637 /// to destructure types. For example, template argument deduction will 3638 /// not be able to match a parameter declared as 3639 /// T (*)(U) 3640 /// against an argument of type 3641 /// void (*)(__attribute__((ns_consumed)) id) 3642 /// because the substitution of T=void, U=id into the former will 3643 /// not produce the latter. 3644 class ExtParameterInfo { 3645 enum { 3646 ABIMask = 0x0F, 3647 IsConsumed = 0x10, 3648 HasPassObjSize = 0x20, 3649 IsNoEscape = 0x40, 3650 }; 3651 unsigned char Data = 0; 3652 3653 public: 3654 ExtParameterInfo() = default; 3655 3656 /// Return the ABI treatment of this parameter. 3657 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } 3658 ExtParameterInfo withABI(ParameterABI kind) const { 3659 ExtParameterInfo copy = *this; 3660 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); 3661 return copy; 3662 } 3663 3664 /// Is this parameter considered "consumed" by Objective-C ARC? 3665 /// Consumed parameters must have retainable object type. 3666 bool isConsumed() const { return (Data & IsConsumed); } 3667 ExtParameterInfo withIsConsumed(bool consumed) const { 3668 ExtParameterInfo copy = *this; 3669 if (consumed) 3670 copy.Data |= IsConsumed; 3671 else 3672 copy.Data &= ~IsConsumed; 3673 return copy; 3674 } 3675 3676 bool hasPassObjectSize() const { return Data & HasPassObjSize; } 3677 ExtParameterInfo withHasPassObjectSize() const { 3678 ExtParameterInfo Copy = *this; 3679 Copy.Data |= HasPassObjSize; 3680 return Copy; 3681 } 3682 3683 bool isNoEscape() const { return Data & IsNoEscape; } 3684 ExtParameterInfo withIsNoEscape(bool NoEscape) const { 3685 ExtParameterInfo Copy = *this; 3686 if (NoEscape) 3687 Copy.Data |= IsNoEscape; 3688 else 3689 Copy.Data &= ~IsNoEscape; 3690 return Copy; 3691 } 3692 3693 unsigned char getOpaqueValue() const { return Data; } 3694 static ExtParameterInfo getFromOpaqueValue(unsigned char data) { 3695 ExtParameterInfo result; 3696 result.Data = data; 3697 return result; 3698 } 3699 3700 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { 3701 return lhs.Data == rhs.Data; 3702 } 3703 3704 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { 3705 return lhs.Data != rhs.Data; 3706 } 3707 }; 3708 3709 /// A class which abstracts out some details necessary for 3710 /// making a call. 3711 /// 3712 /// It is not actually used directly for storing this information in 3713 /// a FunctionType, although FunctionType does currently use the 3714 /// same bit-pattern. 3715 /// 3716 // If you add a field (say Foo), other than the obvious places (both, 3717 // constructors, compile failures), what you need to update is 3718 // * Operator== 3719 // * getFoo 3720 // * withFoo 3721 // * functionType. Add Foo, getFoo. 3722 // * ASTContext::getFooType 3723 // * ASTContext::mergeFunctionTypes 3724 // * FunctionNoProtoType::Profile 3725 // * FunctionProtoType::Profile 3726 // * TypePrinter::PrintFunctionProto 3727 // * AST read and write 3728 // * Codegen 3729 class ExtInfo { 3730 friend class FunctionType; 3731 3732 // Feel free to rearrange or add bits, but if you go over 16, you'll need to 3733 // adjust the Bits field below, and if you add bits, you'll need to adjust 3734 // Type::FunctionTypeBitfields::ExtInfo as well. 3735 3736 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall| 3737 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 | 3738 // 3739 // regparm is either 0 (no regparm attribute) or the regparm value+1. 3740 enum { CallConvMask = 0x1F }; 3741 enum { NoReturnMask = 0x20 }; 3742 enum { ProducesResultMask = 0x40 }; 3743 enum { NoCallerSavedRegsMask = 0x80 }; 3744 enum { 3745 RegParmMask = 0x700, 3746 RegParmOffset = 8 3747 }; 3748 enum { NoCfCheckMask = 0x800 }; 3749 enum { CmseNSCallMask = 0x1000 }; 3750 uint16_t Bits = CC_C; 3751 3752 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} 3753 3754 public: 3755 // Constructor with no defaults. Use this when you know that you 3756 // have all the elements (when reading an AST file for example). 3757 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, 3758 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck, 3759 bool cmseNSCall) { 3760 assert((!hasRegParm || regParm < 7) && "Invalid regparm value"); 3761 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | 3762 (producesResult ? ProducesResultMask : 0) | 3763 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | 3764 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | 3765 (NoCfCheck ? NoCfCheckMask : 0) | 3766 (cmseNSCall ? CmseNSCallMask : 0); 3767 } 3768 3769 // Constructor with all defaults. Use when for example creating a 3770 // function known to use defaults. 3771 ExtInfo() = default; 3772 3773 // Constructor with just the calling convention, which is an important part 3774 // of the canonical type. 3775 ExtInfo(CallingConv CC) : Bits(CC) {} 3776 3777 bool getNoReturn() const { return Bits & NoReturnMask; } 3778 bool getProducesResult() const { return Bits & ProducesResultMask; } 3779 bool getCmseNSCall() const { return Bits & CmseNSCallMask; } 3780 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } 3781 bool getNoCfCheck() const { return Bits & NoCfCheckMask; } 3782 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; } 3783 3784 unsigned getRegParm() const { 3785 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; 3786 if (RegParm > 0) 3787 --RegParm; 3788 return RegParm; 3789 } 3790 3791 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } 3792 3793 bool operator==(ExtInfo Other) const { 3794 return Bits == Other.Bits; 3795 } 3796 bool operator!=(ExtInfo Other) const { 3797 return Bits != Other.Bits; 3798 } 3799 3800 // Note that we don't have setters. That is by design, use 3801 // the following with methods instead of mutating these objects. 3802 3803 ExtInfo withNoReturn(bool noReturn) const { 3804 if (noReturn) 3805 return ExtInfo(Bits | NoReturnMask); 3806 else 3807 return ExtInfo(Bits & ~NoReturnMask); 3808 } 3809 3810 ExtInfo withProducesResult(bool producesResult) const { 3811 if (producesResult) 3812 return ExtInfo(Bits | ProducesResultMask); 3813 else 3814 return ExtInfo(Bits & ~ProducesResultMask); 3815 } 3816 3817 ExtInfo withCmseNSCall(bool cmseNSCall) const { 3818 if (cmseNSCall) 3819 return ExtInfo(Bits | CmseNSCallMask); 3820 else 3821 return ExtInfo(Bits & ~CmseNSCallMask); 3822 } 3823 3824 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { 3825 if (noCallerSavedRegs) 3826 return ExtInfo(Bits | NoCallerSavedRegsMask); 3827 else 3828 return ExtInfo(Bits & ~NoCallerSavedRegsMask); 3829 } 3830 3831 ExtInfo withNoCfCheck(bool noCfCheck) const { 3832 if (noCfCheck) 3833 return ExtInfo(Bits | NoCfCheckMask); 3834 else 3835 return ExtInfo(Bits & ~NoCfCheckMask); 3836 } 3837 3838 ExtInfo withRegParm(unsigned RegParm) const { 3839 assert(RegParm < 7 && "Invalid regparm value"); 3840 return ExtInfo((Bits & ~RegParmMask) | 3841 ((RegParm + 1) << RegParmOffset)); 3842 } 3843 3844 ExtInfo withCallingConv(CallingConv cc) const { 3845 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); 3846 } 3847 3848 void Profile(llvm::FoldingSetNodeID &ID) const { 3849 ID.AddInteger(Bits); 3850 } 3851 }; 3852 3853 /// A simple holder for a QualType representing a type in an 3854 /// exception specification. Unfortunately needed by FunctionProtoType 3855 /// because TrailingObjects cannot handle repeated types. 3856 struct ExceptionType { QualType Type; }; 3857 3858 /// A simple holder for various uncommon bits which do not fit in 3859 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the 3860 /// alignment of subsequent objects in TrailingObjects. 3861 struct alignas(void *) FunctionTypeExtraBitfields { 3862 /// The number of types in the exception specification. 3863 /// A whole unsigned is not needed here and according to 3864 /// [implimits] 8 bits would be enough here. 3865 unsigned NumExceptionType = 0; 3866 }; 3867 3868 protected: 3869 FunctionType(TypeClass tc, QualType res, QualType Canonical, 3870 TypeDependence Dependence, ExtInfo Info) 3871 : Type(tc, Canonical, Dependence), ResultType(res) { 3872 FunctionTypeBits.ExtInfo = Info.Bits; 3873 } 3874 3875 Qualifiers getFastTypeQuals() const { 3876 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); 3877 } 3878 3879 public: 3880 QualType getReturnType() const { return ResultType; } 3881 3882 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } 3883 unsigned getRegParmType() const { return getExtInfo().getRegParm(); } 3884 3885 /// Determine whether this function type includes the GNU noreturn 3886 /// attribute. The C++11 [[noreturn]] attribute does not affect the function 3887 /// type. 3888 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } 3889 3890 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); } 3891 CallingConv getCallConv() const { return getExtInfo().getCC(); } 3892 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } 3893 3894 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, 3895 "Const, volatile and restrict are assumed to be a subset of " 3896 "the fast qualifiers."); 3897 3898 bool isConst() const { return getFastTypeQuals().hasConst(); } 3899 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } 3900 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } 3901 3902 /// Determine the type of an expression that calls a function of 3903 /// this type. 3904 QualType getCallResultType(const ASTContext &Context) const { 3905 return getReturnType().getNonLValueExprType(Context); 3906 } 3907 3908 static StringRef getNameForCallConv(CallingConv CC); 3909 3910 static bool classof(const Type *T) { 3911 return T->getTypeClass() == FunctionNoProto || 3912 T->getTypeClass() == FunctionProto; 3913 } 3914 }; 3915 3916 /// Represents a K&R-style 'int foo()' function, which has 3917 /// no information available about its arguments. 3918 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { 3919 friend class ASTContext; // ASTContext creates these. 3920 3921 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) 3922 : FunctionType(FunctionNoProto, Result, Canonical, 3923 Result->getDependence() & 3924 ~(TypeDependence::DependentInstantiation | 3925 TypeDependence::UnexpandedPack), 3926 Info) {} 3927 3928 public: 3929 // No additional state past what FunctionType provides. 3930 3931 bool isSugared() const { return false; } 3932 QualType desugar() const { return QualType(this, 0); } 3933 3934 void Profile(llvm::FoldingSetNodeID &ID) { 3935 Profile(ID, getReturnType(), getExtInfo()); 3936 } 3937 3938 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, 3939 ExtInfo Info) { 3940 Info.Profile(ID); 3941 ID.AddPointer(ResultType.getAsOpaquePtr()); 3942 } 3943 3944 static bool classof(const Type *T) { 3945 return T->getTypeClass() == FunctionNoProto; 3946 } 3947 }; 3948 3949 /// Represents a prototype with parameter type info, e.g. 3950 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no 3951 /// parameters, not as having a single void parameter. Such a type can have 3952 /// an exception specification, but this specification is not part of the 3953 /// canonical type. FunctionProtoType has several trailing objects, some of 3954 /// which optional. For more information about the trailing objects see 3955 /// the first comment inside FunctionProtoType. 3956 class FunctionProtoType final 3957 : public FunctionType, 3958 public llvm::FoldingSetNode, 3959 private llvm::TrailingObjects< 3960 FunctionProtoType, QualType, SourceLocation, 3961 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType, 3962 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> { 3963 friend class ASTContext; // ASTContext creates these. 3964 friend TrailingObjects; 3965 3966 // FunctionProtoType is followed by several trailing objects, some of 3967 // which optional. They are in order: 3968 // 3969 // * An array of getNumParams() QualType holding the parameter types. 3970 // Always present. Note that for the vast majority of FunctionProtoType, 3971 // these will be the only trailing objects. 3972 // 3973 // * Optionally if the function is variadic, the SourceLocation of the 3974 // ellipsis. 3975 // 3976 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields 3977 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): 3978 // a single FunctionTypeExtraBitfields. Present if and only if 3979 // hasExtraBitfields() is true. 3980 // 3981 // * Optionally exactly one of: 3982 // * an array of getNumExceptions() ExceptionType, 3983 // * a single Expr *, 3984 // * a pair of FunctionDecl *, 3985 // * a single FunctionDecl * 3986 // used to store information about the various types of exception 3987 // specification. See getExceptionSpecSize for the details. 3988 // 3989 // * Optionally an array of getNumParams() ExtParameterInfo holding 3990 // an ExtParameterInfo for each of the parameters. Present if and 3991 // only if hasExtParameterInfos() is true. 3992 // 3993 // * Optionally a Qualifiers object to represent extra qualifiers that can't 3994 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only 3995 // if hasExtQualifiers() is true. 3996 // 3997 // The optional FunctionTypeExtraBitfields has to be before the data 3998 // related to the exception specification since it contains the number 3999 // of exception types. 4000 // 4001 // We put the ExtParameterInfos last. If all were equal, it would make 4002 // more sense to put these before the exception specification, because 4003 // it's much easier to skip past them compared to the elaborate switch 4004 // required to skip the exception specification. However, all is not 4005 // equal; ExtParameterInfos are used to model very uncommon features, 4006 // and it's better not to burden the more common paths. 4007 4008 public: 4009 /// Holds information about the various types of exception specification. 4010 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is 4011 /// used to group together the various bits of information about the 4012 /// exception specification. 4013 struct ExceptionSpecInfo { 4014 /// The kind of exception specification this is. 4015 ExceptionSpecificationType Type = EST_None; 4016 4017 /// Explicitly-specified list of exception types. 4018 ArrayRef<QualType> Exceptions; 4019 4020 /// Noexcept expression, if this is a computed noexcept specification. 4021 Expr *NoexceptExpr = nullptr; 4022 4023 /// The function whose exception specification this is, for 4024 /// EST_Unevaluated and EST_Uninstantiated. 4025 FunctionDecl *SourceDecl = nullptr; 4026 4027 /// The function template whose exception specification this is instantiated 4028 /// from, for EST_Uninstantiated. 4029 FunctionDecl *SourceTemplate = nullptr; 4030 4031 ExceptionSpecInfo() = default; 4032 4033 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} 4034 }; 4035 4036 /// Extra information about a function prototype. ExtProtoInfo is not 4037 /// stored as such in FunctionProtoType but is used to group together 4038 /// the various bits of extra information about a function prototype. 4039 struct ExtProtoInfo { 4040 FunctionType::ExtInfo ExtInfo; 4041 bool Variadic : 1; 4042 bool HasTrailingReturn : 1; 4043 Qualifiers TypeQuals; 4044 RefQualifierKind RefQualifier = RQ_None; 4045 ExceptionSpecInfo ExceptionSpec; 4046 const ExtParameterInfo *ExtParameterInfos = nullptr; 4047 SourceLocation EllipsisLoc; 4048 4049 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} 4050 4051 ExtProtoInfo(CallingConv CC) 4052 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} 4053 4054 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { 4055 ExtProtoInfo Result(*this); 4056 Result.ExceptionSpec = ESI; 4057 return Result; 4058 } 4059 4060 bool requiresFunctionProtoTypeExtraBitfields() const { 4061 return ExceptionSpec.Type == EST_Dynamic; 4062 } 4063 }; 4064 4065 private: 4066 unsigned numTrailingObjects(OverloadToken<QualType>) const { 4067 return getNumParams(); 4068 } 4069 4070 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const { 4071 return isVariadic(); 4072 } 4073 4074 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { 4075 return hasExtraBitfields(); 4076 } 4077 4078 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { 4079 return getExceptionSpecSize().NumExceptionType; 4080 } 4081 4082 unsigned numTrailingObjects(OverloadToken<Expr *>) const { 4083 return getExceptionSpecSize().NumExprPtr; 4084 } 4085 4086 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { 4087 return getExceptionSpecSize().NumFunctionDeclPtr; 4088 } 4089 4090 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { 4091 return hasExtParameterInfos() ? getNumParams() : 0; 4092 } 4093 4094 /// Determine whether there are any argument types that 4095 /// contain an unexpanded parameter pack. 4096 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, 4097 unsigned numArgs) { 4098 for (unsigned Idx = 0; Idx < numArgs; ++Idx) 4099 if (ArgArray[Idx]->containsUnexpandedParameterPack()) 4100 return true; 4101 4102 return false; 4103 } 4104 4105 FunctionProtoType(QualType result, ArrayRef<QualType> params, 4106 QualType canonical, const ExtProtoInfo &epi); 4107 4108 /// This struct is returned by getExceptionSpecSize and is used to 4109 /// translate an ExceptionSpecificationType to the number and kind 4110 /// of trailing objects related to the exception specification. 4111 struct ExceptionSpecSizeHolder { 4112 unsigned NumExceptionType; 4113 unsigned NumExprPtr; 4114 unsigned NumFunctionDeclPtr; 4115 }; 4116 4117 /// Return the number and kind of trailing objects 4118 /// related to the exception specification. 4119 static ExceptionSpecSizeHolder 4120 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { 4121 switch (EST) { 4122 case EST_None: 4123 case EST_DynamicNone: 4124 case EST_MSAny: 4125 case EST_BasicNoexcept: 4126 case EST_Unparsed: 4127 case EST_NoThrow: 4128 return {0, 0, 0}; 4129 4130 case EST_Dynamic: 4131 return {NumExceptions, 0, 0}; 4132 4133 case EST_DependentNoexcept: 4134 case EST_NoexceptFalse: 4135 case EST_NoexceptTrue: 4136 return {0, 1, 0}; 4137 4138 case EST_Uninstantiated: 4139 return {0, 0, 2}; 4140 4141 case EST_Unevaluated: 4142 return {0, 0, 1}; 4143 } 4144 llvm_unreachable("bad exception specification kind"); 4145 } 4146 4147 /// Return the number and kind of trailing objects 4148 /// related to the exception specification. 4149 ExceptionSpecSizeHolder getExceptionSpecSize() const { 4150 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); 4151 } 4152 4153 /// Whether the trailing FunctionTypeExtraBitfields is present. 4154 bool hasExtraBitfields() const { 4155 assert((getExceptionSpecType() != EST_Dynamic || 4156 FunctionTypeBits.HasExtraBitfields) && 4157 "ExtraBitfields are required for given ExceptionSpecType"); 4158 return FunctionTypeBits.HasExtraBitfields; 4159 4160 } 4161 4162 bool hasExtQualifiers() const { 4163 return FunctionTypeBits.HasExtQuals; 4164 } 4165 4166 public: 4167 unsigned getNumParams() const { return FunctionTypeBits.NumParams; } 4168 4169 QualType getParamType(unsigned i) const { 4170 assert(i < getNumParams() && "invalid parameter index"); 4171 return param_type_begin()[i]; 4172 } 4173 4174 ArrayRef<QualType> getParamTypes() const { 4175 return llvm::makeArrayRef(param_type_begin(), param_type_end()); 4176 } 4177 4178 ExtProtoInfo getExtProtoInfo() const { 4179 ExtProtoInfo EPI; 4180 EPI.ExtInfo = getExtInfo(); 4181 EPI.Variadic = isVariadic(); 4182 EPI.EllipsisLoc = getEllipsisLoc(); 4183 EPI.HasTrailingReturn = hasTrailingReturn(); 4184 EPI.ExceptionSpec = getExceptionSpecInfo(); 4185 EPI.TypeQuals = getMethodQuals(); 4186 EPI.RefQualifier = getRefQualifier(); 4187 EPI.ExtParameterInfos = getExtParameterInfosOrNull(); 4188 return EPI; 4189 } 4190 4191 /// Get the kind of exception specification on this function. 4192 ExceptionSpecificationType getExceptionSpecType() const { 4193 return static_cast<ExceptionSpecificationType>( 4194 FunctionTypeBits.ExceptionSpecType); 4195 } 4196 4197 /// Return whether this function has any kind of exception spec. 4198 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } 4199 4200 /// Return whether this function has a dynamic (throw) exception spec. 4201 bool hasDynamicExceptionSpec() const { 4202 return isDynamicExceptionSpec(getExceptionSpecType()); 4203 } 4204 4205 /// Return whether this function has a noexcept exception spec. 4206 bool hasNoexceptExceptionSpec() const { 4207 return isNoexceptExceptionSpec(getExceptionSpecType()); 4208 } 4209 4210 /// Return whether this function has a dependent exception spec. 4211 bool hasDependentExceptionSpec() const; 4212 4213 /// Return whether this function has an instantiation-dependent exception 4214 /// spec. 4215 bool hasInstantiationDependentExceptionSpec() const; 4216 4217 /// Return all the available information about this type's exception spec. 4218 ExceptionSpecInfo getExceptionSpecInfo() const { 4219 ExceptionSpecInfo Result; 4220 Result.Type = getExceptionSpecType(); 4221 if (Result.Type == EST_Dynamic) { 4222 Result.Exceptions = exceptions(); 4223 } else if (isComputedNoexcept(Result.Type)) { 4224 Result.NoexceptExpr = getNoexceptExpr(); 4225 } else if (Result.Type == EST_Uninstantiated) { 4226 Result.SourceDecl = getExceptionSpecDecl(); 4227 Result.SourceTemplate = getExceptionSpecTemplate(); 4228 } else if (Result.Type == EST_Unevaluated) { 4229 Result.SourceDecl = getExceptionSpecDecl(); 4230 } 4231 return Result; 4232 } 4233 4234 /// Return the number of types in the exception specification. 4235 unsigned getNumExceptions() const { 4236 return getExceptionSpecType() == EST_Dynamic 4237 ? getTrailingObjects<FunctionTypeExtraBitfields>() 4238 ->NumExceptionType 4239 : 0; 4240 } 4241 4242 /// Return the ith exception type, where 0 <= i < getNumExceptions(). 4243 QualType getExceptionType(unsigned i) const { 4244 assert(i < getNumExceptions() && "Invalid exception number!"); 4245 return exception_begin()[i]; 4246 } 4247 4248 /// Return the expression inside noexcept(expression), or a null pointer 4249 /// if there is none (because the exception spec is not of this form). 4250 Expr *getNoexceptExpr() const { 4251 if (!isComputedNoexcept(getExceptionSpecType())) 4252 return nullptr; 4253 return *getTrailingObjects<Expr *>(); 4254 } 4255 4256 /// If this function type has an exception specification which hasn't 4257 /// been determined yet (either because it has not been evaluated or because 4258 /// it has not been instantiated), this is the function whose exception 4259 /// specification is represented by this type. 4260 FunctionDecl *getExceptionSpecDecl() const { 4261 if (getExceptionSpecType() != EST_Uninstantiated && 4262 getExceptionSpecType() != EST_Unevaluated) 4263 return nullptr; 4264 return getTrailingObjects<FunctionDecl *>()[0]; 4265 } 4266 4267 /// If this function type has an uninstantiated exception 4268 /// specification, this is the function whose exception specification 4269 /// should be instantiated to find the exception specification for 4270 /// this type. 4271 FunctionDecl *getExceptionSpecTemplate() const { 4272 if (getExceptionSpecType() != EST_Uninstantiated) 4273 return nullptr; 4274 return getTrailingObjects<FunctionDecl *>()[1]; 4275 } 4276 4277 /// Determine whether this function type has a non-throwing exception 4278 /// specification. 4279 CanThrowResult canThrow() const; 4280 4281 /// Determine whether this function type has a non-throwing exception 4282 /// specification. If this depends on template arguments, returns 4283 /// \c ResultIfDependent. 4284 bool isNothrow(bool ResultIfDependent = false) const { 4285 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; 4286 } 4287 4288 /// Whether this function prototype is variadic. 4289 bool isVariadic() const { return FunctionTypeBits.Variadic; } 4290 4291 SourceLocation getEllipsisLoc() const { 4292 return isVariadic() ? *getTrailingObjects<SourceLocation>() 4293 : SourceLocation(); 4294 } 4295 4296 /// Determines whether this function prototype contains a 4297 /// parameter pack at the end. 4298 /// 4299 /// A function template whose last parameter is a parameter pack can be 4300 /// called with an arbitrary number of arguments, much like a variadic 4301 /// function. 4302 bool isTemplateVariadic() const; 4303 4304 /// Whether this function prototype has a trailing return type. 4305 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } 4306 4307 Qualifiers getMethodQuals() const { 4308 if (hasExtQualifiers()) 4309 return *getTrailingObjects<Qualifiers>(); 4310 else 4311 return getFastTypeQuals(); 4312 } 4313 4314 /// Retrieve the ref-qualifier associated with this function type. 4315 RefQualifierKind getRefQualifier() const { 4316 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); 4317 } 4318 4319 using param_type_iterator = const QualType *; 4320 using param_type_range = llvm::iterator_range<param_type_iterator>; 4321 4322 param_type_range param_types() const { 4323 return param_type_range(param_type_begin(), param_type_end()); 4324 } 4325 4326 param_type_iterator param_type_begin() const { 4327 return getTrailingObjects<QualType>(); 4328 } 4329 4330 param_type_iterator param_type_end() const { 4331 return param_type_begin() + getNumParams(); 4332 } 4333 4334 using exception_iterator = const QualType *; 4335 4336 ArrayRef<QualType> exceptions() const { 4337 return llvm::makeArrayRef(exception_begin(), exception_end()); 4338 } 4339 4340 exception_iterator exception_begin() const { 4341 return reinterpret_cast<exception_iterator>( 4342 getTrailingObjects<ExceptionType>()); 4343 } 4344 4345 exception_iterator exception_end() const { 4346 return exception_begin() + getNumExceptions(); 4347 } 4348 4349 /// Is there any interesting extra information for any of the parameters 4350 /// of this function type? 4351 bool hasExtParameterInfos() const { 4352 return FunctionTypeBits.HasExtParameterInfos; 4353 } 4354 4355 ArrayRef<ExtParameterInfo> getExtParameterInfos() const { 4356 assert(hasExtParameterInfos()); 4357 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), 4358 getNumParams()); 4359 } 4360 4361 /// Return a pointer to the beginning of the array of extra parameter 4362 /// information, if present, or else null if none of the parameters 4363 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. 4364 const ExtParameterInfo *getExtParameterInfosOrNull() const { 4365 if (!hasExtParameterInfos()) 4366 return nullptr; 4367 return getTrailingObjects<ExtParameterInfo>(); 4368 } 4369 4370 ExtParameterInfo getExtParameterInfo(unsigned I) const { 4371 assert(I < getNumParams() && "parameter index out of range"); 4372 if (hasExtParameterInfos()) 4373 return getTrailingObjects<ExtParameterInfo>()[I]; 4374 return ExtParameterInfo(); 4375 } 4376 4377 ParameterABI getParameterABI(unsigned I) const { 4378 assert(I < getNumParams() && "parameter index out of range"); 4379 if (hasExtParameterInfos()) 4380 return getTrailingObjects<ExtParameterInfo>()[I].getABI(); 4381 return ParameterABI::Ordinary; 4382 } 4383 4384 bool isParamConsumed(unsigned I) const { 4385 assert(I < getNumParams() && "parameter index out of range"); 4386 if (hasExtParameterInfos()) 4387 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); 4388 return false; 4389 } 4390 4391 bool isSugared() const { return false; } 4392 QualType desugar() const { return QualType(this, 0); } 4393 4394 void printExceptionSpecification(raw_ostream &OS, 4395 const PrintingPolicy &Policy) const; 4396 4397 static bool classof(const Type *T) { 4398 return T->getTypeClass() == FunctionProto; 4399 } 4400 4401 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); 4402 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, 4403 param_type_iterator ArgTys, unsigned NumArgs, 4404 const ExtProtoInfo &EPI, const ASTContext &Context, 4405 bool Canonical); 4406 }; 4407 4408 /// Represents the dependent type named by a dependently-scoped 4409 /// typename using declaration, e.g. 4410 /// using typename Base<T>::foo; 4411 /// 4412 /// Template instantiation turns these into the underlying type. 4413 class UnresolvedUsingType : public Type { 4414 friend class ASTContext; // ASTContext creates these. 4415 4416 UnresolvedUsingTypenameDecl *Decl; 4417 4418 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) 4419 : Type(UnresolvedUsing, QualType(), 4420 TypeDependence::DependentInstantiation), 4421 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {} 4422 4423 public: 4424 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } 4425 4426 bool isSugared() const { return false; } 4427 QualType desugar() const { return QualType(this, 0); } 4428 4429 static bool classof(const Type *T) { 4430 return T->getTypeClass() == UnresolvedUsing; 4431 } 4432 4433 void Profile(llvm::FoldingSetNodeID &ID) { 4434 return Profile(ID, Decl); 4435 } 4436 4437 static void Profile(llvm::FoldingSetNodeID &ID, 4438 UnresolvedUsingTypenameDecl *D) { 4439 ID.AddPointer(D); 4440 } 4441 }; 4442 4443 class UsingType : public Type, public llvm::FoldingSetNode { 4444 UsingShadowDecl *Found; 4445 friend class ASTContext; // ASTContext creates these. 4446 4447 UsingType(const UsingShadowDecl *Found, QualType Underlying, QualType Canon); 4448 4449 public: 4450 UsingShadowDecl *getFoundDecl() const { return Found; } 4451 QualType getUnderlyingType() const; 4452 4453 bool isSugared() const { return true; } 4454 QualType desugar() const { return getUnderlyingType(); } 4455 4456 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Found); } 4457 static void Profile(llvm::FoldingSetNodeID &ID, 4458 const UsingShadowDecl *Found) { 4459 ID.AddPointer(Found); 4460 } 4461 static bool classof(const Type *T) { return T->getTypeClass() == Using; } 4462 }; 4463 4464 class TypedefType : public Type { 4465 TypedefNameDecl *Decl; 4466 4467 private: 4468 friend class ASTContext; // ASTContext creates these. 4469 4470 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying, 4471 QualType can); 4472 4473 public: 4474 TypedefNameDecl *getDecl() const { return Decl; } 4475 4476 bool isSugared() const { return true; } 4477 QualType desugar() const; 4478 4479 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } 4480 }; 4481 4482 /// Sugar type that represents a type that was qualified by a qualifier written 4483 /// as a macro invocation. 4484 class MacroQualifiedType : public Type { 4485 friend class ASTContext; // ASTContext creates these. 4486 4487 QualType UnderlyingTy; 4488 const IdentifierInfo *MacroII; 4489 4490 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, 4491 const IdentifierInfo *MacroII) 4492 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()), 4493 UnderlyingTy(UnderlyingTy), MacroII(MacroII) { 4494 assert(isa<AttributedType>(UnderlyingTy) && 4495 "Expected a macro qualified type to only wrap attributed types."); 4496 } 4497 4498 public: 4499 const IdentifierInfo *getMacroIdentifier() const { return MacroII; } 4500 QualType getUnderlyingType() const { return UnderlyingTy; } 4501 4502 /// Return this attributed type's modified type with no qualifiers attached to 4503 /// it. 4504 QualType getModifiedType() const; 4505 4506 bool isSugared() const { return true; } 4507 QualType desugar() const; 4508 4509 static bool classof(const Type *T) { 4510 return T->getTypeClass() == MacroQualified; 4511 } 4512 }; 4513 4514 /// Represents a `typeof` (or __typeof__) expression (a GCC extension). 4515 class TypeOfExprType : public Type { 4516 Expr *TOExpr; 4517 4518 protected: 4519 friend class ASTContext; // ASTContext creates these. 4520 4521 TypeOfExprType(Expr *E, QualType can = QualType()); 4522 4523 public: 4524 Expr *getUnderlyingExpr() const { return TOExpr; } 4525 4526 /// Remove a single level of sugar. 4527 QualType desugar() const; 4528 4529 /// Returns whether this type directly provides sugar. 4530 bool isSugared() const; 4531 4532 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } 4533 }; 4534 4535 /// Internal representation of canonical, dependent 4536 /// `typeof(expr)` types. 4537 /// 4538 /// This class is used internally by the ASTContext to manage 4539 /// canonical, dependent types, only. Clients will only see instances 4540 /// of this class via TypeOfExprType nodes. 4541 class DependentTypeOfExprType 4542 : public TypeOfExprType, public llvm::FoldingSetNode { 4543 const ASTContext &Context; 4544 4545 public: 4546 DependentTypeOfExprType(const ASTContext &Context, Expr *E) 4547 : TypeOfExprType(E), Context(Context) {} 4548 4549 void Profile(llvm::FoldingSetNodeID &ID) { 4550 Profile(ID, Context, getUnderlyingExpr()); 4551 } 4552 4553 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4554 Expr *E); 4555 }; 4556 4557 /// Represents `typeof(type)`, a GCC extension. 4558 class TypeOfType : public Type { 4559 friend class ASTContext; // ASTContext creates these. 4560 4561 QualType TOType; 4562 4563 TypeOfType(QualType T, QualType can) 4564 : Type(TypeOf, can, T->getDependence()), TOType(T) { 4565 assert(!isa<TypedefType>(can) && "Invalid canonical type"); 4566 } 4567 4568 public: 4569 QualType getUnderlyingType() const { return TOType; } 4570 4571 /// Remove a single level of sugar. 4572 QualType desugar() const { return getUnderlyingType(); } 4573 4574 /// Returns whether this type directly provides sugar. 4575 bool isSugared() const { return true; } 4576 4577 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } 4578 }; 4579 4580 /// Represents the type `decltype(expr)` (C++11). 4581 class DecltypeType : public Type { 4582 Expr *E; 4583 QualType UnderlyingType; 4584 4585 protected: 4586 friend class ASTContext; // ASTContext creates these. 4587 4588 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); 4589 4590 public: 4591 Expr *getUnderlyingExpr() const { return E; } 4592 QualType getUnderlyingType() const { return UnderlyingType; } 4593 4594 /// Remove a single level of sugar. 4595 QualType desugar() const; 4596 4597 /// Returns whether this type directly provides sugar. 4598 bool isSugared() const; 4599 4600 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } 4601 }; 4602 4603 /// Internal representation of canonical, dependent 4604 /// decltype(expr) types. 4605 /// 4606 /// This class is used internally by the ASTContext to manage 4607 /// canonical, dependent types, only. Clients will only see instances 4608 /// of this class via DecltypeType nodes. 4609 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { 4610 const ASTContext &Context; 4611 4612 public: 4613 DependentDecltypeType(const ASTContext &Context, Expr *E); 4614 4615 void Profile(llvm::FoldingSetNodeID &ID) { 4616 Profile(ID, Context, getUnderlyingExpr()); 4617 } 4618 4619 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 4620 Expr *E); 4621 }; 4622 4623 /// A unary type transform, which is a type constructed from another. 4624 class UnaryTransformType : public Type { 4625 public: 4626 enum UTTKind { 4627 EnumUnderlyingType 4628 }; 4629 4630 private: 4631 /// The untransformed type. 4632 QualType BaseType; 4633 4634 /// The transformed type if not dependent, otherwise the same as BaseType. 4635 QualType UnderlyingType; 4636 4637 UTTKind UKind; 4638 4639 protected: 4640 friend class ASTContext; 4641 4642 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, 4643 QualType CanonicalTy); 4644 4645 public: 4646 bool isSugared() const { return !isDependentType(); } 4647 QualType desugar() const { return UnderlyingType; } 4648 4649 QualType getUnderlyingType() const { return UnderlyingType; } 4650 QualType getBaseType() const { return BaseType; } 4651 4652 UTTKind getUTTKind() const { return UKind; } 4653 4654 static bool classof(const Type *T) { 4655 return T->getTypeClass() == UnaryTransform; 4656 } 4657 }; 4658 4659 /// Internal representation of canonical, dependent 4660 /// __underlying_type(type) types. 4661 /// 4662 /// This class is used internally by the ASTContext to manage 4663 /// canonical, dependent types, only. Clients will only see instances 4664 /// of this class via UnaryTransformType nodes. 4665 class DependentUnaryTransformType : public UnaryTransformType, 4666 public llvm::FoldingSetNode { 4667 public: 4668 DependentUnaryTransformType(const ASTContext &C, QualType BaseType, 4669 UTTKind UKind); 4670 4671 void Profile(llvm::FoldingSetNodeID &ID) { 4672 Profile(ID, getBaseType(), getUTTKind()); 4673 } 4674 4675 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, 4676 UTTKind UKind) { 4677 ID.AddPointer(BaseType.getAsOpaquePtr()); 4678 ID.AddInteger((unsigned)UKind); 4679 } 4680 }; 4681 4682 class TagType : public Type { 4683 friend class ASTReader; 4684 template <class T> friend class serialization::AbstractTypeReader; 4685 4686 /// Stores the TagDecl associated with this type. The decl may point to any 4687 /// TagDecl that declares the entity. 4688 TagDecl *decl; 4689 4690 protected: 4691 TagType(TypeClass TC, const TagDecl *D, QualType can); 4692 4693 public: 4694 TagDecl *getDecl() const; 4695 4696 /// Determines whether this type is in the process of being defined. 4697 bool isBeingDefined() const; 4698 4699 static bool classof(const Type *T) { 4700 return T->getTypeClass() == Enum || T->getTypeClass() == Record; 4701 } 4702 }; 4703 4704 /// A helper class that allows the use of isa/cast/dyncast 4705 /// to detect TagType objects of structs/unions/classes. 4706 class RecordType : public TagType { 4707 protected: 4708 friend class ASTContext; // ASTContext creates these. 4709 4710 explicit RecordType(const RecordDecl *D) 4711 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4712 explicit RecordType(TypeClass TC, RecordDecl *D) 4713 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4714 4715 public: 4716 RecordDecl *getDecl() const { 4717 return reinterpret_cast<RecordDecl*>(TagType::getDecl()); 4718 } 4719 4720 /// Recursively check all fields in the record for const-ness. If any field 4721 /// is declared const, return true. Otherwise, return false. 4722 bool hasConstFields() const; 4723 4724 bool isSugared() const { return false; } 4725 QualType desugar() const { return QualType(this, 0); } 4726 4727 static bool classof(const Type *T) { return T->getTypeClass() == Record; } 4728 }; 4729 4730 /// A helper class that allows the use of isa/cast/dyncast 4731 /// to detect TagType objects of enums. 4732 class EnumType : public TagType { 4733 friend class ASTContext; // ASTContext creates these. 4734 4735 explicit EnumType(const EnumDecl *D) 4736 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} 4737 4738 public: 4739 EnumDecl *getDecl() const { 4740 return reinterpret_cast<EnumDecl*>(TagType::getDecl()); 4741 } 4742 4743 bool isSugared() const { return false; } 4744 QualType desugar() const { return QualType(this, 0); } 4745 4746 static bool classof(const Type *T) { return T->getTypeClass() == Enum; } 4747 }; 4748 4749 /// An attributed type is a type to which a type attribute has been applied. 4750 /// 4751 /// The "modified type" is the fully-sugared type to which the attributed 4752 /// type was applied; generally it is not canonically equivalent to the 4753 /// attributed type. The "equivalent type" is the minimally-desugared type 4754 /// which the type is canonically equivalent to. 4755 /// 4756 /// For example, in the following attributed type: 4757 /// int32_t __attribute__((vector_size(16))) 4758 /// - the modified type is the TypedefType for int32_t 4759 /// - the equivalent type is VectorType(16, int32_t) 4760 /// - the canonical type is VectorType(16, int) 4761 class AttributedType : public Type, public llvm::FoldingSetNode { 4762 public: 4763 using Kind = attr::Kind; 4764 4765 private: 4766 friend class ASTContext; // ASTContext creates these 4767 4768 QualType ModifiedType; 4769 QualType EquivalentType; 4770 4771 AttributedType(QualType canon, attr::Kind attrKind, QualType modified, 4772 QualType equivalent) 4773 : Type(Attributed, canon, equivalent->getDependence()), 4774 ModifiedType(modified), EquivalentType(equivalent) { 4775 AttributedTypeBits.AttrKind = attrKind; 4776 } 4777 4778 public: 4779 Kind getAttrKind() const { 4780 return static_cast<Kind>(AttributedTypeBits.AttrKind); 4781 } 4782 4783 QualType getModifiedType() const { return ModifiedType; } 4784 QualType getEquivalentType() const { return EquivalentType; } 4785 4786 bool isSugared() const { return true; } 4787 QualType desugar() const { return getEquivalentType(); } 4788 4789 /// Does this attribute behave like a type qualifier? 4790 /// 4791 /// A type qualifier adjusts a type to provide specialized rules for 4792 /// a specific object, like the standard const and volatile qualifiers. 4793 /// This includes attributes controlling things like nullability, 4794 /// address spaces, and ARC ownership. The value of the object is still 4795 /// largely described by the modified type. 4796 /// 4797 /// In contrast, many type attributes "rewrite" their modified type to 4798 /// produce a fundamentally different type, not necessarily related in any 4799 /// formalizable way to the original type. For example, calling convention 4800 /// and vector attributes are not simple type qualifiers. 4801 /// 4802 /// Type qualifiers are often, but not always, reflected in the canonical 4803 /// type. 4804 bool isQualifier() const; 4805 4806 bool isMSTypeSpec() const; 4807 4808 bool isCallingConv() const; 4809 4810 llvm::Optional<NullabilityKind> getImmediateNullability() const; 4811 4812 /// Retrieve the attribute kind corresponding to the given 4813 /// nullability kind. 4814 static Kind getNullabilityAttrKind(NullabilityKind kind) { 4815 switch (kind) { 4816 case NullabilityKind::NonNull: 4817 return attr::TypeNonNull; 4818 4819 case NullabilityKind::Nullable: 4820 return attr::TypeNullable; 4821 4822 case NullabilityKind::NullableResult: 4823 return attr::TypeNullableResult; 4824 4825 case NullabilityKind::Unspecified: 4826 return attr::TypeNullUnspecified; 4827 } 4828 llvm_unreachable("Unknown nullability kind."); 4829 } 4830 4831 /// Strip off the top-level nullability annotation on the given 4832 /// type, if it's there. 4833 /// 4834 /// \param T The type to strip. If the type is exactly an 4835 /// AttributedType specifying nullability (without looking through 4836 /// type sugar), the nullability is returned and this type changed 4837 /// to the underlying modified type. 4838 /// 4839 /// \returns the top-level nullability, if present. 4840 static Optional<NullabilityKind> stripOuterNullability(QualType &T); 4841 4842 void Profile(llvm::FoldingSetNodeID &ID) { 4843 Profile(ID, getAttrKind(), ModifiedType, EquivalentType); 4844 } 4845 4846 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, 4847 QualType modified, QualType equivalent) { 4848 ID.AddInteger(attrKind); 4849 ID.AddPointer(modified.getAsOpaquePtr()); 4850 ID.AddPointer(equivalent.getAsOpaquePtr()); 4851 } 4852 4853 static bool classof(const Type *T) { 4854 return T->getTypeClass() == Attributed; 4855 } 4856 }; 4857 4858 class BTFTagAttributedType : public Type, public llvm::FoldingSetNode { 4859 private: 4860 friend class ASTContext; // ASTContext creates these 4861 4862 QualType WrappedType; 4863 const BTFTypeTagAttr *BTFAttr; 4864 4865 BTFTagAttributedType(QualType Canon, QualType Wrapped, 4866 const BTFTypeTagAttr *BTFAttr) 4867 : Type(BTFTagAttributed, Canon, Wrapped->getDependence()), 4868 WrappedType(Wrapped), BTFAttr(BTFAttr) {} 4869 4870 public: 4871 QualType getWrappedType() const { return WrappedType; } 4872 const BTFTypeTagAttr *getAttr() const { return BTFAttr; } 4873 4874 bool isSugared() const { return true; } 4875 QualType desugar() const { return getWrappedType(); } 4876 4877 void Profile(llvm::FoldingSetNodeID &ID) { 4878 Profile(ID, WrappedType, BTFAttr); 4879 } 4880 4881 static void Profile(llvm::FoldingSetNodeID &ID, QualType Wrapped, 4882 const BTFTypeTagAttr *BTFAttr) { 4883 ID.AddPointer(Wrapped.getAsOpaquePtr()); 4884 ID.AddPointer(BTFAttr); 4885 } 4886 4887 static bool classof(const Type *T) { 4888 return T->getTypeClass() == BTFTagAttributed; 4889 } 4890 }; 4891 4892 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { 4893 friend class ASTContext; // ASTContext creates these 4894 4895 // Helper data collector for canonical types. 4896 struct CanonicalTTPTInfo { 4897 unsigned Depth : 15; 4898 unsigned ParameterPack : 1; 4899 unsigned Index : 16; 4900 }; 4901 4902 union { 4903 // Info for the canonical type. 4904 CanonicalTTPTInfo CanTTPTInfo; 4905 4906 // Info for the non-canonical type. 4907 TemplateTypeParmDecl *TTPDecl; 4908 }; 4909 4910 /// Build a non-canonical type. 4911 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) 4912 : Type(TemplateTypeParm, Canon, 4913 TypeDependence::DependentInstantiation | 4914 (Canon->getDependence() & TypeDependence::UnexpandedPack)), 4915 TTPDecl(TTPDecl) {} 4916 4917 /// Build the canonical type. 4918 TemplateTypeParmType(unsigned D, unsigned I, bool PP) 4919 : Type(TemplateTypeParm, QualType(this, 0), 4920 TypeDependence::DependentInstantiation | 4921 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) { 4922 CanTTPTInfo.Depth = D; 4923 CanTTPTInfo.Index = I; 4924 CanTTPTInfo.ParameterPack = PP; 4925 } 4926 4927 const CanonicalTTPTInfo& getCanTTPTInfo() const { 4928 QualType Can = getCanonicalTypeInternal(); 4929 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; 4930 } 4931 4932 public: 4933 unsigned getDepth() const { return getCanTTPTInfo().Depth; } 4934 unsigned getIndex() const { return getCanTTPTInfo().Index; } 4935 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } 4936 4937 TemplateTypeParmDecl *getDecl() const { 4938 return isCanonicalUnqualified() ? nullptr : TTPDecl; 4939 } 4940 4941 IdentifierInfo *getIdentifier() const; 4942 4943 bool isSugared() const { return false; } 4944 QualType desugar() const { return QualType(this, 0); } 4945 4946 void Profile(llvm::FoldingSetNodeID &ID) { 4947 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); 4948 } 4949 4950 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, 4951 unsigned Index, bool ParameterPack, 4952 TemplateTypeParmDecl *TTPDecl) { 4953 ID.AddInteger(Depth); 4954 ID.AddInteger(Index); 4955 ID.AddBoolean(ParameterPack); 4956 ID.AddPointer(TTPDecl); 4957 } 4958 4959 static bool classof(const Type *T) { 4960 return T->getTypeClass() == TemplateTypeParm; 4961 } 4962 }; 4963 4964 /// Represents the result of substituting a type for a template 4965 /// type parameter. 4966 /// 4967 /// Within an instantiated template, all template type parameters have 4968 /// been replaced with these. They are used solely to record that a 4969 /// type was originally written as a template type parameter; 4970 /// therefore they are never canonical. 4971 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { 4972 friend class ASTContext; 4973 4974 // The original type parameter. 4975 const TemplateTypeParmType *Replaced; 4976 4977 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) 4978 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()), 4979 Replaced(Param) {} 4980 4981 public: 4982 /// Gets the template parameter that was substituted for. 4983 const TemplateTypeParmType *getReplacedParameter() const { 4984 return Replaced; 4985 } 4986 4987 /// Gets the type that was substituted for the template 4988 /// parameter. 4989 QualType getReplacementType() const { 4990 return getCanonicalTypeInternal(); 4991 } 4992 4993 bool isSugared() const { return true; } 4994 QualType desugar() const { return getReplacementType(); } 4995 4996 void Profile(llvm::FoldingSetNodeID &ID) { 4997 Profile(ID, getReplacedParameter(), getReplacementType()); 4998 } 4999 5000 static void Profile(llvm::FoldingSetNodeID &ID, 5001 const TemplateTypeParmType *Replaced, 5002 QualType Replacement) { 5003 ID.AddPointer(Replaced); 5004 ID.AddPointer(Replacement.getAsOpaquePtr()); 5005 } 5006 5007 static bool classof(const Type *T) { 5008 return T->getTypeClass() == SubstTemplateTypeParm; 5009 } 5010 }; 5011 5012 /// Represents the result of substituting a set of types for a template 5013 /// type parameter pack. 5014 /// 5015 /// When a pack expansion in the source code contains multiple parameter packs 5016 /// and those parameter packs correspond to different levels of template 5017 /// parameter lists, this type node is used to represent a template type 5018 /// parameter pack from an outer level, which has already had its argument pack 5019 /// substituted but that still lives within a pack expansion that itself 5020 /// could not be instantiated. When actually performing a substitution into 5021 /// that pack expansion (e.g., when all template parameters have corresponding 5022 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType 5023 /// at the current pack substitution index. 5024 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { 5025 friend class ASTContext; 5026 5027 /// The original type parameter. 5028 const TemplateTypeParmType *Replaced; 5029 5030 /// A pointer to the set of template arguments that this 5031 /// parameter pack is instantiated with. 5032 const TemplateArgument *Arguments; 5033 5034 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 5035 QualType Canon, 5036 const TemplateArgument &ArgPack); 5037 5038 public: 5039 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } 5040 5041 /// Gets the template parameter that was substituted for. 5042 const TemplateTypeParmType *getReplacedParameter() const { 5043 return Replaced; 5044 } 5045 5046 unsigned getNumArgs() const { 5047 return SubstTemplateTypeParmPackTypeBits.NumArgs; 5048 } 5049 5050 bool isSugared() const { return false; } 5051 QualType desugar() const { return QualType(this, 0); } 5052 5053 TemplateArgument getArgumentPack() const; 5054 5055 void Profile(llvm::FoldingSetNodeID &ID); 5056 static void Profile(llvm::FoldingSetNodeID &ID, 5057 const TemplateTypeParmType *Replaced, 5058 const TemplateArgument &ArgPack); 5059 5060 static bool classof(const Type *T) { 5061 return T->getTypeClass() == SubstTemplateTypeParmPack; 5062 } 5063 }; 5064 5065 /// Common base class for placeholders for types that get replaced by 5066 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced 5067 /// class template types, and constrained type names. 5068 /// 5069 /// These types are usually a placeholder for a deduced type. However, before 5070 /// the initializer is attached, or (usually) if the initializer is 5071 /// type-dependent, there is no deduced type and the type is canonical. In 5072 /// the latter case, it is also a dependent type. 5073 class DeducedType : public Type { 5074 QualType DeducedAsType; 5075 5076 protected: 5077 DeducedType(TypeClass TC, QualType DeducedAsType, 5078 TypeDependence ExtraDependence, QualType Canon) 5079 : Type(TC, Canon, 5080 ExtraDependence | (DeducedAsType.isNull() 5081 ? TypeDependence::None 5082 : DeducedAsType->getDependence() & 5083 ~TypeDependence::VariablyModified)), 5084 DeducedAsType(DeducedAsType) {} 5085 5086 public: 5087 bool isSugared() const { return !DeducedAsType.isNull(); } 5088 QualType desugar() const { 5089 return isSugared() ? DeducedAsType : QualType(this, 0); 5090 } 5091 5092 /// Get the type deduced for this placeholder type, or null if it 5093 /// has not been deduced. 5094 QualType getDeducedType() const { return DeducedAsType; } 5095 bool isDeduced() const { 5096 return !DeducedAsType.isNull() || isDependentType(); 5097 } 5098 5099 static bool classof(const Type *T) { 5100 return T->getTypeClass() == Auto || 5101 T->getTypeClass() == DeducedTemplateSpecialization; 5102 } 5103 }; 5104 5105 /// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained 5106 /// by a type-constraint. 5107 class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode { 5108 friend class ASTContext; // ASTContext creates these 5109 5110 ConceptDecl *TypeConstraintConcept; 5111 5112 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, 5113 TypeDependence ExtraDependence, QualType Canon, ConceptDecl *CD, 5114 ArrayRef<TemplateArgument> TypeConstraintArgs); 5115 5116 const TemplateArgument *getArgBuffer() const { 5117 return reinterpret_cast<const TemplateArgument*>(this+1); 5118 } 5119 5120 TemplateArgument *getArgBuffer() { 5121 return reinterpret_cast<TemplateArgument*>(this+1); 5122 } 5123 5124 public: 5125 /// Retrieve the template arguments. 5126 const TemplateArgument *getArgs() const { 5127 return getArgBuffer(); 5128 } 5129 5130 /// Retrieve the number of template arguments. 5131 unsigned getNumArgs() const { 5132 return AutoTypeBits.NumArgs; 5133 } 5134 5135 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5136 5137 ArrayRef<TemplateArgument> getTypeConstraintArguments() const { 5138 return {getArgs(), getNumArgs()}; 5139 } 5140 5141 ConceptDecl *getTypeConstraintConcept() const { 5142 return TypeConstraintConcept; 5143 } 5144 5145 bool isConstrained() const { 5146 return TypeConstraintConcept != nullptr; 5147 } 5148 5149 bool isDecltypeAuto() const { 5150 return getKeyword() == AutoTypeKeyword::DecltypeAuto; 5151 } 5152 5153 bool isGNUAutoType() const { 5154 return getKeyword() == AutoTypeKeyword::GNUAutoType; 5155 } 5156 5157 AutoTypeKeyword getKeyword() const { 5158 return (AutoTypeKeyword)AutoTypeBits.Keyword; 5159 } 5160 5161 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { 5162 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(), 5163 getTypeConstraintConcept(), getTypeConstraintArguments()); 5164 } 5165 5166 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 5167 QualType Deduced, AutoTypeKeyword Keyword, 5168 bool IsDependent, ConceptDecl *CD, 5169 ArrayRef<TemplateArgument> Arguments); 5170 5171 static bool classof(const Type *T) { 5172 return T->getTypeClass() == Auto; 5173 } 5174 }; 5175 5176 /// Represents a C++17 deduced template specialization type. 5177 class DeducedTemplateSpecializationType : public DeducedType, 5178 public llvm::FoldingSetNode { 5179 friend class ASTContext; // ASTContext creates these 5180 5181 /// The name of the template whose arguments will be deduced. 5182 TemplateName Template; 5183 5184 DeducedTemplateSpecializationType(TemplateName Template, 5185 QualType DeducedAsType, 5186 bool IsDeducedAsDependent) 5187 : DeducedType(DeducedTemplateSpecialization, DeducedAsType, 5188 toTypeDependence(Template.getDependence()) | 5189 (IsDeducedAsDependent 5190 ? TypeDependence::DependentInstantiation 5191 : TypeDependence::None), 5192 DeducedAsType.isNull() ? QualType(this, 0) 5193 : DeducedAsType.getCanonicalType()), 5194 Template(Template) {} 5195 5196 public: 5197 /// Retrieve the name of the template that we are deducing. 5198 TemplateName getTemplateName() const { return Template;} 5199 5200 void Profile(llvm::FoldingSetNodeID &ID) { 5201 Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); 5202 } 5203 5204 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, 5205 QualType Deduced, bool IsDependent) { 5206 Template.Profile(ID); 5207 QualType CanonicalType = 5208 Deduced.isNull() ? Deduced : Deduced.getCanonicalType(); 5209 ID.AddPointer(CanonicalType.getAsOpaquePtr()); 5210 ID.AddBoolean(IsDependent || Template.isDependent()); 5211 } 5212 5213 static bool classof(const Type *T) { 5214 return T->getTypeClass() == DeducedTemplateSpecialization; 5215 } 5216 }; 5217 5218 /// Represents a type template specialization; the template 5219 /// must be a class template, a type alias template, or a template 5220 /// template parameter. A template which cannot be resolved to one of 5221 /// these, e.g. because it is written with a dependent scope 5222 /// specifier, is instead represented as a 5223 /// @c DependentTemplateSpecializationType. 5224 /// 5225 /// A non-dependent template specialization type is always "sugar", 5226 /// typically for a \c RecordType. For example, a class template 5227 /// specialization type of \c vector<int> will refer to a tag type for 5228 /// the instantiation \c std::vector<int, std::allocator<int>> 5229 /// 5230 /// Template specializations are dependent if either the template or 5231 /// any of the template arguments are dependent, in which case the 5232 /// type may also be canonical. 5233 /// 5234 /// Instances of this type are allocated with a trailing array of 5235 /// TemplateArguments, followed by a QualType representing the 5236 /// non-canonical aliased type when the template is a type alias 5237 /// template. 5238 class alignas(8) TemplateSpecializationType 5239 : public Type, 5240 public llvm::FoldingSetNode { 5241 friend class ASTContext; // ASTContext creates these 5242 5243 /// The name of the template being specialized. This is 5244 /// either a TemplateName::Template (in which case it is a 5245 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a 5246 /// TypeAliasTemplateDecl*), a 5247 /// TemplateName::SubstTemplateTemplateParmPack, or a 5248 /// TemplateName::SubstTemplateTemplateParm (in which case the 5249 /// replacement must, recursively, be one of these). 5250 TemplateName Template; 5251 5252 TemplateSpecializationType(TemplateName T, 5253 ArrayRef<TemplateArgument> Args, 5254 QualType Canon, 5255 QualType Aliased); 5256 5257 public: 5258 /// Determine whether any of the given template arguments are dependent. 5259 /// 5260 /// The converted arguments should be supplied when known; whether an 5261 /// argument is dependent can depend on the conversions performed on it 5262 /// (for example, a 'const int' passed as a template argument might be 5263 /// dependent if the parameter is a reference but non-dependent if the 5264 /// parameter is an int). 5265 /// 5266 /// Note that the \p Args parameter is unused: this is intentional, to remind 5267 /// the caller that they need to pass in the converted arguments, not the 5268 /// specified arguments. 5269 static bool 5270 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 5271 ArrayRef<TemplateArgument> Converted); 5272 static bool 5273 anyDependentTemplateArguments(const TemplateArgumentListInfo &, 5274 ArrayRef<TemplateArgument> Converted); 5275 static bool anyInstantiationDependentTemplateArguments( 5276 ArrayRef<TemplateArgumentLoc> Args); 5277 5278 /// True if this template specialization type matches a current 5279 /// instantiation in the context in which it is found. 5280 bool isCurrentInstantiation() const { 5281 return isa<InjectedClassNameType>(getCanonicalTypeInternal()); 5282 } 5283 5284 /// Determine if this template specialization type is for a type alias 5285 /// template that has been substituted. 5286 /// 5287 /// Nearly every template specialization type whose template is an alias 5288 /// template will be substituted. However, this is not the case when 5289 /// the specialization contains a pack expansion but the template alias 5290 /// does not have a corresponding parameter pack, e.g., 5291 /// 5292 /// \code 5293 /// template<typename T, typename U, typename V> struct S; 5294 /// template<typename T, typename U> using A = S<T, int, U>; 5295 /// template<typename... Ts> struct X { 5296 /// typedef A<Ts...> type; // not a type alias 5297 /// }; 5298 /// \endcode 5299 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } 5300 5301 /// Get the aliased type, if this is a specialization of a type alias 5302 /// template. 5303 QualType getAliasedType() const { 5304 assert(isTypeAlias() && "not a type alias template specialization"); 5305 return *reinterpret_cast<const QualType*>(end()); 5306 } 5307 5308 using iterator = const TemplateArgument *; 5309 5310 iterator begin() const { return getArgs(); } 5311 iterator end() const; // defined inline in TemplateBase.h 5312 5313 /// Retrieve the name of the template that we are specializing. 5314 TemplateName getTemplateName() const { return Template; } 5315 5316 /// Retrieve the template arguments. 5317 const TemplateArgument *getArgs() const { 5318 return reinterpret_cast<const TemplateArgument *>(this + 1); 5319 } 5320 5321 /// Retrieve the number of template arguments. 5322 unsigned getNumArgs() const { 5323 return TemplateSpecializationTypeBits.NumArgs; 5324 } 5325 5326 /// Retrieve a specific template argument as a type. 5327 /// \pre \c isArgType(Arg) 5328 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5329 5330 ArrayRef<TemplateArgument> template_arguments() const { 5331 return {getArgs(), getNumArgs()}; 5332 } 5333 5334 bool isSugared() const { 5335 return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); 5336 } 5337 5338 QualType desugar() const { 5339 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); 5340 } 5341 5342 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { 5343 Profile(ID, Template, template_arguments(), Ctx); 5344 if (isTypeAlias()) 5345 getAliasedType().Profile(ID); 5346 } 5347 5348 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, 5349 ArrayRef<TemplateArgument> Args, 5350 const ASTContext &Context); 5351 5352 static bool classof(const Type *T) { 5353 return T->getTypeClass() == TemplateSpecialization; 5354 } 5355 }; 5356 5357 /// Print a template argument list, including the '<' and '>' 5358 /// enclosing the template arguments. 5359 void printTemplateArgumentList(raw_ostream &OS, 5360 ArrayRef<TemplateArgument> Args, 5361 const PrintingPolicy &Policy, 5362 const TemplateParameterList *TPL = nullptr); 5363 5364 void printTemplateArgumentList(raw_ostream &OS, 5365 ArrayRef<TemplateArgumentLoc> Args, 5366 const PrintingPolicy &Policy, 5367 const TemplateParameterList *TPL = nullptr); 5368 5369 void printTemplateArgumentList(raw_ostream &OS, 5370 const TemplateArgumentListInfo &Args, 5371 const PrintingPolicy &Policy, 5372 const TemplateParameterList *TPL = nullptr); 5373 5374 /// The injected class name of a C++ class template or class 5375 /// template partial specialization. Used to record that a type was 5376 /// spelled with a bare identifier rather than as a template-id; the 5377 /// equivalent for non-templated classes is just RecordType. 5378 /// 5379 /// Injected class name types are always dependent. Template 5380 /// instantiation turns these into RecordTypes. 5381 /// 5382 /// Injected class name types are always canonical. This works 5383 /// because it is impossible to compare an injected class name type 5384 /// with the corresponding non-injected template type, for the same 5385 /// reason that it is impossible to directly compare template 5386 /// parameters from different dependent contexts: injected class name 5387 /// types can only occur within the scope of a particular templated 5388 /// declaration, and within that scope every template specialization 5389 /// will canonicalize to the injected class name (when appropriate 5390 /// according to the rules of the language). 5391 class InjectedClassNameType : public Type { 5392 friend class ASTContext; // ASTContext creates these. 5393 friend class ASTNodeImporter; 5394 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not 5395 // currently suitable for AST reading, too much 5396 // interdependencies. 5397 template <class T> friend class serialization::AbstractTypeReader; 5398 5399 CXXRecordDecl *Decl; 5400 5401 /// The template specialization which this type represents. 5402 /// For example, in 5403 /// template <class T> class A { ... }; 5404 /// this is A<T>, whereas in 5405 /// template <class X, class Y> class A<B<X,Y> > { ... }; 5406 /// this is A<B<X,Y> >. 5407 /// 5408 /// It is always unqualified, always a template specialization type, 5409 /// and always dependent. 5410 QualType InjectedType; 5411 5412 InjectedClassNameType(CXXRecordDecl *D, QualType TST) 5413 : Type(InjectedClassName, QualType(), 5414 TypeDependence::DependentInstantiation), 5415 Decl(D), InjectedType(TST) { 5416 assert(isa<TemplateSpecializationType>(TST)); 5417 assert(!TST.hasQualifiers()); 5418 assert(TST->isDependentType()); 5419 } 5420 5421 public: 5422 QualType getInjectedSpecializationType() const { return InjectedType; } 5423 5424 const TemplateSpecializationType *getInjectedTST() const { 5425 return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); 5426 } 5427 5428 TemplateName getTemplateName() const { 5429 return getInjectedTST()->getTemplateName(); 5430 } 5431 5432 CXXRecordDecl *getDecl() const; 5433 5434 bool isSugared() const { return false; } 5435 QualType desugar() const { return QualType(this, 0); } 5436 5437 static bool classof(const Type *T) { 5438 return T->getTypeClass() == InjectedClassName; 5439 } 5440 }; 5441 5442 /// The kind of a tag type. 5443 enum TagTypeKind { 5444 /// The "struct" keyword. 5445 TTK_Struct, 5446 5447 /// The "__interface" keyword. 5448 TTK_Interface, 5449 5450 /// The "union" keyword. 5451 TTK_Union, 5452 5453 /// The "class" keyword. 5454 TTK_Class, 5455 5456 /// The "enum" keyword. 5457 TTK_Enum 5458 }; 5459 5460 /// The elaboration keyword that precedes a qualified type name or 5461 /// introduces an elaborated-type-specifier. 5462 enum ElaboratedTypeKeyword { 5463 /// The "struct" keyword introduces the elaborated-type-specifier. 5464 ETK_Struct, 5465 5466 /// The "__interface" keyword introduces the elaborated-type-specifier. 5467 ETK_Interface, 5468 5469 /// The "union" keyword introduces the elaborated-type-specifier. 5470 ETK_Union, 5471 5472 /// The "class" keyword introduces the elaborated-type-specifier. 5473 ETK_Class, 5474 5475 /// The "enum" keyword introduces the elaborated-type-specifier. 5476 ETK_Enum, 5477 5478 /// The "typename" keyword precedes the qualified type name, e.g., 5479 /// \c typename T::type. 5480 ETK_Typename, 5481 5482 /// No keyword precedes the qualified type name. 5483 ETK_None 5484 }; 5485 5486 /// A helper class for Type nodes having an ElaboratedTypeKeyword. 5487 /// The keyword in stored in the free bits of the base class. 5488 /// Also provides a few static helpers for converting and printing 5489 /// elaborated type keyword and tag type kind enumerations. 5490 class TypeWithKeyword : public Type { 5491 protected: 5492 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, 5493 QualType Canonical, TypeDependence Dependence) 5494 : Type(tc, Canonical, Dependence) { 5495 TypeWithKeywordBits.Keyword = Keyword; 5496 } 5497 5498 public: 5499 ElaboratedTypeKeyword getKeyword() const { 5500 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); 5501 } 5502 5503 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. 5504 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); 5505 5506 /// Converts a type specifier (DeclSpec::TST) into a tag type kind. 5507 /// It is an error to provide a type specifier which *isn't* a tag kind here. 5508 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); 5509 5510 /// Converts a TagTypeKind into an elaborated type keyword. 5511 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); 5512 5513 /// Converts an elaborated type keyword into a TagTypeKind. 5514 /// It is an error to provide an elaborated type keyword 5515 /// which *isn't* a tag kind here. 5516 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); 5517 5518 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); 5519 5520 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); 5521 5522 static StringRef getTagTypeKindName(TagTypeKind Kind) { 5523 return getKeywordName(getKeywordForTagTypeKind(Kind)); 5524 } 5525 5526 class CannotCastToThisType {}; 5527 static CannotCastToThisType classof(const Type *); 5528 }; 5529 5530 /// Represents a type that was referred to using an elaborated type 5531 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, 5532 /// or both. 5533 /// 5534 /// This type is used to keep track of a type name as written in the 5535 /// source code, including tag keywords and any nested-name-specifiers. 5536 /// The type itself is always "sugar", used to express what was written 5537 /// in the source code but containing no additional semantic information. 5538 class ElaboratedType final 5539 : public TypeWithKeyword, 5540 public llvm::FoldingSetNode, 5541 private llvm::TrailingObjects<ElaboratedType, TagDecl *> { 5542 friend class ASTContext; // ASTContext creates these 5543 friend TrailingObjects; 5544 5545 /// The nested name specifier containing the qualifier. 5546 NestedNameSpecifier *NNS; 5547 5548 /// The type that this qualified name refers to. 5549 QualType NamedType; 5550 5551 /// The (re)declaration of this tag type owned by this occurrence is stored 5552 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain 5553 /// it, or obtain a null pointer if there is none. 5554 5555 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 5556 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) 5557 : TypeWithKeyword(Keyword, Elaborated, CanonType, 5558 // Any semantic dependence on the qualifier will have 5559 // been incorporated into NamedType. We still need to 5560 // track syntactic (instantiation / error / pack) 5561 // dependence on the qualifier. 5562 NamedType->getDependence() | 5563 (NNS ? toSyntacticDependence( 5564 toTypeDependence(NNS->getDependence())) 5565 : TypeDependence::None)), 5566 NNS(NNS), NamedType(NamedType) { 5567 ElaboratedTypeBits.HasOwnedTagDecl = false; 5568 if (OwnedTagDecl) { 5569 ElaboratedTypeBits.HasOwnedTagDecl = true; 5570 *getTrailingObjects<TagDecl *>() = OwnedTagDecl; 5571 } 5572 assert(!(Keyword == ETK_None && NNS == nullptr) && 5573 "ElaboratedType cannot have elaborated type keyword " 5574 "and name qualifier both null."); 5575 } 5576 5577 public: 5578 /// Retrieve the qualification on this type. 5579 NestedNameSpecifier *getQualifier() const { return NNS; } 5580 5581 /// Retrieve the type named by the qualified-id. 5582 QualType getNamedType() const { return NamedType; } 5583 5584 /// Remove a single level of sugar. 5585 QualType desugar() const { return getNamedType(); } 5586 5587 /// Returns whether this type directly provides sugar. 5588 bool isSugared() const { return true; } 5589 5590 /// Return the (re)declaration of this type owned by this occurrence of this 5591 /// type, or nullptr if there is none. 5592 TagDecl *getOwnedTagDecl() const { 5593 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() 5594 : nullptr; 5595 } 5596 5597 void Profile(llvm::FoldingSetNodeID &ID) { 5598 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); 5599 } 5600 5601 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, 5602 NestedNameSpecifier *NNS, QualType NamedType, 5603 TagDecl *OwnedTagDecl) { 5604 ID.AddInteger(Keyword); 5605 ID.AddPointer(NNS); 5606 NamedType.Profile(ID); 5607 ID.AddPointer(OwnedTagDecl); 5608 } 5609 5610 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } 5611 }; 5612 5613 /// Represents a qualified type name for which the type name is 5614 /// dependent. 5615 /// 5616 /// DependentNameType represents a class of dependent types that involve a 5617 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a 5618 /// name of a type. The DependentNameType may start with a "typename" (for a 5619 /// typename-specifier), "class", "struct", "union", or "enum" (for a 5620 /// dependent elaborated-type-specifier), or nothing (in contexts where we 5621 /// know that we must be referring to a type, e.g., in a base class specifier). 5622 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility 5623 /// mode, this type is used with non-dependent names to delay name lookup until 5624 /// instantiation. 5625 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { 5626 friend class ASTContext; // ASTContext creates these 5627 5628 /// The nested name specifier containing the qualifier. 5629 NestedNameSpecifier *NNS; 5630 5631 /// The type that this typename specifier refers to. 5632 const IdentifierInfo *Name; 5633 5634 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, 5635 const IdentifierInfo *Name, QualType CanonType) 5636 : TypeWithKeyword(Keyword, DependentName, CanonType, 5637 TypeDependence::DependentInstantiation | 5638 toTypeDependence(NNS->getDependence())), 5639 NNS(NNS), Name(Name) {} 5640 5641 public: 5642 /// Retrieve the qualification on this type. 5643 NestedNameSpecifier *getQualifier() const { return NNS; } 5644 5645 /// Retrieve the type named by the typename specifier as an identifier. 5646 /// 5647 /// This routine will return a non-NULL identifier pointer when the 5648 /// form of the original typename was terminated by an identifier, 5649 /// e.g., "typename T::type". 5650 const IdentifierInfo *getIdentifier() const { 5651 return Name; 5652 } 5653 5654 bool isSugared() const { return false; } 5655 QualType desugar() const { return QualType(this, 0); } 5656 5657 void Profile(llvm::FoldingSetNodeID &ID) { 5658 Profile(ID, getKeyword(), NNS, Name); 5659 } 5660 5661 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, 5662 NestedNameSpecifier *NNS, const IdentifierInfo *Name) { 5663 ID.AddInteger(Keyword); 5664 ID.AddPointer(NNS); 5665 ID.AddPointer(Name); 5666 } 5667 5668 static bool classof(const Type *T) { 5669 return T->getTypeClass() == DependentName; 5670 } 5671 }; 5672 5673 /// Represents a template specialization type whose template cannot be 5674 /// resolved, e.g. 5675 /// A<T>::template B<T> 5676 class alignas(8) DependentTemplateSpecializationType 5677 : public TypeWithKeyword, 5678 public llvm::FoldingSetNode { 5679 friend class ASTContext; // ASTContext creates these 5680 5681 /// The nested name specifier containing the qualifier. 5682 NestedNameSpecifier *NNS; 5683 5684 /// The identifier of the template. 5685 const IdentifierInfo *Name; 5686 5687 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, 5688 NestedNameSpecifier *NNS, 5689 const IdentifierInfo *Name, 5690 ArrayRef<TemplateArgument> Args, 5691 QualType Canon); 5692 5693 const TemplateArgument *getArgBuffer() const { 5694 return reinterpret_cast<const TemplateArgument*>(this+1); 5695 } 5696 5697 TemplateArgument *getArgBuffer() { 5698 return reinterpret_cast<TemplateArgument*>(this+1); 5699 } 5700 5701 public: 5702 NestedNameSpecifier *getQualifier() const { return NNS; } 5703 const IdentifierInfo *getIdentifier() const { return Name; } 5704 5705 /// Retrieve the template arguments. 5706 const TemplateArgument *getArgs() const { 5707 return getArgBuffer(); 5708 } 5709 5710 /// Retrieve the number of template arguments. 5711 unsigned getNumArgs() const { 5712 return DependentTemplateSpecializationTypeBits.NumArgs; 5713 } 5714 5715 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h 5716 5717 ArrayRef<TemplateArgument> template_arguments() const { 5718 return {getArgs(), getNumArgs()}; 5719 } 5720 5721 using iterator = const TemplateArgument *; 5722 5723 iterator begin() const { return getArgs(); } 5724 iterator end() const; // inline in TemplateBase.h 5725 5726 bool isSugared() const { return false; } 5727 QualType desugar() const { return QualType(this, 0); } 5728 5729 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { 5730 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); 5731 } 5732 5733 static void Profile(llvm::FoldingSetNodeID &ID, 5734 const ASTContext &Context, 5735 ElaboratedTypeKeyword Keyword, 5736 NestedNameSpecifier *Qualifier, 5737 const IdentifierInfo *Name, 5738 ArrayRef<TemplateArgument> Args); 5739 5740 static bool classof(const Type *T) { 5741 return T->getTypeClass() == DependentTemplateSpecialization; 5742 } 5743 }; 5744 5745 /// Represents a pack expansion of types. 5746 /// 5747 /// Pack expansions are part of C++11 variadic templates. A pack 5748 /// expansion contains a pattern, which itself contains one or more 5749 /// "unexpanded" parameter packs. When instantiated, a pack expansion 5750 /// produces a series of types, each instantiated from the pattern of 5751 /// the expansion, where the Ith instantiation of the pattern uses the 5752 /// Ith arguments bound to each of the unexpanded parameter packs. The 5753 /// pack expansion is considered to "expand" these unexpanded 5754 /// parameter packs. 5755 /// 5756 /// \code 5757 /// template<typename ...Types> struct tuple; 5758 /// 5759 /// template<typename ...Types> 5760 /// struct tuple_of_references { 5761 /// typedef tuple<Types&...> type; 5762 /// }; 5763 /// \endcode 5764 /// 5765 /// Here, the pack expansion \c Types&... is represented via a 5766 /// PackExpansionType whose pattern is Types&. 5767 class PackExpansionType : public Type, public llvm::FoldingSetNode { 5768 friend class ASTContext; // ASTContext creates these 5769 5770 /// The pattern of the pack expansion. 5771 QualType Pattern; 5772 5773 PackExpansionType(QualType Pattern, QualType Canon, 5774 Optional<unsigned> NumExpansions) 5775 : Type(PackExpansion, Canon, 5776 (Pattern->getDependence() | TypeDependence::Dependent | 5777 TypeDependence::Instantiation) & 5778 ~TypeDependence::UnexpandedPack), 5779 Pattern(Pattern) { 5780 PackExpansionTypeBits.NumExpansions = 5781 NumExpansions ? *NumExpansions + 1 : 0; 5782 } 5783 5784 public: 5785 /// Retrieve the pattern of this pack expansion, which is the 5786 /// type that will be repeatedly instantiated when instantiating the 5787 /// pack expansion itself. 5788 QualType getPattern() const { return Pattern; } 5789 5790 /// Retrieve the number of expansions that this pack expansion will 5791 /// generate, if known. 5792 Optional<unsigned> getNumExpansions() const { 5793 if (PackExpansionTypeBits.NumExpansions) 5794 return PackExpansionTypeBits.NumExpansions - 1; 5795 return None; 5796 } 5797 5798 bool isSugared() const { return false; } 5799 QualType desugar() const { return QualType(this, 0); } 5800 5801 void Profile(llvm::FoldingSetNodeID &ID) { 5802 Profile(ID, getPattern(), getNumExpansions()); 5803 } 5804 5805 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, 5806 Optional<unsigned> NumExpansions) { 5807 ID.AddPointer(Pattern.getAsOpaquePtr()); 5808 ID.AddBoolean(NumExpansions.has_value()); 5809 if (NumExpansions) 5810 ID.AddInteger(*NumExpansions); 5811 } 5812 5813 static bool classof(const Type *T) { 5814 return T->getTypeClass() == PackExpansion; 5815 } 5816 }; 5817 5818 /// This class wraps the list of protocol qualifiers. For types that can 5819 /// take ObjC protocol qualifers, they can subclass this class. 5820 template <class T> 5821 class ObjCProtocolQualifiers { 5822 protected: 5823 ObjCProtocolQualifiers() = default; 5824 5825 ObjCProtocolDecl * const *getProtocolStorage() const { 5826 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); 5827 } 5828 5829 ObjCProtocolDecl **getProtocolStorage() { 5830 return static_cast<T*>(this)->getProtocolStorageImpl(); 5831 } 5832 5833 void setNumProtocols(unsigned N) { 5834 static_cast<T*>(this)->setNumProtocolsImpl(N); 5835 } 5836 5837 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { 5838 setNumProtocols(protocols.size()); 5839 assert(getNumProtocols() == protocols.size() && 5840 "bitfield overflow in protocol count"); 5841 if (!protocols.empty()) 5842 memcpy(getProtocolStorage(), protocols.data(), 5843 protocols.size() * sizeof(ObjCProtocolDecl*)); 5844 } 5845 5846 public: 5847 using qual_iterator = ObjCProtocolDecl * const *; 5848 using qual_range = llvm::iterator_range<qual_iterator>; 5849 5850 qual_range quals() const { return qual_range(qual_begin(), qual_end()); } 5851 qual_iterator qual_begin() const { return getProtocolStorage(); } 5852 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } 5853 5854 bool qual_empty() const { return getNumProtocols() == 0; } 5855 5856 /// Return the number of qualifying protocols in this type, or 0 if 5857 /// there are none. 5858 unsigned getNumProtocols() const { 5859 return static_cast<const T*>(this)->getNumProtocolsImpl(); 5860 } 5861 5862 /// Fetch a protocol by index. 5863 ObjCProtocolDecl *getProtocol(unsigned I) const { 5864 assert(I < getNumProtocols() && "Out-of-range protocol access"); 5865 return qual_begin()[I]; 5866 } 5867 5868 /// Retrieve all of the protocol qualifiers. 5869 ArrayRef<ObjCProtocolDecl *> getProtocols() const { 5870 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); 5871 } 5872 }; 5873 5874 /// Represents a type parameter type in Objective C. It can take 5875 /// a list of protocols. 5876 class ObjCTypeParamType : public Type, 5877 public ObjCProtocolQualifiers<ObjCTypeParamType>, 5878 public llvm::FoldingSetNode { 5879 friend class ASTContext; 5880 friend class ObjCProtocolQualifiers<ObjCTypeParamType>; 5881 5882 /// The number of protocols stored on this type. 5883 unsigned NumProtocols : 6; 5884 5885 ObjCTypeParamDecl *OTPDecl; 5886 5887 /// The protocols are stored after the ObjCTypeParamType node. In the 5888 /// canonical type, the list of protocols are sorted alphabetically 5889 /// and uniqued. 5890 ObjCProtocolDecl **getProtocolStorageImpl(); 5891 5892 /// Return the number of qualifying protocols in this interface type, 5893 /// or 0 if there are none. 5894 unsigned getNumProtocolsImpl() const { 5895 return NumProtocols; 5896 } 5897 5898 void setNumProtocolsImpl(unsigned N) { 5899 NumProtocols = N; 5900 } 5901 5902 ObjCTypeParamType(const ObjCTypeParamDecl *D, 5903 QualType can, 5904 ArrayRef<ObjCProtocolDecl *> protocols); 5905 5906 public: 5907 bool isSugared() const { return true; } 5908 QualType desugar() const { return getCanonicalTypeInternal(); } 5909 5910 static bool classof(const Type *T) { 5911 return T->getTypeClass() == ObjCTypeParam; 5912 } 5913 5914 void Profile(llvm::FoldingSetNodeID &ID); 5915 static void Profile(llvm::FoldingSetNodeID &ID, 5916 const ObjCTypeParamDecl *OTPDecl, 5917 QualType CanonicalType, 5918 ArrayRef<ObjCProtocolDecl *> protocols); 5919 5920 ObjCTypeParamDecl *getDecl() const { return OTPDecl; } 5921 }; 5922 5923 /// Represents a class type in Objective C. 5924 /// 5925 /// Every Objective C type is a combination of a base type, a set of 5926 /// type arguments (optional, for parameterized classes) and a list of 5927 /// protocols. 5928 /// 5929 /// Given the following declarations: 5930 /// \code 5931 /// \@class C<T>; 5932 /// \@protocol P; 5933 /// \endcode 5934 /// 5935 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType 5936 /// with base C and no protocols. 5937 /// 5938 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. 5939 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no 5940 /// protocol list. 5941 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', 5942 /// and protocol list [P]. 5943 /// 5944 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose 5945 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType 5946 /// and no protocols. 5947 /// 5948 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType 5949 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually 5950 /// this should get its own sugar class to better represent the source. 5951 class ObjCObjectType : public Type, 5952 public ObjCProtocolQualifiers<ObjCObjectType> { 5953 friend class ObjCProtocolQualifiers<ObjCObjectType>; 5954 5955 // ObjCObjectType.NumTypeArgs - the number of type arguments stored 5956 // after the ObjCObjectPointerType node. 5957 // ObjCObjectType.NumProtocols - the number of protocols stored 5958 // after the type arguments of ObjCObjectPointerType node. 5959 // 5960 // These protocols are those written directly on the type. If 5961 // protocol qualifiers ever become additive, the iterators will need 5962 // to get kindof complicated. 5963 // 5964 // In the canonical object type, these are sorted alphabetically 5965 // and uniqued. 5966 5967 /// Either a BuiltinType or an InterfaceType or sugar for either. 5968 QualType BaseType; 5969 5970 /// Cached superclass type. 5971 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> 5972 CachedSuperClassType; 5973 5974 QualType *getTypeArgStorage(); 5975 const QualType *getTypeArgStorage() const { 5976 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); 5977 } 5978 5979 ObjCProtocolDecl **getProtocolStorageImpl(); 5980 /// Return the number of qualifying protocols in this interface type, 5981 /// or 0 if there are none. 5982 unsigned getNumProtocolsImpl() const { 5983 return ObjCObjectTypeBits.NumProtocols; 5984 } 5985 void setNumProtocolsImpl(unsigned N) { 5986 ObjCObjectTypeBits.NumProtocols = N; 5987 } 5988 5989 protected: 5990 enum Nonce_ObjCInterface { Nonce_ObjCInterface }; 5991 5992 ObjCObjectType(QualType Canonical, QualType Base, 5993 ArrayRef<QualType> typeArgs, 5994 ArrayRef<ObjCProtocolDecl *> protocols, 5995 bool isKindOf); 5996 5997 ObjCObjectType(enum Nonce_ObjCInterface) 5998 : Type(ObjCInterface, QualType(), TypeDependence::None), 5999 BaseType(QualType(this_(), 0)) { 6000 ObjCObjectTypeBits.NumProtocols = 0; 6001 ObjCObjectTypeBits.NumTypeArgs = 0; 6002 ObjCObjectTypeBits.IsKindOf = 0; 6003 } 6004 6005 void computeSuperClassTypeSlow() const; 6006 6007 public: 6008 /// Gets the base type of this object type. This is always (possibly 6009 /// sugar for) one of: 6010 /// - the 'id' builtin type (as opposed to the 'id' type visible to the 6011 /// user, which is a typedef for an ObjCObjectPointerType) 6012 /// - the 'Class' builtin type (same caveat) 6013 /// - an ObjCObjectType (currently always an ObjCInterfaceType) 6014 QualType getBaseType() const { return BaseType; } 6015 6016 bool isObjCId() const { 6017 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); 6018 } 6019 6020 bool isObjCClass() const { 6021 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); 6022 } 6023 6024 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } 6025 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } 6026 bool isObjCUnqualifiedIdOrClass() const { 6027 if (!qual_empty()) return false; 6028 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) 6029 return T->getKind() == BuiltinType::ObjCId || 6030 T->getKind() == BuiltinType::ObjCClass; 6031 return false; 6032 } 6033 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } 6034 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } 6035 6036 /// Gets the interface declaration for this object type, if the base type 6037 /// really is an interface. 6038 ObjCInterfaceDecl *getInterface() const; 6039 6040 /// Determine whether this object type is "specialized", meaning 6041 /// that it has type arguments. 6042 bool isSpecialized() const; 6043 6044 /// Determine whether this object type was written with type arguments. 6045 bool isSpecializedAsWritten() const { 6046 return ObjCObjectTypeBits.NumTypeArgs > 0; 6047 } 6048 6049 /// Determine whether this object type is "unspecialized", meaning 6050 /// that it has no type arguments. 6051 bool isUnspecialized() const { return !isSpecialized(); } 6052 6053 /// Determine whether this object type is "unspecialized" as 6054 /// written, meaning that it has no type arguments. 6055 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } 6056 6057 /// Retrieve the type arguments of this object type (semantically). 6058 ArrayRef<QualType> getTypeArgs() const; 6059 6060 /// Retrieve the type arguments of this object type as they were 6061 /// written. 6062 ArrayRef<QualType> getTypeArgsAsWritten() const { 6063 return llvm::makeArrayRef(getTypeArgStorage(), 6064 ObjCObjectTypeBits.NumTypeArgs); 6065 } 6066 6067 /// Whether this is a "__kindof" type as written. 6068 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } 6069 6070 /// Whether this ia a "__kindof" type (semantically). 6071 bool isKindOfType() const; 6072 6073 /// Retrieve the type of the superclass of this object type. 6074 /// 6075 /// This operation substitutes any type arguments into the 6076 /// superclass of the current class type, potentially producing a 6077 /// specialization of the superclass type. Produces a null type if 6078 /// there is no superclass. 6079 QualType getSuperClassType() const { 6080 if (!CachedSuperClassType.getInt()) 6081 computeSuperClassTypeSlow(); 6082 6083 assert(CachedSuperClassType.getInt() && "Superclass not set?"); 6084 return QualType(CachedSuperClassType.getPointer(), 0); 6085 } 6086 6087 /// Strip off the Objective-C "kindof" type and (with it) any 6088 /// protocol qualifiers. 6089 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; 6090 6091 bool isSugared() const { return false; } 6092 QualType desugar() const { return QualType(this, 0); } 6093 6094 static bool classof(const Type *T) { 6095 return T->getTypeClass() == ObjCObject || 6096 T->getTypeClass() == ObjCInterface; 6097 } 6098 }; 6099 6100 /// A class providing a concrete implementation 6101 /// of ObjCObjectType, so as to not increase the footprint of 6102 /// ObjCInterfaceType. Code outside of ASTContext and the core type 6103 /// system should not reference this type. 6104 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { 6105 friend class ASTContext; 6106 6107 // If anyone adds fields here, ObjCObjectType::getProtocolStorage() 6108 // will need to be modified. 6109 6110 ObjCObjectTypeImpl(QualType Canonical, QualType Base, 6111 ArrayRef<QualType> typeArgs, 6112 ArrayRef<ObjCProtocolDecl *> protocols, 6113 bool isKindOf) 6114 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} 6115 6116 public: 6117 void Profile(llvm::FoldingSetNodeID &ID); 6118 static void Profile(llvm::FoldingSetNodeID &ID, 6119 QualType Base, 6120 ArrayRef<QualType> typeArgs, 6121 ArrayRef<ObjCProtocolDecl *> protocols, 6122 bool isKindOf); 6123 }; 6124 6125 inline QualType *ObjCObjectType::getTypeArgStorage() { 6126 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); 6127 } 6128 6129 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { 6130 return reinterpret_cast<ObjCProtocolDecl**>( 6131 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); 6132 } 6133 6134 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { 6135 return reinterpret_cast<ObjCProtocolDecl**>( 6136 static_cast<ObjCTypeParamType*>(this)+1); 6137 } 6138 6139 /// Interfaces are the core concept in Objective-C for object oriented design. 6140 /// They basically correspond to C++ classes. There are two kinds of interface 6141 /// types: normal interfaces like `NSString`, and qualified interfaces, which 6142 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. 6143 /// 6144 /// ObjCInterfaceType guarantees the following properties when considered 6145 /// as a subtype of its superclass, ObjCObjectType: 6146 /// - There are no protocol qualifiers. To reinforce this, code which 6147 /// tries to invoke the protocol methods via an ObjCInterfaceType will 6148 /// fail to compile. 6149 /// - It is its own base type. That is, if T is an ObjCInterfaceType*, 6150 /// T->getBaseType() == QualType(T, 0). 6151 class ObjCInterfaceType : public ObjCObjectType { 6152 friend class ASTContext; // ASTContext creates these. 6153 friend class ASTReader; 6154 template <class T> friend class serialization::AbstractTypeReader; 6155 6156 ObjCInterfaceDecl *Decl; 6157 6158 ObjCInterfaceType(const ObjCInterfaceDecl *D) 6159 : ObjCObjectType(Nonce_ObjCInterface), 6160 Decl(const_cast<ObjCInterfaceDecl*>(D)) {} 6161 6162 public: 6163 /// Get the declaration of this interface. 6164 ObjCInterfaceDecl *getDecl() const; 6165 6166 bool isSugared() const { return false; } 6167 QualType desugar() const { return QualType(this, 0); } 6168 6169 static bool classof(const Type *T) { 6170 return T->getTypeClass() == ObjCInterface; 6171 } 6172 6173 // Nonsense to "hide" certain members of ObjCObjectType within this 6174 // class. People asking for protocols on an ObjCInterfaceType are 6175 // not going to get what they want: ObjCInterfaceTypes are 6176 // guaranteed to have no protocols. 6177 enum { 6178 qual_iterator, 6179 qual_begin, 6180 qual_end, 6181 getNumProtocols, 6182 getProtocol 6183 }; 6184 }; 6185 6186 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { 6187 QualType baseType = getBaseType(); 6188 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { 6189 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) 6190 return T->getDecl(); 6191 6192 baseType = ObjT->getBaseType(); 6193 } 6194 6195 return nullptr; 6196 } 6197 6198 /// Represents a pointer to an Objective C object. 6199 /// 6200 /// These are constructed from pointer declarators when the pointee type is 6201 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' 6202 /// types are typedefs for these, and the protocol-qualified types 'id<P>' 6203 /// and 'Class<P>' are translated into these. 6204 /// 6205 /// Pointers to pointers to Objective C objects are still PointerTypes; 6206 /// only the first level of pointer gets it own type implementation. 6207 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { 6208 friend class ASTContext; // ASTContext creates these. 6209 6210 QualType PointeeType; 6211 6212 ObjCObjectPointerType(QualType Canonical, QualType Pointee) 6213 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()), 6214 PointeeType(Pointee) {} 6215 6216 public: 6217 /// Gets the type pointed to by this ObjC pointer. 6218 /// The result will always be an ObjCObjectType or sugar thereof. 6219 QualType getPointeeType() const { return PointeeType; } 6220 6221 /// Gets the type pointed to by this ObjC pointer. Always returns non-null. 6222 /// 6223 /// This method is equivalent to getPointeeType() except that 6224 /// it discards any typedefs (or other sugar) between this 6225 /// type and the "outermost" object type. So for: 6226 /// \code 6227 /// \@class A; \@protocol P; \@protocol Q; 6228 /// typedef A<P> AP; 6229 /// typedef A A1; 6230 /// typedef A1<P> A1P; 6231 /// typedef A1P<Q> A1PQ; 6232 /// \endcode 6233 /// For 'A*', getObjectType() will return 'A'. 6234 /// For 'A<P>*', getObjectType() will return 'A<P>'. 6235 /// For 'AP*', getObjectType() will return 'A<P>'. 6236 /// For 'A1*', getObjectType() will return 'A'. 6237 /// For 'A1<P>*', getObjectType() will return 'A1<P>'. 6238 /// For 'A1P*', getObjectType() will return 'A1<P>'. 6239 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because 6240 /// adding protocols to a protocol-qualified base discards the 6241 /// old qualifiers (for now). But if it didn't, getObjectType() 6242 /// would return 'A1P<Q>' (and we'd have to make iterating over 6243 /// qualifiers more complicated). 6244 const ObjCObjectType *getObjectType() const { 6245 return PointeeType->castAs<ObjCObjectType>(); 6246 } 6247 6248 /// If this pointer points to an Objective C 6249 /// \@interface type, gets the type for that interface. Any protocol 6250 /// qualifiers on the interface are ignored. 6251 /// 6252 /// \return null if the base type for this pointer is 'id' or 'Class' 6253 const ObjCInterfaceType *getInterfaceType() const; 6254 6255 /// If this pointer points to an Objective \@interface 6256 /// type, gets the declaration for that interface. 6257 /// 6258 /// \return null if the base type for this pointer is 'id' or 'Class' 6259 ObjCInterfaceDecl *getInterfaceDecl() const { 6260 return getObjectType()->getInterface(); 6261 } 6262 6263 /// True if this is equivalent to the 'id' type, i.e. if 6264 /// its object type is the primitive 'id' type with no protocols. 6265 bool isObjCIdType() const { 6266 return getObjectType()->isObjCUnqualifiedId(); 6267 } 6268 6269 /// True if this is equivalent to the 'Class' type, 6270 /// i.e. if its object tive is the primitive 'Class' type with no protocols. 6271 bool isObjCClassType() const { 6272 return getObjectType()->isObjCUnqualifiedClass(); 6273 } 6274 6275 /// True if this is equivalent to the 'id' or 'Class' type, 6276 bool isObjCIdOrClassType() const { 6277 return getObjectType()->isObjCUnqualifiedIdOrClass(); 6278 } 6279 6280 /// True if this is equivalent to 'id<P>' for some non-empty set of 6281 /// protocols. 6282 bool isObjCQualifiedIdType() const { 6283 return getObjectType()->isObjCQualifiedId(); 6284 } 6285 6286 /// True if this is equivalent to 'Class<P>' for some non-empty set of 6287 /// protocols. 6288 bool isObjCQualifiedClassType() const { 6289 return getObjectType()->isObjCQualifiedClass(); 6290 } 6291 6292 /// Whether this is a "__kindof" type. 6293 bool isKindOfType() const { return getObjectType()->isKindOfType(); } 6294 6295 /// Whether this type is specialized, meaning that it has type arguments. 6296 bool isSpecialized() const { return getObjectType()->isSpecialized(); } 6297 6298 /// Whether this type is specialized, meaning that it has type arguments. 6299 bool isSpecializedAsWritten() const { 6300 return getObjectType()->isSpecializedAsWritten(); 6301 } 6302 6303 /// Whether this type is unspecialized, meaning that is has no type arguments. 6304 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } 6305 6306 /// Determine whether this object type is "unspecialized" as 6307 /// written, meaning that it has no type arguments. 6308 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } 6309 6310 /// Retrieve the type arguments for this type. 6311 ArrayRef<QualType> getTypeArgs() const { 6312 return getObjectType()->getTypeArgs(); 6313 } 6314 6315 /// Retrieve the type arguments for this type. 6316 ArrayRef<QualType> getTypeArgsAsWritten() const { 6317 return getObjectType()->getTypeArgsAsWritten(); 6318 } 6319 6320 /// An iterator over the qualifiers on the object type. Provided 6321 /// for convenience. This will always iterate over the full set of 6322 /// protocols on a type, not just those provided directly. 6323 using qual_iterator = ObjCObjectType::qual_iterator; 6324 using qual_range = llvm::iterator_range<qual_iterator>; 6325 6326 qual_range quals() const { return qual_range(qual_begin(), qual_end()); } 6327 6328 qual_iterator qual_begin() const { 6329 return getObjectType()->qual_begin(); 6330 } 6331 6332 qual_iterator qual_end() const { 6333 return getObjectType()->qual_end(); 6334 } 6335 6336 bool qual_empty() const { return getObjectType()->qual_empty(); } 6337 6338 /// Return the number of qualifying protocols on the object type. 6339 unsigned getNumProtocols() const { 6340 return getObjectType()->getNumProtocols(); 6341 } 6342 6343 /// Retrieve a qualifying protocol by index on the object type. 6344 ObjCProtocolDecl *getProtocol(unsigned I) const { 6345 return getObjectType()->getProtocol(I); 6346 } 6347 6348 bool isSugared() const { return false; } 6349 QualType desugar() const { return QualType(this, 0); } 6350 6351 /// Retrieve the type of the superclass of this object pointer type. 6352 /// 6353 /// This operation substitutes any type arguments into the 6354 /// superclass of the current class type, potentially producing a 6355 /// pointer to a specialization of the superclass type. Produces a 6356 /// null type if there is no superclass. 6357 QualType getSuperClassType() const; 6358 6359 /// Strip off the Objective-C "kindof" type and (with it) any 6360 /// protocol qualifiers. 6361 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( 6362 const ASTContext &ctx) const; 6363 6364 void Profile(llvm::FoldingSetNodeID &ID) { 6365 Profile(ID, getPointeeType()); 6366 } 6367 6368 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { 6369 ID.AddPointer(T.getAsOpaquePtr()); 6370 } 6371 6372 static bool classof(const Type *T) { 6373 return T->getTypeClass() == ObjCObjectPointer; 6374 } 6375 }; 6376 6377 class AtomicType : public Type, public llvm::FoldingSetNode { 6378 friend class ASTContext; // ASTContext creates these. 6379 6380 QualType ValueType; 6381 6382 AtomicType(QualType ValTy, QualType Canonical) 6383 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {} 6384 6385 public: 6386 /// Gets the type contained by this atomic type, i.e. 6387 /// the type returned by performing an atomic load of this atomic type. 6388 QualType getValueType() const { return ValueType; } 6389 6390 bool isSugared() const { return false; } 6391 QualType desugar() const { return QualType(this, 0); } 6392 6393 void Profile(llvm::FoldingSetNodeID &ID) { 6394 Profile(ID, getValueType()); 6395 } 6396 6397 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { 6398 ID.AddPointer(T.getAsOpaquePtr()); 6399 } 6400 6401 static bool classof(const Type *T) { 6402 return T->getTypeClass() == Atomic; 6403 } 6404 }; 6405 6406 /// PipeType - OpenCL20. 6407 class PipeType : public Type, public llvm::FoldingSetNode { 6408 friend class ASTContext; // ASTContext creates these. 6409 6410 QualType ElementType; 6411 bool isRead; 6412 6413 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) 6414 : Type(Pipe, CanonicalPtr, elemType->getDependence()), 6415 ElementType(elemType), isRead(isRead) {} 6416 6417 public: 6418 QualType getElementType() const { return ElementType; } 6419 6420 bool isSugared() const { return false; } 6421 6422 QualType desugar() const { return QualType(this, 0); } 6423 6424 void Profile(llvm::FoldingSetNodeID &ID) { 6425 Profile(ID, getElementType(), isReadOnly()); 6426 } 6427 6428 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { 6429 ID.AddPointer(T.getAsOpaquePtr()); 6430 ID.AddBoolean(isRead); 6431 } 6432 6433 static bool classof(const Type *T) { 6434 return T->getTypeClass() == Pipe; 6435 } 6436 6437 bool isReadOnly() const { return isRead; } 6438 }; 6439 6440 /// A fixed int type of a specified bitwidth. 6441 class BitIntType final : public Type, public llvm::FoldingSetNode { 6442 friend class ASTContext; 6443 unsigned IsUnsigned : 1; 6444 unsigned NumBits : 24; 6445 6446 protected: 6447 BitIntType(bool isUnsigned, unsigned NumBits); 6448 6449 public: 6450 bool isUnsigned() const { return IsUnsigned; } 6451 bool isSigned() const { return !IsUnsigned; } 6452 unsigned getNumBits() const { return NumBits; } 6453 6454 bool isSugared() const { return false; } 6455 QualType desugar() const { return QualType(this, 0); } 6456 6457 void Profile(llvm::FoldingSetNodeID &ID) { 6458 Profile(ID, isUnsigned(), getNumBits()); 6459 } 6460 6461 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned, 6462 unsigned NumBits) { 6463 ID.AddBoolean(IsUnsigned); 6464 ID.AddInteger(NumBits); 6465 } 6466 6467 static bool classof(const Type *T) { return T->getTypeClass() == BitInt; } 6468 }; 6469 6470 class DependentBitIntType final : public Type, public llvm::FoldingSetNode { 6471 friend class ASTContext; 6472 const ASTContext &Context; 6473 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned; 6474 6475 protected: 6476 DependentBitIntType(const ASTContext &Context, bool IsUnsigned, 6477 Expr *NumBits); 6478 6479 public: 6480 bool isUnsigned() const; 6481 bool isSigned() const { return !isUnsigned(); } 6482 Expr *getNumBitsExpr() const; 6483 6484 bool isSugared() const { return false; } 6485 QualType desugar() const { return QualType(this, 0); } 6486 6487 void Profile(llvm::FoldingSetNodeID &ID) { 6488 Profile(ID, Context, isUnsigned(), getNumBitsExpr()); 6489 } 6490 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, 6491 bool IsUnsigned, Expr *NumBitsExpr); 6492 6493 static bool classof(const Type *T) { 6494 return T->getTypeClass() == DependentBitInt; 6495 } 6496 }; 6497 6498 /// A qualifier set is used to build a set of qualifiers. 6499 class QualifierCollector : public Qualifiers { 6500 public: 6501 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} 6502 6503 /// Collect any qualifiers on the given type and return an 6504 /// unqualified type. The qualifiers are assumed to be consistent 6505 /// with those already in the type. 6506 const Type *strip(QualType type) { 6507 addFastQualifiers(type.getLocalFastQualifiers()); 6508 if (!type.hasLocalNonFastQualifiers()) 6509 return type.getTypePtrUnsafe(); 6510 6511 const ExtQuals *extQuals = type.getExtQualsUnsafe(); 6512 addConsistentQualifiers(extQuals->getQualifiers()); 6513 return extQuals->getBaseType(); 6514 } 6515 6516 /// Apply the collected qualifiers to the given type. 6517 QualType apply(const ASTContext &Context, QualType QT) const; 6518 6519 /// Apply the collected qualifiers to the given type. 6520 QualType apply(const ASTContext &Context, const Type* T) const; 6521 }; 6522 6523 /// A container of type source information. 6524 /// 6525 /// A client can read the relevant info using TypeLoc wrappers, e.g: 6526 /// @code 6527 /// TypeLoc TL = TypeSourceInfo->getTypeLoc(); 6528 /// TL.getBeginLoc().print(OS, SrcMgr); 6529 /// @endcode 6530 class alignas(8) TypeSourceInfo { 6531 // Contains a memory block after the class, used for type source information, 6532 // allocated by ASTContext. 6533 friend class ASTContext; 6534 6535 QualType Ty; 6536 6537 TypeSourceInfo(QualType ty) : Ty(ty) {} 6538 6539 public: 6540 /// Return the type wrapped by this type source info. 6541 QualType getType() const { return Ty; } 6542 6543 /// Return the TypeLoc wrapper for the type source info. 6544 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h 6545 6546 /// Override the type stored in this TypeSourceInfo. Use with caution! 6547 void overrideType(QualType T) { Ty = T; } 6548 }; 6549 6550 // Inline function definitions. 6551 6552 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { 6553 SplitQualType desugar = 6554 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); 6555 desugar.Quals.addConsistentQualifiers(Quals); 6556 return desugar; 6557 } 6558 6559 inline const Type *QualType::getTypePtr() const { 6560 return getCommonPtr()->BaseType; 6561 } 6562 6563 inline const Type *QualType::getTypePtrOrNull() const { 6564 return (isNull() ? nullptr : getCommonPtr()->BaseType); 6565 } 6566 6567 inline SplitQualType QualType::split() const { 6568 if (!hasLocalNonFastQualifiers()) 6569 return SplitQualType(getTypePtrUnsafe(), 6570 Qualifiers::fromFastMask(getLocalFastQualifiers())); 6571 6572 const ExtQuals *eq = getExtQualsUnsafe(); 6573 Qualifiers qs = eq->getQualifiers(); 6574 qs.addFastQualifiers(getLocalFastQualifiers()); 6575 return SplitQualType(eq->getBaseType(), qs); 6576 } 6577 6578 inline Qualifiers QualType::getLocalQualifiers() const { 6579 Qualifiers Quals; 6580 if (hasLocalNonFastQualifiers()) 6581 Quals = getExtQualsUnsafe()->getQualifiers(); 6582 Quals.addFastQualifiers(getLocalFastQualifiers()); 6583 return Quals; 6584 } 6585 6586 inline Qualifiers QualType::getQualifiers() const { 6587 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); 6588 quals.addFastQualifiers(getLocalFastQualifiers()); 6589 return quals; 6590 } 6591 6592 inline unsigned QualType::getCVRQualifiers() const { 6593 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); 6594 cvr |= getLocalCVRQualifiers(); 6595 return cvr; 6596 } 6597 6598 inline QualType QualType::getCanonicalType() const { 6599 QualType canon = getCommonPtr()->CanonicalType; 6600 return canon.withFastQualifiers(getLocalFastQualifiers()); 6601 } 6602 6603 inline bool QualType::isCanonical() const { 6604 return getTypePtr()->isCanonicalUnqualified(); 6605 } 6606 6607 inline bool QualType::isCanonicalAsParam() const { 6608 if (!isCanonical()) return false; 6609 if (hasLocalQualifiers()) return false; 6610 6611 const Type *T = getTypePtr(); 6612 if (T->isVariablyModifiedType() && T->hasSizedVLAType()) 6613 return false; 6614 6615 return !isa<FunctionType>(T) && !isa<ArrayType>(T); 6616 } 6617 6618 inline bool QualType::isConstQualified() const { 6619 return isLocalConstQualified() || 6620 getCommonPtr()->CanonicalType.isLocalConstQualified(); 6621 } 6622 6623 inline bool QualType::isRestrictQualified() const { 6624 return isLocalRestrictQualified() || 6625 getCommonPtr()->CanonicalType.isLocalRestrictQualified(); 6626 } 6627 6628 6629 inline bool QualType::isVolatileQualified() const { 6630 return isLocalVolatileQualified() || 6631 getCommonPtr()->CanonicalType.isLocalVolatileQualified(); 6632 } 6633 6634 inline bool QualType::hasQualifiers() const { 6635 return hasLocalQualifiers() || 6636 getCommonPtr()->CanonicalType.hasLocalQualifiers(); 6637 } 6638 6639 inline QualType QualType::getUnqualifiedType() const { 6640 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) 6641 return QualType(getTypePtr(), 0); 6642 6643 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); 6644 } 6645 6646 inline SplitQualType QualType::getSplitUnqualifiedType() const { 6647 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) 6648 return split(); 6649 6650 return getSplitUnqualifiedTypeImpl(*this); 6651 } 6652 6653 inline void QualType::removeLocalConst() { 6654 removeLocalFastQualifiers(Qualifiers::Const); 6655 } 6656 6657 inline void QualType::removeLocalRestrict() { 6658 removeLocalFastQualifiers(Qualifiers::Restrict); 6659 } 6660 6661 inline void QualType::removeLocalVolatile() { 6662 removeLocalFastQualifiers(Qualifiers::Volatile); 6663 } 6664 6665 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { 6666 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"); 6667 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, 6668 "Fast bits differ from CVR bits!"); 6669 6670 // Fast path: we don't need to touch the slow qualifiers. 6671 removeLocalFastQualifiers(Mask); 6672 } 6673 6674 /// Check if this type has any address space qualifier. 6675 inline bool QualType::hasAddressSpace() const { 6676 return getQualifiers().hasAddressSpace(); 6677 } 6678 6679 /// Return the address space of this type. 6680 inline LangAS QualType::getAddressSpace() const { 6681 return getQualifiers().getAddressSpace(); 6682 } 6683 6684 /// Return the gc attribute of this type. 6685 inline Qualifiers::GC QualType::getObjCGCAttr() const { 6686 return getQualifiers().getObjCGCAttr(); 6687 } 6688 6689 inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { 6690 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6691 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); 6692 return false; 6693 } 6694 6695 inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { 6696 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6697 return hasNonTrivialToPrimitiveDestructCUnion(RD); 6698 return false; 6699 } 6700 6701 inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { 6702 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) 6703 return hasNonTrivialToPrimitiveCopyCUnion(RD); 6704 return false; 6705 } 6706 6707 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { 6708 if (const auto *PT = t.getAs<PointerType>()) { 6709 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) 6710 return FT->getExtInfo(); 6711 } else if (const auto *FT = t.getAs<FunctionType>()) 6712 return FT->getExtInfo(); 6713 6714 return FunctionType::ExtInfo(); 6715 } 6716 6717 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { 6718 return getFunctionExtInfo(*t); 6719 } 6720 6721 /// Determine whether this type is more 6722 /// qualified than the Other type. For example, "const volatile int" 6723 /// is more qualified than "const int", "volatile int", and 6724 /// "int". However, it is not more qualified than "const volatile 6725 /// int". 6726 inline bool QualType::isMoreQualifiedThan(QualType other) const { 6727 Qualifiers MyQuals = getQualifiers(); 6728 Qualifiers OtherQuals = other.getQualifiers(); 6729 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); 6730 } 6731 6732 /// Determine whether this type is at last 6733 /// as qualified as the Other type. For example, "const volatile 6734 /// int" is at least as qualified as "const int", "volatile int", 6735 /// "int", and "const volatile int". 6736 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { 6737 Qualifiers OtherQuals = other.getQualifiers(); 6738 6739 // Ignore __unaligned qualifier if this type is a void. 6740 if (getUnqualifiedType()->isVoidType()) 6741 OtherQuals.removeUnaligned(); 6742 6743 return getQualifiers().compatiblyIncludes(OtherQuals); 6744 } 6745 6746 /// If Type is a reference type (e.g., const 6747 /// int&), returns the type that the reference refers to ("const 6748 /// int"). Otherwise, returns the type itself. This routine is used 6749 /// throughout Sema to implement C++ 5p6: 6750 /// 6751 /// If an expression initially has the type "reference to T" (8.3.2, 6752 /// 8.5.3), the type is adjusted to "T" prior to any further 6753 /// analysis, the expression designates the object or function 6754 /// denoted by the reference, and the expression is an lvalue. 6755 inline QualType QualType::getNonReferenceType() const { 6756 if (const auto *RefType = (*this)->getAs<ReferenceType>()) 6757 return RefType->getPointeeType(); 6758 else 6759 return *this; 6760 } 6761 6762 inline bool QualType::isCForbiddenLValueType() const { 6763 return ((getTypePtr()->isVoidType() && !hasQualifiers()) || 6764 getTypePtr()->isFunctionType()); 6765 } 6766 6767 /// Tests whether the type is categorized as a fundamental type. 6768 /// 6769 /// \returns True for types specified in C++0x [basic.fundamental]. 6770 inline bool Type::isFundamentalType() const { 6771 return isVoidType() || 6772 isNullPtrType() || 6773 // FIXME: It's really annoying that we don't have an 6774 // 'isArithmeticType()' which agrees with the standard definition. 6775 (isArithmeticType() && !isEnumeralType()); 6776 } 6777 6778 /// Tests whether the type is categorized as a compound type. 6779 /// 6780 /// \returns True for types specified in C++0x [basic.compound]. 6781 inline bool Type::isCompoundType() const { 6782 // C++0x [basic.compound]p1: 6783 // Compound types can be constructed in the following ways: 6784 // -- arrays of objects of a given type [...]; 6785 return isArrayType() || 6786 // -- functions, which have parameters of given types [...]; 6787 isFunctionType() || 6788 // -- pointers to void or objects or functions [...]; 6789 isPointerType() || 6790 // -- references to objects or functions of a given type. [...] 6791 isReferenceType() || 6792 // -- classes containing a sequence of objects of various types, [...]; 6793 isRecordType() || 6794 // -- unions, which are classes capable of containing objects of different 6795 // types at different times; 6796 isUnionType() || 6797 // -- enumerations, which comprise a set of named constant values. [...]; 6798 isEnumeralType() || 6799 // -- pointers to non-static class members, [...]. 6800 isMemberPointerType(); 6801 } 6802 6803 inline bool Type::isFunctionType() const { 6804 return isa<FunctionType>(CanonicalType); 6805 } 6806 6807 inline bool Type::isPointerType() const { 6808 return isa<PointerType>(CanonicalType); 6809 } 6810 6811 inline bool Type::isAnyPointerType() const { 6812 return isPointerType() || isObjCObjectPointerType(); 6813 } 6814 6815 inline bool Type::isBlockPointerType() const { 6816 return isa<BlockPointerType>(CanonicalType); 6817 } 6818 6819 inline bool Type::isReferenceType() const { 6820 return isa<ReferenceType>(CanonicalType); 6821 } 6822 6823 inline bool Type::isLValueReferenceType() const { 6824 return isa<LValueReferenceType>(CanonicalType); 6825 } 6826 6827 inline bool Type::isRValueReferenceType() const { 6828 return isa<RValueReferenceType>(CanonicalType); 6829 } 6830 6831 inline bool Type::isObjectPointerType() const { 6832 // Note: an "object pointer type" is not the same thing as a pointer to an 6833 // object type; rather, it is a pointer to an object type or a pointer to cv 6834 // void. 6835 if (const auto *T = getAs<PointerType>()) 6836 return !T->getPointeeType()->isFunctionType(); 6837 else 6838 return false; 6839 } 6840 6841 inline bool Type::isFunctionPointerType() const { 6842 if (const auto *T = getAs<PointerType>()) 6843 return T->getPointeeType()->isFunctionType(); 6844 else 6845 return false; 6846 } 6847 6848 inline bool Type::isFunctionReferenceType() const { 6849 if (const auto *T = getAs<ReferenceType>()) 6850 return T->getPointeeType()->isFunctionType(); 6851 else 6852 return false; 6853 } 6854 6855 inline bool Type::isMemberPointerType() const { 6856 return isa<MemberPointerType>(CanonicalType); 6857 } 6858 6859 inline bool Type::isMemberFunctionPointerType() const { 6860 if (const auto *T = getAs<MemberPointerType>()) 6861 return T->isMemberFunctionPointer(); 6862 else 6863 return false; 6864 } 6865 6866 inline bool Type::isMemberDataPointerType() const { 6867 if (const auto *T = getAs<MemberPointerType>()) 6868 return T->isMemberDataPointer(); 6869 else 6870 return false; 6871 } 6872 6873 inline bool Type::isArrayType() const { 6874 return isa<ArrayType>(CanonicalType); 6875 } 6876 6877 inline bool Type::isConstantArrayType() const { 6878 return isa<ConstantArrayType>(CanonicalType); 6879 } 6880 6881 inline bool Type::isIncompleteArrayType() const { 6882 return isa<IncompleteArrayType>(CanonicalType); 6883 } 6884 6885 inline bool Type::isVariableArrayType() const { 6886 return isa<VariableArrayType>(CanonicalType); 6887 } 6888 6889 inline bool Type::isDependentSizedArrayType() const { 6890 return isa<DependentSizedArrayType>(CanonicalType); 6891 } 6892 6893 inline bool Type::isBuiltinType() const { 6894 return isa<BuiltinType>(CanonicalType); 6895 } 6896 6897 inline bool Type::isRecordType() const { 6898 return isa<RecordType>(CanonicalType); 6899 } 6900 6901 inline bool Type::isEnumeralType() const { 6902 return isa<EnumType>(CanonicalType); 6903 } 6904 6905 inline bool Type::isAnyComplexType() const { 6906 return isa<ComplexType>(CanonicalType); 6907 } 6908 6909 inline bool Type::isVectorType() const { 6910 return isa<VectorType>(CanonicalType); 6911 } 6912 6913 inline bool Type::isExtVectorType() const { 6914 return isa<ExtVectorType>(CanonicalType); 6915 } 6916 6917 inline bool Type::isExtVectorBoolType() const { 6918 if (!isExtVectorType()) 6919 return false; 6920 return cast<ExtVectorType>(CanonicalType)->getElementType()->isBooleanType(); 6921 } 6922 6923 inline bool Type::isMatrixType() const { 6924 return isa<MatrixType>(CanonicalType); 6925 } 6926 6927 inline bool Type::isConstantMatrixType() const { 6928 return isa<ConstantMatrixType>(CanonicalType); 6929 } 6930 6931 inline bool Type::isDependentAddressSpaceType() const { 6932 return isa<DependentAddressSpaceType>(CanonicalType); 6933 } 6934 6935 inline bool Type::isObjCObjectPointerType() const { 6936 return isa<ObjCObjectPointerType>(CanonicalType); 6937 } 6938 6939 inline bool Type::isObjCObjectType() const { 6940 return isa<ObjCObjectType>(CanonicalType); 6941 } 6942 6943 inline bool Type::isObjCObjectOrInterfaceType() const { 6944 return isa<ObjCInterfaceType>(CanonicalType) || 6945 isa<ObjCObjectType>(CanonicalType); 6946 } 6947 6948 inline bool Type::isAtomicType() const { 6949 return isa<AtomicType>(CanonicalType); 6950 } 6951 6952 inline bool Type::isUndeducedAutoType() const { 6953 return isa<AutoType>(CanonicalType); 6954 } 6955 6956 inline bool Type::isObjCQualifiedIdType() const { 6957 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6958 return OPT->isObjCQualifiedIdType(); 6959 return false; 6960 } 6961 6962 inline bool Type::isObjCQualifiedClassType() const { 6963 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6964 return OPT->isObjCQualifiedClassType(); 6965 return false; 6966 } 6967 6968 inline bool Type::isObjCIdType() const { 6969 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6970 return OPT->isObjCIdType(); 6971 return false; 6972 } 6973 6974 inline bool Type::isObjCClassType() const { 6975 if (const auto *OPT = getAs<ObjCObjectPointerType>()) 6976 return OPT->isObjCClassType(); 6977 return false; 6978 } 6979 6980 inline bool Type::isObjCSelType() const { 6981 if (const auto *OPT = getAs<PointerType>()) 6982 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); 6983 return false; 6984 } 6985 6986 inline bool Type::isObjCBuiltinType() const { 6987 return isObjCIdType() || isObjCClassType() || isObjCSelType(); 6988 } 6989 6990 inline bool Type::isDecltypeType() const { 6991 return isa<DecltypeType>(this); 6992 } 6993 6994 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6995 inline bool Type::is##Id##Type() const { \ 6996 return isSpecificBuiltinType(BuiltinType::Id); \ 6997 } 6998 #include "clang/Basic/OpenCLImageTypes.def" 6999 7000 inline bool Type::isSamplerT() const { 7001 return isSpecificBuiltinType(BuiltinType::OCLSampler); 7002 } 7003 7004 inline bool Type::isEventT() const { 7005 return isSpecificBuiltinType(BuiltinType::OCLEvent); 7006 } 7007 7008 inline bool Type::isClkEventT() const { 7009 return isSpecificBuiltinType(BuiltinType::OCLClkEvent); 7010 } 7011 7012 inline bool Type::isQueueT() const { 7013 return isSpecificBuiltinType(BuiltinType::OCLQueue); 7014 } 7015 7016 inline bool Type::isReserveIDT() const { 7017 return isSpecificBuiltinType(BuiltinType::OCLReserveID); 7018 } 7019 7020 inline bool Type::isImageType() const { 7021 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || 7022 return 7023 #include "clang/Basic/OpenCLImageTypes.def" 7024 false; // end boolean or operation 7025 } 7026 7027 inline bool Type::isPipeType() const { 7028 return isa<PipeType>(CanonicalType); 7029 } 7030 7031 inline bool Type::isBitIntType() const { 7032 return isa<BitIntType>(CanonicalType); 7033 } 7034 7035 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 7036 inline bool Type::is##Id##Type() const { \ 7037 return isSpecificBuiltinType(BuiltinType::Id); \ 7038 } 7039 #include "clang/Basic/OpenCLExtensionTypes.def" 7040 7041 inline bool Type::isOCLIntelSubgroupAVCType() const { 7042 #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ 7043 isOCLIntelSubgroupAVC##Id##Type() || 7044 return 7045 #include "clang/Basic/OpenCLExtensionTypes.def" 7046 false; // end of boolean or operation 7047 } 7048 7049 inline bool Type::isOCLExtOpaqueType() const { 7050 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || 7051 return 7052 #include "clang/Basic/OpenCLExtensionTypes.def" 7053 false; // end of boolean or operation 7054 } 7055 7056 inline bool Type::isOpenCLSpecificType() const { 7057 return isSamplerT() || isEventT() || isImageType() || isClkEventT() || 7058 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); 7059 } 7060 7061 inline bool Type::isTemplateTypeParmType() const { 7062 return isa<TemplateTypeParmType>(CanonicalType); 7063 } 7064 7065 inline bool Type::isSpecificBuiltinType(unsigned K) const { 7066 if (const BuiltinType *BT = getAs<BuiltinType>()) { 7067 return BT->getKind() == static_cast<BuiltinType::Kind>(K); 7068 } 7069 return false; 7070 } 7071 7072 inline bool Type::isPlaceholderType() const { 7073 if (const auto *BT = dyn_cast<BuiltinType>(this)) 7074 return BT->isPlaceholderType(); 7075 return false; 7076 } 7077 7078 inline const BuiltinType *Type::getAsPlaceholderType() const { 7079 if (const auto *BT = dyn_cast<BuiltinType>(this)) 7080 if (BT->isPlaceholderType()) 7081 return BT; 7082 return nullptr; 7083 } 7084 7085 inline bool Type::isSpecificPlaceholderType(unsigned K) const { 7086 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)); 7087 return isSpecificBuiltinType(K); 7088 } 7089 7090 inline bool Type::isNonOverloadPlaceholderType() const { 7091 if (const auto *BT = dyn_cast<BuiltinType>(this)) 7092 return BT->isNonOverloadPlaceholderType(); 7093 return false; 7094 } 7095 7096 inline bool Type::isVoidType() const { 7097 return isSpecificBuiltinType(BuiltinType::Void); 7098 } 7099 7100 inline bool Type::isHalfType() const { 7101 // FIXME: Should we allow complex __fp16? Probably not. 7102 return isSpecificBuiltinType(BuiltinType::Half); 7103 } 7104 7105 inline bool Type::isFloat16Type() const { 7106 return isSpecificBuiltinType(BuiltinType::Float16); 7107 } 7108 7109 inline bool Type::isBFloat16Type() const { 7110 return isSpecificBuiltinType(BuiltinType::BFloat16); 7111 } 7112 7113 inline bool Type::isFloat128Type() const { 7114 return isSpecificBuiltinType(BuiltinType::Float128); 7115 } 7116 7117 inline bool Type::isIbm128Type() const { 7118 return isSpecificBuiltinType(BuiltinType::Ibm128); 7119 } 7120 7121 inline bool Type::isNullPtrType() const { 7122 return isSpecificBuiltinType(BuiltinType::NullPtr); 7123 } 7124 7125 bool IsEnumDeclComplete(EnumDecl *); 7126 bool IsEnumDeclScoped(EnumDecl *); 7127 7128 inline bool Type::isIntegerType() const { 7129 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7130 return BT->getKind() >= BuiltinType::Bool && 7131 BT->getKind() <= BuiltinType::Int128; 7132 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { 7133 // Incomplete enum types are not treated as integer types. 7134 // FIXME: In C++, enum types are never integer types. 7135 return IsEnumDeclComplete(ET->getDecl()) && 7136 !IsEnumDeclScoped(ET->getDecl()); 7137 } 7138 return isBitIntType(); 7139 } 7140 7141 inline bool Type::isFixedPointType() const { 7142 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 7143 return BT->getKind() >= BuiltinType::ShortAccum && 7144 BT->getKind() <= BuiltinType::SatULongFract; 7145 } 7146 return false; 7147 } 7148 7149 inline bool Type::isFixedPointOrIntegerType() const { 7150 return isFixedPointType() || isIntegerType(); 7151 } 7152 7153 inline bool Type::isSaturatedFixedPointType() const { 7154 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 7155 return BT->getKind() >= BuiltinType::SatShortAccum && 7156 BT->getKind() <= BuiltinType::SatULongFract; 7157 } 7158 return false; 7159 } 7160 7161 inline bool Type::isUnsaturatedFixedPointType() const { 7162 return isFixedPointType() && !isSaturatedFixedPointType(); 7163 } 7164 7165 inline bool Type::isSignedFixedPointType() const { 7166 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { 7167 return ((BT->getKind() >= BuiltinType::ShortAccum && 7168 BT->getKind() <= BuiltinType::LongAccum) || 7169 (BT->getKind() >= BuiltinType::ShortFract && 7170 BT->getKind() <= BuiltinType::LongFract) || 7171 (BT->getKind() >= BuiltinType::SatShortAccum && 7172 BT->getKind() <= BuiltinType::SatLongAccum) || 7173 (BT->getKind() >= BuiltinType::SatShortFract && 7174 BT->getKind() <= BuiltinType::SatLongFract)); 7175 } 7176 return false; 7177 } 7178 7179 inline bool Type::isUnsignedFixedPointType() const { 7180 return isFixedPointType() && !isSignedFixedPointType(); 7181 } 7182 7183 inline bool Type::isScalarType() const { 7184 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7185 return BT->getKind() > BuiltinType::Void && 7186 BT->getKind() <= BuiltinType::NullPtr; 7187 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) 7188 // Enums are scalar types, but only if they are defined. Incomplete enums 7189 // are not treated as scalar types. 7190 return IsEnumDeclComplete(ET->getDecl()); 7191 return isa<PointerType>(CanonicalType) || 7192 isa<BlockPointerType>(CanonicalType) || 7193 isa<MemberPointerType>(CanonicalType) || 7194 isa<ComplexType>(CanonicalType) || 7195 isa<ObjCObjectPointerType>(CanonicalType) || 7196 isBitIntType(); 7197 } 7198 7199 inline bool Type::isIntegralOrEnumerationType() const { 7200 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7201 return BT->getKind() >= BuiltinType::Bool && 7202 BT->getKind() <= BuiltinType::Int128; 7203 7204 // Check for a complete enum type; incomplete enum types are not properly an 7205 // enumeration type in the sense required here. 7206 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) 7207 return IsEnumDeclComplete(ET->getDecl()); 7208 7209 return isBitIntType(); 7210 } 7211 7212 inline bool Type::isBooleanType() const { 7213 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) 7214 return BT->getKind() == BuiltinType::Bool; 7215 return false; 7216 } 7217 7218 inline bool Type::isUndeducedType() const { 7219 auto *DT = getContainedDeducedType(); 7220 return DT && !DT->isDeduced(); 7221 } 7222 7223 /// Determines whether this is a type for which one can define 7224 /// an overloaded operator. 7225 inline bool Type::isOverloadableType() const { 7226 return isDependentType() || isRecordType() || isEnumeralType(); 7227 } 7228 7229 /// Determines whether this type is written as a typedef-name. 7230 inline bool Type::isTypedefNameType() const { 7231 if (getAs<TypedefType>()) 7232 return true; 7233 if (auto *TST = getAs<TemplateSpecializationType>()) 7234 return TST->isTypeAlias(); 7235 return false; 7236 } 7237 7238 /// Determines whether this type can decay to a pointer type. 7239 inline bool Type::canDecayToPointerType() const { 7240 return isFunctionType() || isArrayType(); 7241 } 7242 7243 inline bool Type::hasPointerRepresentation() const { 7244 return (isPointerType() || isReferenceType() || isBlockPointerType() || 7245 isObjCObjectPointerType() || isNullPtrType()); 7246 } 7247 7248 inline bool Type::hasObjCPointerRepresentation() const { 7249 return isObjCObjectPointerType(); 7250 } 7251 7252 inline const Type *Type::getBaseElementTypeUnsafe() const { 7253 const Type *type = this; 7254 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) 7255 type = arrayType->getElementType().getTypePtr(); 7256 return type; 7257 } 7258 7259 inline const Type *Type::getPointeeOrArrayElementType() const { 7260 const Type *type = this; 7261 if (type->isAnyPointerType()) 7262 return type->getPointeeType().getTypePtr(); 7263 else if (type->isArrayType()) 7264 return type->getBaseElementTypeUnsafe(); 7265 return type; 7266 } 7267 /// Insertion operator for partial diagnostics. This allows sending adress 7268 /// spaces into a diagnostic with <<. 7269 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, 7270 LangAS AS) { 7271 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS), 7272 DiagnosticsEngine::ArgumentKind::ak_addrspace); 7273 return PD; 7274 } 7275 7276 /// Insertion operator for partial diagnostics. This allows sending Qualifiers 7277 /// into a diagnostic with <<. 7278 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, 7279 Qualifiers Q) { 7280 PD.AddTaggedVal(Q.getAsOpaqueValue(), 7281 DiagnosticsEngine::ArgumentKind::ak_qual); 7282 return PD; 7283 } 7284 7285 /// Insertion operator for partial diagnostics. This allows sending QualType's 7286 /// into a diagnostic with <<. 7287 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD, 7288 QualType T) { 7289 PD.AddTaggedVal(reinterpret_cast<uint64_t>(T.getAsOpaquePtr()), 7290 DiagnosticsEngine::ak_qualtype); 7291 return PD; 7292 } 7293 7294 // Helper class template that is used by Type::getAs to ensure that one does 7295 // not try to look through a qualified type to get to an array type. 7296 template <typename T> 7297 using TypeIsArrayType = 7298 std::integral_constant<bool, std::is_same<T, ArrayType>::value || 7299 std::is_base_of<ArrayType, T>::value>; 7300 7301 // Member-template getAs<specific type>'. 7302 template <typename T> const T *Type::getAs() const { 7303 static_assert(!TypeIsArrayType<T>::value, 7304 "ArrayType cannot be used with getAs!"); 7305 7306 // If this is directly a T type, return it. 7307 if (const auto *Ty = dyn_cast<T>(this)) 7308 return Ty; 7309 7310 // If the canonical form of this type isn't the right kind, reject it. 7311 if (!isa<T>(CanonicalType)) 7312 return nullptr; 7313 7314 // If this is a typedef for the type, strip the typedef off without 7315 // losing all typedef information. 7316 return cast<T>(getUnqualifiedDesugaredType()); 7317 } 7318 7319 template <typename T> const T *Type::getAsAdjusted() const { 7320 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); 7321 7322 // If this is directly a T type, return it. 7323 if (const auto *Ty = dyn_cast<T>(this)) 7324 return Ty; 7325 7326 // If the canonical form of this type isn't the right kind, reject it. 7327 if (!isa<T>(CanonicalType)) 7328 return nullptr; 7329 7330 // Strip off type adjustments that do not modify the underlying nature of the 7331 // type. 7332 const Type *Ty = this; 7333 while (Ty) { 7334 if (const auto *A = dyn_cast<AttributedType>(Ty)) 7335 Ty = A->getModifiedType().getTypePtr(); 7336 else if (const auto *A = dyn_cast<BTFTagAttributedType>(Ty)) 7337 Ty = A->getWrappedType().getTypePtr(); 7338 else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) 7339 Ty = E->desugar().getTypePtr(); 7340 else if (const auto *P = dyn_cast<ParenType>(Ty)) 7341 Ty = P->desugar().getTypePtr(); 7342 else if (const auto *A = dyn_cast<AdjustedType>(Ty)) 7343 Ty = A->desugar().getTypePtr(); 7344 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) 7345 Ty = M->desugar().getTypePtr(); 7346 else 7347 break; 7348 } 7349 7350 // Just because the canonical type is correct does not mean we can use cast<>, 7351 // since we may not have stripped off all the sugar down to the base type. 7352 return dyn_cast<T>(Ty); 7353 } 7354 7355 inline const ArrayType *Type::getAsArrayTypeUnsafe() const { 7356 // If this is directly an array type, return it. 7357 if (const auto *arr = dyn_cast<ArrayType>(this)) 7358 return arr; 7359 7360 // If the canonical form of this type isn't the right kind, reject it. 7361 if (!isa<ArrayType>(CanonicalType)) 7362 return nullptr; 7363 7364 // If this is a typedef for the type, strip the typedef off without 7365 // losing all typedef information. 7366 return cast<ArrayType>(getUnqualifiedDesugaredType()); 7367 } 7368 7369 template <typename T> const T *Type::castAs() const { 7370 static_assert(!TypeIsArrayType<T>::value, 7371 "ArrayType cannot be used with castAs!"); 7372 7373 if (const auto *ty = dyn_cast<T>(this)) return ty; 7374 assert(isa<T>(CanonicalType)); 7375 return cast<T>(getUnqualifiedDesugaredType()); 7376 } 7377 7378 inline const ArrayType *Type::castAsArrayTypeUnsafe() const { 7379 assert(isa<ArrayType>(CanonicalType)); 7380 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; 7381 return cast<ArrayType>(getUnqualifiedDesugaredType()); 7382 } 7383 7384 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, 7385 QualType CanonicalPtr) 7386 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { 7387 #ifndef NDEBUG 7388 QualType Adjusted = getAdjustedType(); 7389 (void)AttributedType::stripOuterNullability(Adjusted); 7390 assert(isa<PointerType>(Adjusted)); 7391 #endif 7392 } 7393 7394 QualType DecayedType::getPointeeType() const { 7395 QualType Decayed = getDecayedType(); 7396 (void)AttributedType::stripOuterNullability(Decayed); 7397 return cast<PointerType>(Decayed)->getPointeeType(); 7398 } 7399 7400 // Get the decimal string representation of a fixed point type, represented 7401 // as a scaled integer. 7402 // TODO: At some point, we should change the arguments to instead just accept an 7403 // APFixedPoint instead of APSInt and scale. 7404 void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, 7405 unsigned Scale); 7406 7407 } // namespace clang 7408 7409 #endif // LLVM_CLANG_AST_TYPE_H 7410