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