1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// C Language Family Type Representation
12 /// This file defines the clang::Type interface and subclasses, used to
13 /// represent types for languages in the C family.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_CLANG_AST_TYPE_H
18 #define LLVM_CLANG_AST_TYPE_H
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/TemplateName.h"
22 #include "clang/Basic/AddressSpaces.h"
23 #include "clang/Basic/AttrKinds.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/ExceptionSpecificationType.h"
26 #include "clang/Basic/LLVM.h"
27 #include "clang/Basic/Linkage.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Basic/Visibility.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/APSInt.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/FoldingSet.h"
36 #include "llvm/ADT/None.h"
37 #include "llvm/ADT/Optional.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/PointerUnion.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/type_traits.h"
48 #include "llvm/Support/TrailingObjects.h"
54 #include <type_traits>
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
74 struct PointerLikeTypeTraits;
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
102 template <typename> class CanQual;
107 class ExtQualsTypeCommonBase;
109 class IdentifierInfo;
111 class ObjCInterfaceDecl;
112 class ObjCProtocolDecl;
113 class ObjCTypeParamDecl;
114 struct PrintingPolicy;
118 class TemplateArgument;
119 class TemplateArgumentListInfo;
120 class TemplateArgumentLoc;
121 class TemplateTypeParmDecl;
122 class TypedefNameDecl;
123 class UnresolvedUsingTypenameDecl;
125 using CanQualType = CanQual<Type>;
127 // Provide forward declarations for all of the *Type classes.
128 #define TYPE(Class, Base) class Class##Type;
129 #include "clang/AST/TypeNodes.def"
131 /// The collection of all-type qualifiers we support.
132 /// Clang supports five independent qualifiers:
133 /// * C99: const, volatile, and restrict
134 /// * MS: __unaligned
135 /// * Embedded C (TR18037): address spaces
136 /// * Objective C: the GC attributes (none, weak, or strong)
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
143 CVRMask = Const | Volatile | Restrict
153 /// There is no lifetime qualification on this type.
156 /// This object can be modified without requiring retains or
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
167 /// Reading or writing from this object requires a barrier call.
170 /// Assigning into this object requires a lifetime extension.
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
179 /// The width of the "fast" qualifier mask.
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
186 /// Returns the common set of qualifiers while removing them from
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
192 Q.Mask = L.Mask & R.Mask;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
224 static Qualifiers fromFastMask(unsigned Mask) {
226 Qs.addFastQualifiers(Mask);
230 static Qualifiers fromCVRMask(unsigned CVR) {
232 Qs.addCVRQualifiers(CVR);
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
238 Qs.addCVRUQualifiers(CVRU);
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
275 Mask = (Mask & ~CVRMask) | mask;
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
336 assert(!hasObjCLifetime());
337 Mask |= (type << LifetimeShift);
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace);
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default);
381 setAddressSpace(space);
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
390 Mask = (Mask & ~FastMask) | mask;
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
421 if (!(Q.Mask & ~CVRMask))
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||
455 !hasAddressSpace() || !qs.hasAddressSpace());
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||
459 !hasObjCLifetime() || !qs.hasObjCLifetime());
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
467 /// every address space is a superset of itself.
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
528 explicit operator bool() const { return hasQualifiers(); }
530 Qualifiers &operator+=(Qualifiers R) {
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
542 Qualifiers &operator-=(Qualifiers R) {
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
560 void Profile(llvm::FoldingSetNodeID &ID) const {
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
580 /// A std::pair-like structure for storing a qualified type split
581 /// into its local qualifiers and its locally-unqualified type.
582 struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
586 /// The local qualifiers.
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
607 /// The kind of type we are substituting Objective-C type arguments into.
609 /// The kind of substitution affects the replacement of type parameters when
610 /// no concrete type information is provided, e.g., when dealing with an
611 /// unspecialized type.
612 enum class ObjCSubstitutionContext {
613 /// An ordinary type.
616 /// The result type of a method or function.
619 /// The parameter type of a method or function.
622 /// The type of a property.
625 /// The superclass of a type.
629 /// A (possibly-)qualified type.
631 /// For efficiency, we don't store CV-qualified types as nodes on their
632 /// own: instead each reference to a type stores the qualifiers. This
633 /// greatly reduces the number of nodes we need to allocate for types (for
634 /// example we only need one for 'int', 'const int', 'volatile int',
635 /// 'const volatile int', etc).
637 /// As an added efficiency bonus, instead of making this a pair, we
638 /// just store the two bits we care about in the low bits of the
639 /// pointer. To handle the packing/unpacking, we make QualType be a
640 /// simple wrapper class that acts like a smart pointer. A third bit
641 /// indicates whether there are extended qualifiers present, in which
642 /// case the pointer points to a special structure.
644 friend class QualifierCollector;
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer");
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
673 /// Retrieves a pointer to the underlying (unqualified) type.
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
679 const Type *getTypePtrOrNull() const;
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
684 /// Divides a QualType into its unqualified type and a set of local
686 SplitQualType split() const;
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
690 static QualType getFromOpaquePtr(const void *Ptr) {
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
696 const Type &operator*() const {
697 return *getTypePtr();
700 const Type *operator->() const {
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
762 Qualifiers getLocalQualifiers() const;
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
808 // Don't promise in the API that anything besides 'const' can be
811 /// Add the `const` type qualifier to this QualType.
813 addFastQualifiers(Qualifiers::Const);
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
819 /// Add the `volatile` type qualifier to this QualType.
821 addFastQualifiers(Qualifiers::Volatile);
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
827 /// Add the `restrict` qualifier to this QualType.
829 addFastQualifiers(Qualifiers::Restrict);
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)
841 && "non-fast qualifier bits set in mask!");
842 Value.setInt(Value.getInt() | TQs);
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
853 Value.setInt(Value.getInt() & ~Mask);
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
860 T.addFastQualifiers(TQs);
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
873 T.removeLocalFastQualifiers();
877 QualType getCanonicalType() const;
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
923 QualType getNonReferenceType() const;
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
951 /// Return the specified type with one level of "sugar" removed from
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
976 static std::string getAsString(SplitQualType split,
977 const PrintingPolicy &Policy) {
978 return getAsString(split.Ty, split.Quals, Policy);
980 static std::string getAsString(const Type *ty, Qualifiers qs,
981 const PrintingPolicy &Policy);
983 std::string getAsString() const;
984 std::string getAsString(const PrintingPolicy &Policy) const;
986 void print(raw_ostream &OS, const PrintingPolicy &Policy,
987 const Twine &PlaceHolder = Twine(),
988 unsigned Indentation = 0) const;
990 static void print(SplitQualType split, raw_ostream &OS,
991 const PrintingPolicy &policy, const Twine &PlaceHolder,
992 unsigned Indentation = 0) {
993 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
996 static void print(const Type *ty, Qualifiers qs,
997 raw_ostream &OS, const PrintingPolicy &policy,
998 const Twine &PlaceHolder,
999 unsigned Indentation = 0);
1001 void getAsStringInternal(std::string &Str,
1002 const PrintingPolicy &Policy) const;
1004 static void getAsStringInternal(SplitQualType split, std::string &out,
1005 const PrintingPolicy &policy) {
1006 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1009 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1011 const PrintingPolicy &policy);
1013 class StreamedQualTypeHelper {
1015 const PrintingPolicy &Policy;
1016 const Twine &PlaceHolder;
1017 unsigned Indentation;
1020 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1021 const Twine &PlaceHolder, unsigned Indentation)
1022 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1023 Indentation(Indentation) {}
1025 friend raw_ostream &operator<<(raw_ostream &OS,
1026 const StreamedQualTypeHelper &SQT) {
1027 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1032 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1033 const Twine &PlaceHolder = Twine(),
1034 unsigned Indentation = 0) const {
1035 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1038 void dump(const char *s) const;
1040 void dump(llvm::raw_ostream &OS) const;
1042 void Profile(llvm::FoldingSetNodeID &ID) const {
1043 ID.AddPointer(getAsOpaquePtr());
1046 /// Return the address space of this type.
1047 inline LangAS getAddressSpace() const;
1049 /// Returns gc attribute of this type.
1050 inline Qualifiers::GC getObjCGCAttr() const;
1052 /// true when Type is objc's weak.
1053 bool isObjCGCWeak() const {
1054 return getObjCGCAttr() == Qualifiers::Weak;
1057 /// true when Type is objc's strong.
1058 bool isObjCGCStrong() const {
1059 return getObjCGCAttr() == Qualifiers::Strong;
1062 /// Returns lifetime attribute of this type.
1063 Qualifiers::ObjCLifetime getObjCLifetime() const {
1064 return getQualifiers().getObjCLifetime();
1067 bool hasNonTrivialObjCLifetime() const {
1068 return getQualifiers().hasNonTrivialObjCLifetime();
1071 bool hasStrongOrWeakObjCLifetime() const {
1072 return getQualifiers().hasStrongOrWeakObjCLifetime();
1075 // true when Type is objc's weak and weak is enabled but ARC isn't.
1076 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1078 enum PrimitiveDefaultInitializeKind {
1079 /// The type does not fall into any of the following categories. Note that
1080 /// this case is zero-valued so that values of this enum can be used as a
1081 /// boolean condition for non-triviality.
1084 /// The type is an Objective-C retainable pointer type that is qualified
1085 /// with the ARC __strong qualifier.
1088 /// The type is an Objective-C retainable pointer type that is qualified
1089 /// with the ARC __weak qualifier.
1092 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 /// Functions to query basic properties of non-trivial C struct types.
1098 /// Check if this is a non-trivial type that would cause a C struct
1099 /// transitively containing this type to be non-trivial to default initialize
1100 /// and return the kind.
1101 PrimitiveDefaultInitializeKind
1102 isNonTrivialToPrimitiveDefaultInitialize() const;
1104 enum PrimitiveCopyKind {
1105 /// The type does not fall into any of the following categories. Note that
1106 /// this case is zero-valued so that values of this enum can be used as a
1107 /// boolean condition for non-triviality.
1110 /// The type would be trivial except that it is volatile-qualified. Types
1111 /// that fall into one of the other non-trivial cases may additionally be
1112 /// volatile-qualified.
1113 PCK_VolatileTrivial,
1115 /// The type is an Objective-C retainable pointer type that is qualified
1116 /// with the ARC __strong qualifier.
1119 /// The type is an Objective-C retainable pointer type that is qualified
1120 /// with the ARC __weak qualifier.
1123 /// The type is a struct containing a field whose type is neither
1124 /// PCK_Trivial nor PCK_VolatileTrivial.
1125 /// Note that a C++ struct type does not necessarily match this; C++ copying
1126 /// semantics are too complex to express here, in part because they depend
1127 /// on the exact constructor or assignment operator that is chosen by
1128 /// overload resolution to do the copy.
1132 /// Check if this is a non-trivial type that would cause a C struct
1133 /// transitively containing this type to be non-trivial to copy and return the
1135 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1137 /// Check if this is a non-trivial type that would cause a C struct
1138 /// transitively containing this type to be non-trivial to destructively
1139 /// move and return the kind. Destructive move in this context is a C++-style
1140 /// move in which the source object is placed in a valid but unspecified state
1141 /// after it is moved, as opposed to a truly destructive move in which the
1142 /// source object is placed in an uninitialized state.
1143 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1145 enum DestructionKind {
1148 DK_objc_strong_lifetime,
1149 DK_objc_weak_lifetime,
1150 DK_nontrivial_c_struct
1153 /// Returns a nonzero value if objects of this type require
1154 /// non-trivial work to clean up after. Non-zero because it's
1155 /// conceivable that qualifiers (objc_gc(weak)?) could make
1156 /// something require destruction.
1157 DestructionKind isDestructedType() const {
1158 return isDestructedTypeImpl(*this);
1161 /// Check if this is or contains a C union that is non-trivial to
1162 /// default-initialize, which is a union that has a member that is non-trivial
1163 /// to default-initialize. If this returns true,
1164 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1165 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1167 /// Check if this is or contains a C union that is non-trivial to destruct,
1168 /// which is a union that has a member that is non-trivial to destruct. If
1169 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1170 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1172 /// Check if this is or contains a C union that is non-trivial to copy, which
1173 /// is a union that has a member that is non-trivial to copy. If this returns
1174 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1175 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1177 /// Determine whether expressions of the given type are forbidden
1178 /// from being lvalues in C.
1180 /// The expression types that are forbidden to be lvalues are:
1181 /// - 'void', but not qualified void
1182 /// - function types
1184 /// The exact rule here is C99 6.3.2.1:
1185 /// An lvalue is an expression with an object type or an incomplete
1186 /// type other than void.
1187 bool isCForbiddenLValueType() const;
1189 /// Substitute type arguments for the Objective-C type parameters used in the
1192 /// \param ctx ASTContext in which the type exists.
1194 /// \param typeArgs The type arguments that will be substituted for the
1195 /// Objective-C type parameters in the subject type, which are generally
1196 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1197 /// parameters will be replaced with their bounds or id/Class, as appropriate
1198 /// for the context.
1200 /// \param context The context in which the subject type was written.
1202 /// \returns the resulting type.
1203 QualType substObjCTypeArgs(ASTContext &ctx,
1204 ArrayRef<QualType> typeArgs,
1205 ObjCSubstitutionContext context) const;
1207 /// Substitute type arguments from an object type for the Objective-C type
1208 /// parameters used in the subject type.
1210 /// This operation combines the computation of type arguments for
1211 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1212 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1213 /// callers that need to perform a single substitution in isolation.
1215 /// \param objectType The type of the object whose member type we're
1216 /// substituting into. For example, this might be the receiver of a message
1217 /// or the base of a property access.
1219 /// \param dc The declaration context from which the subject type was
1220 /// retrieved, which indicates (for example) which type parameters should
1223 /// \param context The context in which the subject type was written.
1225 /// \returns the subject type after replacing all of the Objective-C type
1226 /// parameters with their corresponding arguments.
1227 QualType substObjCMemberType(QualType objectType,
1228 const DeclContext *dc,
1229 ObjCSubstitutionContext context) const;
1231 /// Strip Objective-C "__kindof" types from the given type.
1232 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1234 /// Remove all qualifiers including _Atomic.
1235 QualType getAtomicUnqualifiedType() const;
1238 // These methods are implemented in a separate translation unit;
1239 // "static"-ize them to avoid creating temporary QualTypes in the
1241 static bool isConstant(QualType T, const ASTContext& Ctx);
1242 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1243 static SplitQualType getSplitDesugaredType(QualType T);
1244 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1245 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1246 const ASTContext &C);
1247 static QualType IgnoreParens(QualType T);
1248 static DestructionKind isDestructedTypeImpl(QualType type);
1250 /// Check if \param RD is or contains a non-trivial C union.
1251 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1252 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1253 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1256 } // namespace clang
1260 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1261 /// to a specific Type class.
1262 template<> struct simplify_type< ::clang::QualType> {
1263 using SimpleType = const ::clang::Type *;
1265 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1266 return Val.getTypePtr();
1270 // Teach SmallPtrSet that QualType is "basically a pointer".
1272 struct PointerLikeTypeTraits<clang::QualType> {
1273 static inline void *getAsVoidPointer(clang::QualType P) {
1274 return P.getAsOpaquePtr();
1277 static inline clang::QualType getFromVoidPointer(void *P) {
1278 return clang::QualType::getFromOpaquePtr(P);
1281 // Various qualifiers go in low bits.
1282 enum { NumLowBitsAvailable = 0 };
1289 /// Base class that is common to both the \c ExtQuals and \c Type
1290 /// classes, which allows \c QualType to access the common fields between the
1292 class ExtQualsTypeCommonBase {
1293 friend class ExtQuals;
1294 friend class QualType;
1297 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1298 /// a self-referential pointer (for \c Type).
1300 /// This pointer allows an efficient mapping from a QualType to its
1301 /// underlying type pointer.
1302 const Type *const BaseType;
1304 /// The canonical type of this type. A QualType.
1305 QualType CanonicalType;
1307 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1308 : BaseType(baseType), CanonicalType(canon) {}
1311 /// We can encode up to four bits in the low bits of a
1312 /// type pointer, but there are many more type qualifiers that we want
1313 /// to be able to apply to an arbitrary type. Therefore we have this
1314 /// struct, intended to be heap-allocated and used by QualType to
1315 /// store qualifiers.
1317 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1318 /// in three low bits on the QualType pointer; a fourth bit records whether
1319 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1320 /// Objective-C GC attributes) are much more rare.
1321 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1322 // NOTE: changing the fast qualifiers should be straightforward as
1323 // long as you don't make 'const' non-fast.
1325 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1326 // Fast qualifiers must occupy the low-order bits.
1327 // b) Update Qualifiers::FastWidth and FastMask.
1329 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1330 // b) Update remove{Volatile,Restrict}, defined near the end of
1333 // a) Update get{Volatile,Restrict}Type.
1335 /// The immutable set of qualifiers applied by this node. Always contains
1336 /// extended qualifiers.
1339 ExtQuals *this_() { return this; }
1342 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1343 : ExtQualsTypeCommonBase(baseType,
1344 canon.isNull() ? QualType(this_(), 0) : canon),
1346 assert(Quals.hasNonFastQualifiers()
1347 && "ExtQuals created with no fast qualifiers");
1348 assert(!Quals.hasFastQualifiers()
1349 && "ExtQuals created with fast qualifiers");
1352 Qualifiers getQualifiers() const { return Quals; }
1354 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1355 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1357 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1358 Qualifiers::ObjCLifetime getObjCLifetime() const {
1359 return Quals.getObjCLifetime();
1362 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1363 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1365 const Type *getBaseType() const { return BaseType; }
1368 void Profile(llvm::FoldingSetNodeID &ID) const {
1369 Profile(ID, getBaseType(), Quals);
1372 static void Profile(llvm::FoldingSetNodeID &ID,
1373 const Type *BaseType,
1375 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1376 ID.AddPointer(BaseType);
1381 /// The kind of C++11 ref-qualifier associated with a function type.
1382 /// This determines whether a member function's "this" object can be an
1383 /// lvalue, rvalue, or neither.
1384 enum RefQualifierKind {
1385 /// No ref-qualifier was provided.
1388 /// An lvalue ref-qualifier was provided (\c &).
1391 /// An rvalue ref-qualifier was provided (\c &&).
1395 /// Which keyword(s) were used to create an AutoType.
1396 enum class AutoTypeKeyword {
1403 /// __auto_type (GNU extension)
1407 /// The base class of the type hierarchy.
1409 /// A central concept with types is that each type always has a canonical
1410 /// type. A canonical type is the type with any typedef names stripped out
1411 /// of it or the types it references. For example, consider:
1413 /// typedef int foo;
1414 /// typedef foo* bar;
1415 /// 'int *' 'foo *' 'bar'
1417 /// There will be a Type object created for 'int'. Since int is canonical, its
1418 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1419 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1420 /// there is a PointerType that represents 'int*', which, like 'int', is
1421 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1422 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1425 /// Non-canonical types are useful for emitting diagnostics, without losing
1426 /// information about typedefs being used. Canonical types are useful for type
1427 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1428 /// about whether something has a particular form (e.g. is a function type),
1429 /// because they implicitly, recursively, strip all typedefs out of a type.
1431 /// Types, once created, are immutable.
1433 class alignas(8) Type : public ExtQualsTypeCommonBase {
1436 #define TYPE(Class, Base) Class,
1437 #define LAST_TYPE(Class) TypeLast = Class,
1438 #define ABSTRACT_TYPE(Class, Base)
1439 #include "clang/AST/TypeNodes.def"
1440 TagFirst = Record, TagLast = Enum
1444 /// Bitfields required by the Type class.
1445 class TypeBitfields {
1447 template <class T> friend class TypePropertyCache;
1449 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1453 unsigned Dependent : 1;
1455 /// Whether this type somehow involves a template parameter, even
1456 /// if the resolution of the type does not depend on a template parameter.
1457 unsigned InstantiationDependent : 1;
1459 /// Whether this type is a variably-modified type (C99 6.7.5).
1460 unsigned VariablyModified : 1;
1462 /// Whether this type contains an unexpanded parameter pack
1463 /// (for C++11 variadic templates).
1464 unsigned ContainsUnexpandedParameterPack : 1;
1466 /// True if the cache (i.e. the bitfields here starting with
1467 /// 'Cache') is valid.
1468 mutable unsigned CacheValid : 1;
1470 /// Linkage of this type.
1471 mutable unsigned CachedLinkage : 3;
1473 /// Whether this type involves and local or unnamed types.
1474 mutable unsigned CachedLocalOrUnnamed : 1;
1476 /// Whether this type comes from an AST file.
1477 mutable unsigned FromAST : 1;
1479 bool isCacheValid() const {
1483 Linkage getLinkage() const {
1484 assert(isCacheValid() && "getting linkage from invalid cache");
1485 return static_cast<Linkage>(CachedLinkage);
1488 bool hasLocalOrUnnamedType() const {
1489 assert(isCacheValid() && "getting linkage from invalid cache");
1490 return CachedLocalOrUnnamed;
1493 enum { NumTypeBits = 18 };
1496 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 class ArrayTypeBitfields {
1500 friend class ArrayType;
1502 unsigned : NumTypeBits;
1504 /// CVR qualifiers from declarations like
1505 /// 'int X[static restrict 4]'. For function parameters only.
1506 unsigned IndexTypeQuals : 3;
1508 /// Storage class qualifiers from declarations like
1509 /// 'int X[static restrict 4]'. For function parameters only.
1510 /// Actually an ArrayType::ArraySizeModifier.
1511 unsigned SizeModifier : 3;
1514 class BuiltinTypeBitfields {
1515 friend class BuiltinType;
1517 unsigned : NumTypeBits;
1519 /// The kind (BuiltinType::Kind) of builtin type this is.
1523 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1524 /// Only common bits are stored here. Additional uncommon bits are stored
1525 /// in a trailing object after FunctionProtoType.
1526 class FunctionTypeBitfields {
1527 friend class FunctionProtoType;
1528 friend class FunctionType;
1530 unsigned : NumTypeBits;
1532 /// Extra information which affects how the function is called, like
1533 /// regparm and the calling convention.
1534 unsigned ExtInfo : 12;
1536 /// The ref-qualifier associated with a \c FunctionProtoType.
1538 /// This is a value of type \c RefQualifierKind.
1539 unsigned RefQualifier : 2;
1541 /// Used only by FunctionProtoType, put here to pack with the
1542 /// other bitfields.
1543 /// The qualifiers are part of FunctionProtoType because...
1545 /// C++ 8.3.5p4: The return type, the parameter type list and the
1546 /// cv-qualifier-seq, [...], are part of the function type.
1547 unsigned FastTypeQuals : Qualifiers::FastWidth;
1548 /// Whether this function has extended Qualifiers.
1549 unsigned HasExtQuals : 1;
1551 /// The number of parameters this function has, not counting '...'.
1552 /// According to [implimits] 8 bits should be enough here but this is
1553 /// somewhat easy to exceed with metaprogramming and so we would like to
1554 /// keep NumParams as wide as reasonably possible.
1555 unsigned NumParams : 16;
1557 /// The type of exception specification this function has.
1558 unsigned ExceptionSpecType : 4;
1560 /// Whether this function has extended parameter information.
1561 unsigned HasExtParameterInfos : 1;
1563 /// Whether the function is variadic.
1564 unsigned Variadic : 1;
1566 /// Whether this function has a trailing return type.
1567 unsigned HasTrailingReturn : 1;
1570 class ObjCObjectTypeBitfields {
1571 friend class ObjCObjectType;
1573 unsigned : NumTypeBits;
1575 /// The number of type arguments stored directly on this object type.
1576 unsigned NumTypeArgs : 7;
1578 /// The number of protocols stored directly on this object type.
1579 unsigned NumProtocols : 6;
1581 /// Whether this is a "kindof" type.
1582 unsigned IsKindOf : 1;
1585 class ReferenceTypeBitfields {
1586 friend class ReferenceType;
1588 unsigned : NumTypeBits;
1590 /// True if the type was originally spelled with an lvalue sigil.
1591 /// This is never true of rvalue references but can also be false
1592 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// typedef int &ref; // lvalue, spelled lvalue
1596 /// typedef int &&rvref; // rvalue
1597 /// ref &a; // lvalue, inner ref, spelled lvalue
1598 /// ref &&a; // lvalue, inner ref
1599 /// rvref &a; // lvalue, inner ref, spelled lvalue
1600 /// rvref &&a; // rvalue, inner ref
1601 unsigned SpelledAsLValue : 1;
1603 /// True if the inner type is a reference type. This only happens
1604 /// in non-canonical forms.
1605 unsigned InnerRef : 1;
1608 class TypeWithKeywordBitfields {
1609 friend class TypeWithKeyword;
1611 unsigned : NumTypeBits;
1613 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1614 unsigned Keyword : 8;
1617 enum { NumTypeWithKeywordBits = 8 };
1619 class ElaboratedTypeBitfields {
1620 friend class ElaboratedType;
1622 unsigned : NumTypeBits;
1623 unsigned : NumTypeWithKeywordBits;
1625 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1626 unsigned HasOwnedTagDecl : 1;
1629 class VectorTypeBitfields {
1630 friend class VectorType;
1631 friend class DependentVectorType;
1633 unsigned : NumTypeBits;
1635 /// The kind of vector, either a generic vector type or some
1636 /// target-specific vector type such as for AltiVec or Neon.
1637 unsigned VecKind : 3;
1639 /// The number of elements in the vector.
1640 unsigned NumElements : 29 - NumTypeBits;
1642 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 class AttributedTypeBitfields {
1646 friend class AttributedType;
1648 unsigned : NumTypeBits;
1650 /// An AttributedType::Kind
1651 unsigned AttrKind : 32 - NumTypeBits;
1654 class AutoTypeBitfields {
1655 friend class AutoType;
1657 unsigned : NumTypeBits;
1659 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1660 /// or '__auto_type'? AutoTypeKeyword value.
1661 unsigned Keyword : 2;
1664 class SubstTemplateTypeParmPackTypeBitfields {
1665 friend class SubstTemplateTypeParmPackType;
1667 unsigned : NumTypeBits;
1669 /// The number of template arguments in \c Arguments, which is
1670 /// expected to be able to hold at least 1024 according to [implimits].
1671 /// However as this limit is somewhat easy to hit with template
1672 /// metaprogramming we'd prefer to keep it as large as possible.
1673 /// At the moment it has been left as a non-bitfield since this type
1674 /// safely fits in 64 bits as an unsigned, so there is no reason to
1675 /// introduce the performance impact of a bitfield.
1679 class TemplateSpecializationTypeBitfields {
1680 friend class TemplateSpecializationType;
1682 unsigned : NumTypeBits;
1684 /// Whether this template specialization type is a substituted type alias.
1685 unsigned TypeAlias : 1;
1687 /// The number of template arguments named in this class template
1688 /// specialization, which is expected to be able to hold at least 1024
1689 /// according to [implimits]. However, as this limit is somewhat easy to
1690 /// hit with template metaprogramming we'd prefer to keep it as large
1691 /// as possible. At the moment it has been left as a non-bitfield since
1692 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1693 /// to introduce the performance impact of a bitfield.
1697 class DependentTemplateSpecializationTypeBitfields {
1698 friend class DependentTemplateSpecializationType;
1700 unsigned : NumTypeBits;
1701 unsigned : NumTypeWithKeywordBits;
1703 /// The number of template arguments named in this class template
1704 /// specialization, which is expected to be able to hold at least 1024
1705 /// according to [implimits]. However, as this limit is somewhat easy to
1706 /// hit with template metaprogramming we'd prefer to keep it as large
1707 /// as possible. At the moment it has been left as a non-bitfield since
1708 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1709 /// to introduce the performance impact of a bitfield.
1713 class PackExpansionTypeBitfields {
1714 friend class PackExpansionType;
1716 unsigned : NumTypeBits;
1718 /// The number of expansions that this pack expansion will
1719 /// generate when substituted (+1), which is expected to be able to
1720 /// hold at least 1024 according to [implimits]. However, as this limit
1721 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1722 /// keep it as large as possible. At the moment it has been left as a
1723 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1724 /// there is no reason to introduce the performance impact of a bitfield.
1726 /// This field will only have a non-zero value when some of the parameter
1727 /// packs that occur within the pattern have been substituted but others
1729 unsigned NumExpansions;
1733 TypeBitfields TypeBits;
1734 ArrayTypeBitfields ArrayTypeBits;
1735 AttributedTypeBitfields AttributedTypeBits;
1736 AutoTypeBitfields AutoTypeBits;
1737 BuiltinTypeBitfields BuiltinTypeBits;
1738 FunctionTypeBitfields FunctionTypeBits;
1739 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1740 ReferenceTypeBitfields ReferenceTypeBits;
1741 TypeWithKeywordBitfields TypeWithKeywordBits;
1742 ElaboratedTypeBitfields ElaboratedTypeBits;
1743 VectorTypeBitfields VectorTypeBits;
1744 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1745 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1746 DependentTemplateSpecializationTypeBitfields
1747 DependentTemplateSpecializationTypeBits;
1748 PackExpansionTypeBitfields PackExpansionTypeBits;
1751 static_assert(sizeof(TypeBitfields) <= 8,
1752 "TypeBitfields is larger than 8 bytes!");
1753 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1754 "ArrayTypeBitfields is larger than 8 bytes!");
1755 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1756 "AttributedTypeBitfields is larger than 8 bytes!");
1757 static_assert(sizeof(AutoTypeBitfields) <= 8,
1758 "AutoTypeBitfields is larger than 8 bytes!");
1759 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1760 "BuiltinTypeBitfields is larger than 8 bytes!");
1761 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1762 "FunctionTypeBitfields is larger than 8 bytes!");
1763 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1764 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1765 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1766 "ReferenceTypeBitfields is larger than 8 bytes!");
1767 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1768 "TypeWithKeywordBitfields is larger than 8 bytes!");
1769 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1770 "ElaboratedTypeBitfields is larger than 8 bytes!");
1771 static_assert(sizeof(VectorTypeBitfields) <= 8,
1772 "VectorTypeBitfields is larger than 8 bytes!");
1773 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1774 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1777 "TemplateSpecializationTypeBitfields is larger"
1779 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1780 "DependentTemplateSpecializationTypeBitfields is larger"
1782 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1783 "PackExpansionTypeBitfields is larger than 8 bytes");
1786 template <class T> friend class TypePropertyCache;
1788 /// Set whether this type comes from an AST file.
1789 void setFromAST(bool V = true) const {
1790 TypeBits.FromAST = V;
1794 friend class ASTContext;
1796 Type(TypeClass tc, QualType canon, bool Dependent,
1797 bool InstantiationDependent, bool VariablyModified,
1798 bool ContainsUnexpandedParameterPack)
1799 : ExtQualsTypeCommonBase(this,
1800 canon.isNull() ? QualType(this_(), 0) : canon) {
1802 TypeBits.Dependent = Dependent;
1803 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1804 TypeBits.VariablyModified = VariablyModified;
1805 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1806 TypeBits.CacheValid = false;
1807 TypeBits.CachedLocalOrUnnamed = false;
1808 TypeBits.CachedLinkage = NoLinkage;
1809 TypeBits.FromAST = false;
1812 // silence VC++ warning C4355: 'this' : used in base member initializer list
1813 Type *this_() { return this; }
1815 void setDependent(bool D = true) {
1816 TypeBits.Dependent = D;
1818 TypeBits.InstantiationDependent = true;
1821 void setInstantiationDependent(bool D = true) {
1822 TypeBits.InstantiationDependent = D; }
1824 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1826 void setContainsUnexpandedParameterPack(bool PP = true) {
1827 TypeBits.ContainsUnexpandedParameterPack = PP;
1831 friend class ASTReader;
1832 friend class ASTWriter;
1834 Type(const Type &) = delete;
1835 Type(Type &&) = delete;
1836 Type &operator=(const Type &) = delete;
1837 Type &operator=(Type &&) = delete;
1839 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1841 /// Whether this type comes from an AST file.
1842 bool isFromAST() const { return TypeBits.FromAST; }
1844 /// Whether this type is or contains an unexpanded parameter
1845 /// pack, used to support C++0x variadic templates.
1847 /// A type that contains a parameter pack shall be expanded by the
1848 /// ellipsis operator at some point. For example, the typedef in the
1849 /// following example contains an unexpanded parameter pack 'T':
1852 /// template<typename ...T>
1854 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1858 /// Note that this routine does not specify which
1859 bool containsUnexpandedParameterPack() const {
1860 return TypeBits.ContainsUnexpandedParameterPack;
1863 /// Determines if this type would be canonical if it had no further
1865 bool isCanonicalUnqualified() const {
1866 return CanonicalType == QualType(this, 0);
1869 /// Pull a single level of sugar off of this locally-unqualified type.
1870 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1871 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1872 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1874 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1875 /// object types, function types, and incomplete types.
1877 /// Return true if this is an incomplete type.
1878 /// A type that can describe objects, but which lacks information needed to
1879 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1880 /// routine will need to determine if the size is actually required.
1882 /// Def If non-null, and the type refers to some kind of declaration
1883 /// that can be completed (such as a C struct, C++ class, or Objective-C
1884 /// class), will be set to the declaration.
1885 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1887 /// Return true if this is an incomplete or object
1888 /// type, in other words, not a function type.
1889 bool isIncompleteOrObjectType() const {
1890 return !isFunctionType();
1893 /// Determine whether this type is an object type.
1894 bool isObjectType() const {
1895 // C++ [basic.types]p8:
1896 // An object type is a (possibly cv-qualified) type that is not a
1897 // function type, not a reference type, and not a void type.
1898 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 /// Return true if this is a literal type
1902 /// (C++11 [basic.types]p10)
1903 bool isLiteralType(const ASTContext &Ctx) const;
1905 /// Test if this type is a standard-layout type.
1906 /// (C++0x [basic.type]p9)
1907 bool isStandardLayoutType() const;
1909 /// Helper methods to distinguish type categories. All type predicates
1910 /// operate on the canonical type, ignoring typedefs and qualifiers.
1912 /// Returns true if the type is a builtin type.
1913 bool isBuiltinType() const;
1915 /// Test for a particular builtin type.
1916 bool isSpecificBuiltinType(unsigned K) const;
1918 /// Test for a type which does not represent an actual type-system type but
1919 /// is instead used as a placeholder for various convenient purposes within
1920 /// Clang. All such types are BuiltinTypes.
1921 bool isPlaceholderType() const;
1922 const BuiltinType *getAsPlaceholderType() const;
1924 /// Test for a specific placeholder type.
1925 bool isSpecificPlaceholderType(unsigned K) const;
1927 /// Test for a placeholder type other than Overload; see
1928 /// BuiltinType::isNonOverloadPlaceholderType.
1929 bool isNonOverloadPlaceholderType() const;
1931 /// isIntegerType() does *not* include complex integers (a GCC extension).
1932 /// isComplexIntegerType() can be used to test for complex integers.
1933 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1934 bool isEnumeralType() const;
1936 /// Determine whether this type is a scoped enumeration type.
1937 bool isScopedEnumeralType() const;
1938 bool isBooleanType() const;
1939 bool isCharType() const;
1940 bool isWideCharType() const;
1941 bool isChar8Type() const;
1942 bool isChar16Type() const;
1943 bool isChar32Type() const;
1944 bool isAnyCharacterType() const;
1945 bool isIntegralType(const ASTContext &Ctx) const;
1947 /// Determine whether this type is an integral or enumeration type.
1948 bool isIntegralOrEnumerationType() const;
1950 /// Determine whether this type is an integral or unscoped enumeration type.
1951 bool isIntegralOrUnscopedEnumerationType() const;
1953 /// Floating point categories.
1954 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1955 /// isComplexType() does *not* include complex integers (a GCC extension).
1956 /// isComplexIntegerType() can be used to test for complex integers.
1957 bool isComplexType() const; // C99 6.2.5p11 (complex)
1958 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1959 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1960 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1961 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1962 bool isFloat128Type() const;
1963 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1964 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1965 bool isVoidType() const; // C99 6.2.5p19
1966 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1967 bool isAggregateType() const;
1968 bool isFundamentalType() const;
1969 bool isCompoundType() const;
1971 // Type Predicates: Check to see if this type is structurally the specified
1972 // type, ignoring typedefs and qualifiers.
1973 bool isFunctionType() const;
1974 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1975 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1976 bool isPointerType() const;
1977 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1978 bool isBlockPointerType() const;
1979 bool isVoidPointerType() const;
1980 bool isReferenceType() const;
1981 bool isLValueReferenceType() const;
1982 bool isRValueReferenceType() const;
1983 bool isFunctionPointerType() const;
1984 bool isFunctionReferenceType() const;
1985 bool isMemberPointerType() const;
1986 bool isMemberFunctionPointerType() const;
1987 bool isMemberDataPointerType() const;
1988 bool isArrayType() const;
1989 bool isConstantArrayType() const;
1990 bool isIncompleteArrayType() const;
1991 bool isVariableArrayType() const;
1992 bool isDependentSizedArrayType() const;
1993 bool isRecordType() const;
1994 bool isClassType() const;
1995 bool isStructureType() const;
1996 bool isObjCBoxableRecordType() const;
1997 bool isInterfaceType() const;
1998 bool isStructureOrClassType() const;
1999 bool isUnionType() const;
2000 bool isComplexIntegerType() const; // GCC _Complex integer type.
2001 bool isVectorType() const; // GCC vector type.
2002 bool isExtVectorType() const; // Extended vector type.
2003 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2004 bool isObjCObjectPointerType() const; // pointer to ObjC object
2005 bool isObjCRetainableType() const; // ObjC object or block pointer
2006 bool isObjCLifetimeType() const; // (array of)* retainable type
2007 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2008 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2009 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2010 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2011 // for the common case.
2012 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2013 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2014 bool isObjCQualifiedIdType() const; // id<foo>
2015 bool isObjCQualifiedClassType() const; // Class<foo>
2016 bool isObjCObjectOrInterfaceType() const;
2017 bool isObjCIdType() const; // id
2018 bool isDecltypeType() const;
2019 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// This approximates the answer to the following question: if this
2023 /// translation unit were compiled in ARC, would this type be qualified
2024 /// with __unsafe_unretained?
2025 bool isObjCInertUnsafeUnretainedType() const {
2026 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 /// Whether the type is Objective-C 'id' or a __kindof type of an
2030 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// \param bound Will be set to the bound on non-id subtype types,
2034 /// which will be (possibly specialized) Objective-C class type, or
2036 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2037 const ObjCObjectType *&bound) const;
2039 bool isObjCClassType() const; // Class
2041 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2042 /// Class type, e.g., __kindof Class <NSCopying>.
2044 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2045 /// here because Objective-C's type system cannot express "a class
2046 /// object for a subclass of NSFoo".
2047 bool isObjCClassOrClassKindOfType() const;
2049 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2050 bool isObjCSelType() const; // Class
2051 bool isObjCBuiltinType() const; // 'id' or 'Class'
2052 bool isObjCARCBridgableType() const;
2053 bool isCARCBridgableType() const;
2054 bool isTemplateTypeParmType() const; // C++ template type parameter
2055 bool isNullPtrType() const; // C++11 std::nullptr_t
2056 bool isAlignValT() const; // C++17 std::align_val_t
2057 bool isStdByteType() const; // C++17 std::byte
2058 bool isAtomicType() const; // C11 _Atomic()
2060 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2061 bool is##Id##Type() const;
2062 #include "clang/Basic/OpenCLImageTypes.def"
2064 bool isImageType() const; // Any OpenCL image type
2066 bool isSamplerT() const; // OpenCL sampler_t
2067 bool isEventT() const; // OpenCL event_t
2068 bool isClkEventT() const; // OpenCL clk_event_t
2069 bool isQueueT() const; // OpenCL queue_t
2070 bool isReserveIDT() const; // OpenCL reserve_id_t
2072 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2073 bool is##Id##Type() const;
2074 #include "clang/Basic/OpenCLExtensionTypes.def"
2075 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2076 bool isOCLIntelSubgroupAVCType() const;
2077 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2079 bool isPipeType() const; // OpenCL pipe type
2080 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2082 /// Determines if this type, which must satisfy
2083 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2084 /// than implicitly __strong.
2085 bool isObjCARCImplicitlyUnretainedType() const;
2087 /// Return the implicit lifetime for this type, which must not be dependent.
2088 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2090 enum ScalarTypeKind {
2093 STK_ObjCObjectPointer,
2098 STK_IntegralComplex,
2099 STK_FloatingComplex,
2103 /// Given that this is a scalar type, classify it.
2104 ScalarTypeKind getScalarTypeKind() const;
2106 /// Whether this type is a dependent type, meaning that its definition
2107 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2108 bool isDependentType() const { return TypeBits.Dependent; }
2110 /// Determine whether this type is an instantiation-dependent type,
2111 /// meaning that the type involves a template parameter (even if the
2112 /// definition does not actually depend on the type substituted for that
2113 /// template parameter).
2114 bool isInstantiationDependentType() const {
2115 return TypeBits.InstantiationDependent;
2118 /// Determine whether this type is an undeduced type, meaning that
2119 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2121 bool isUndeducedType() const;
2123 /// Whether this type is a variably-modified type (C99 6.7.5).
2124 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2126 /// Whether this type involves a variable-length array type
2127 /// with a definite size.
2128 bool hasSizedVLAType() const;
2130 /// Whether this type is or contains a local or unnamed type.
2131 bool hasUnnamedOrLocalType() const;
2133 bool isOverloadableType() const;
2135 /// Determine wither this type is a C++ elaborated-type-specifier.
2136 bool isElaboratedTypeSpecifier() const;
2138 bool canDecayToPointerType() const;
2140 /// Whether this type is represented natively as a pointer. This includes
2141 /// pointers, references, block pointers, and Objective-C interface,
2142 /// qualified id, and qualified interface types, as well as nullptr_t.
2143 bool hasPointerRepresentation() const;
2145 /// Whether this type can represent an objective pointer type for the
2146 /// purpose of GC'ability
2147 bool hasObjCPointerRepresentation() const;
2149 /// Determine whether this type has an integer representation
2150 /// of some sort, e.g., it is an integer type or a vector.
2151 bool hasIntegerRepresentation() const;
2153 /// Determine whether this type has an signed integer representation
2154 /// of some sort, e.g., it is an signed integer type or a vector.
2155 bool hasSignedIntegerRepresentation() const;
2157 /// Determine whether this type has an unsigned integer representation
2158 /// of some sort, e.g., it is an unsigned integer type or a vector.
2159 bool hasUnsignedIntegerRepresentation() const;
2161 /// Determine whether this type has a floating-point representation
2162 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2163 bool hasFloatingRepresentation() const;
2165 // Type Checking Functions: Check to see if this type is structurally the
2166 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2167 // the best type we can.
2168 const RecordType *getAsStructureType() const;
2169 /// NOTE: getAs*ArrayType are methods on ASTContext.
2170 const RecordType *getAsUnionType() const;
2171 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2172 const ObjCObjectType *getAsObjCInterfaceType() const;
2174 // The following is a convenience method that returns an ObjCObjectPointerType
2175 // for object declared using an interface.
2176 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2177 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2178 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2179 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2181 /// Retrieves the CXXRecordDecl that this type refers to, either
2182 /// because the type is a RecordType or because it is the injected-class-name
2183 /// type of a class template or class template partial specialization.
2184 CXXRecordDecl *getAsCXXRecordDecl() const;
2186 /// Retrieves the RecordDecl this type refers to.
2187 RecordDecl *getAsRecordDecl() const;
2189 /// Retrieves the TagDecl that this type refers to, either
2190 /// because the type is a TagType or because it is the injected-class-name
2191 /// type of a class template or class template partial specialization.
2192 TagDecl *getAsTagDecl() const;
2194 /// If this is a pointer or reference to a RecordType, return the
2195 /// CXXRecordDecl that the type refers to.
2197 /// If this is not a pointer or reference, or the type being pointed to does
2198 /// not refer to a CXXRecordDecl, returns NULL.
2199 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2201 /// Get the DeducedType whose type will be deduced for a variable with
2202 /// an initializer of this type. This looks through declarators like pointer
2203 /// types, but not through decltype or typedefs.
2204 DeducedType *getContainedDeducedType() const;
2206 /// Get the AutoType whose type will be deduced for a variable with
2207 /// an initializer of this type. This looks through declarators like pointer
2208 /// types, but not through decltype or typedefs.
2209 AutoType *getContainedAutoType() const {
2210 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2213 /// Determine whether this type was written with a leading 'auto'
2214 /// corresponding to a trailing return type (possibly for a nested
2215 /// function type within a pointer to function type or similar).
2216 bool hasAutoForTrailingReturnType() const;
2218 /// Member-template getAs<specific type>'. Look through sugar for
2219 /// an instance of \<specific type>. This scheme will eventually
2220 /// replace the specific getAsXXXX methods above.
2222 /// There are some specializations of this member template listed
2223 /// immediately following this class.
2224 template <typename T> const T *getAs() const;
2226 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2227 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2228 /// This is used when you need to walk over sugar nodes that represent some
2229 /// kind of type adjustment from a type that was written as a \<specific type>
2230 /// to another type that is still canonically a \<specific type>.
2231 template <typename T> const T *getAsAdjusted() const;
2233 /// A variant of getAs<> for array types which silently discards
2234 /// qualifiers from the outermost type.
2235 const ArrayType *getAsArrayTypeUnsafe() const;
2237 /// Member-template castAs<specific type>. Look through sugar for
2238 /// the underlying instance of \<specific type>.
2240 /// This method has the same relationship to getAs<T> as cast<T> has
2241 /// to dyn_cast<T>; which is to say, the underlying type *must*
2242 /// have the intended type, and this method will never return null.
2243 template <typename T> const T *castAs() const;
2245 /// A variant of castAs<> for array type which silently discards
2246 /// qualifiers from the outermost type.
2247 const ArrayType *castAsArrayTypeUnsafe() const;
2249 /// Determine whether this type had the specified attribute applied to it
2250 /// (looking through top-level type sugar).
2251 bool hasAttr(attr::Kind AK) const;
2253 /// Get the base element type of this type, potentially discarding type
2254 /// qualifiers. This should never be used when type qualifiers
2256 const Type *getBaseElementTypeUnsafe() const;
2258 /// If this is an array type, return the element type of the array,
2259 /// potentially with type qualifiers missing.
2260 /// This should never be used when type qualifiers are meaningful.
2261 const Type *getArrayElementTypeNoTypeQual() const;
2263 /// If this is a pointer type, return the pointee type.
2264 /// If this is an array type, return the array element type.
2265 /// This should never be used when type qualifiers are meaningful.
2266 const Type *getPointeeOrArrayElementType() const;
2268 /// If this is a pointer, ObjC object pointer, or block
2269 /// pointer, this returns the respective pointee.
2270 QualType getPointeeType() const;
2272 /// Return the specified type with any "sugar" removed from the type,
2273 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2274 const Type *getUnqualifiedDesugaredType() const;
2276 /// More type predicates useful for type checking/promotion
2277 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2279 /// Return true if this is an integer type that is
2280 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2281 /// or an enum decl which has a signed representation.
2282 bool isSignedIntegerType() const;
2284 /// Return true if this is an integer type that is
2285 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2286 /// or an enum decl which has an unsigned representation.
2287 bool isUnsignedIntegerType() const;
2289 /// Determines whether this is an integer type that is signed or an
2290 /// enumeration types whose underlying type is a signed integer type.
2291 bool isSignedIntegerOrEnumerationType() const;
2293 /// Determines whether this is an integer type that is unsigned or an
2294 /// enumeration types whose underlying type is a unsigned integer type.
2295 bool isUnsignedIntegerOrEnumerationType() const;
2297 /// Return true if this is a fixed point type according to
2298 /// ISO/IEC JTC1 SC22 WG14 N1169.
2299 bool isFixedPointType() const;
2301 /// Return true if this is a fixed point or integer type.
2302 bool isFixedPointOrIntegerType() const;
2304 /// Return true if this is a saturated fixed point type according to
2305 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2306 bool isSaturatedFixedPointType() const;
2308 /// Return true if this is a saturated fixed point type according to
2309 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2310 bool isUnsaturatedFixedPointType() const;
2312 /// Return true if this is a fixed point type that is signed according
2313 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2314 bool isSignedFixedPointType() const;
2316 /// Return true if this is a fixed point type that is unsigned according
2317 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2318 bool isUnsignedFixedPointType() const;
2320 /// Return true if this is not a variable sized type,
2321 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2322 /// incomplete types.
2323 bool isConstantSizeType() const;
2325 /// Returns true if this type can be represented by some
2326 /// set of type specifiers.
2327 bool isSpecifierType() const;
2329 /// Determine the linkage of this type.
2330 Linkage getLinkage() const;
2332 /// Determine the visibility of this type.
2333 Visibility getVisibility() const {
2334 return getLinkageAndVisibility().getVisibility();
2337 /// Return true if the visibility was explicitly set is the code.
2338 bool isVisibilityExplicit() const {
2339 return getLinkageAndVisibility().isVisibilityExplicit();
2342 /// Determine the linkage and visibility of this type.
2343 LinkageInfo getLinkageAndVisibility() const;
2345 /// True if the computed linkage is valid. Used for consistency
2346 /// checking. Should always return true.
2347 bool isLinkageValid() const;
2349 /// Determine the nullability of the given type.
2351 /// Note that nullability is only captured as sugar within the type
2352 /// system, not as part of the canonical type, so nullability will
2353 /// be lost by canonicalization and desugaring.
2354 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2356 /// Determine whether the given type can have a nullability
2357 /// specifier applied to it, i.e., if it is any kind of pointer type.
2359 /// \param ResultIfUnknown The value to return if we don't yet know whether
2360 /// this type can have nullability because it is dependent.
2361 bool canHaveNullability(bool ResultIfUnknown = true) const;
2363 /// Retrieve the set of substitutions required when accessing a member
2364 /// of the Objective-C receiver type that is declared in the given context.
2366 /// \c *this is the type of the object we're operating on, e.g., the
2367 /// receiver for a message send or the base of a property access, and is
2368 /// expected to be of some object or object pointer type.
2370 /// \param dc The declaration context for which we are building up a
2371 /// substitution mapping, which should be an Objective-C class, extension,
2372 /// category, or method within.
2374 /// \returns an array of type arguments that can be substituted for
2375 /// the type parameters of the given declaration context in any type described
2376 /// within that context, or an empty optional to indicate that no
2377 /// substitution is required.
2378 Optional<ArrayRef<QualType>>
2379 getObjCSubstitutions(const DeclContext *dc) const;
2381 /// Determines if this is an ObjC interface type that may accept type
2383 bool acceptsObjCTypeParams() const;
2385 const char *getTypeClassName() const;
2387 QualType getCanonicalTypeInternal() const {
2388 return CanonicalType;
2391 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2393 void dump(llvm::raw_ostream &OS) const;
2396 /// This will check for a TypedefType by removing any existing sugar
2397 /// until it reaches a TypedefType or a non-sugared type.
2398 template <> const TypedefType *Type::getAs() const;
2400 /// This will check for a TemplateSpecializationType by removing any
2401 /// existing sugar until it reaches a TemplateSpecializationType or a
2402 /// non-sugared type.
2403 template <> const TemplateSpecializationType *Type::getAs() const;
2405 /// This will check for an AttributedType by removing any existing sugar
2406 /// until it reaches an AttributedType or a non-sugared type.
2407 template <> const AttributedType *Type::getAs() const;
2409 // We can do canonical leaf types faster, because we don't have to
2410 // worry about preserving child type decoration.
2411 #define TYPE(Class, Base)
2412 #define LEAF_TYPE(Class) \
2413 template <> inline const Class##Type *Type::getAs() const { \
2414 return dyn_cast<Class##Type>(CanonicalType); \
2416 template <> inline const Class##Type *Type::castAs() const { \
2417 return cast<Class##Type>(CanonicalType); \
2419 #include "clang/AST/TypeNodes.def"
2421 /// This class is used for builtin types like 'int'. Builtin
2422 /// types are always canonical and have a literal name field.
2423 class BuiltinType : public Type {
2426 // OpenCL image types
2427 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2428 #include "clang/Basic/OpenCLImageTypes.def"
2429 // OpenCL extension types
2430 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2431 #include "clang/Basic/OpenCLExtensionTypes.def"
2432 // All other builtin types
2433 #define BUILTIN_TYPE(Id, SingletonId) Id,
2434 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2435 #include "clang/AST/BuiltinTypes.def"
2439 friend class ASTContext; // ASTContext creates these.
2442 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2443 /*InstantiationDependent=*/(K == Dependent),
2444 /*VariablyModified=*/false,
2445 /*Unexpanded parameter pack=*/false) {
2446 BuiltinTypeBits.Kind = K;
2450 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2451 StringRef getName(const PrintingPolicy &Policy) const;
2453 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2454 // The StringRef is null-terminated.
2455 StringRef str = getName(Policy);
2456 assert(!str.empty() && str.data()[str.size()] == '\0');
2460 bool isSugared() const { return false; }
2461 QualType desugar() const { return QualType(this, 0); }
2463 bool isInteger() const {
2464 return getKind() >= Bool && getKind() <= Int128;
2467 bool isSignedInteger() const {
2468 return getKind() >= Char_S && getKind() <= Int128;
2471 bool isUnsignedInteger() const {
2472 return getKind() >= Bool && getKind() <= UInt128;
2475 bool isFloatingPoint() const {
2476 return getKind() >= Half && getKind() <= Float128;
2479 /// Determines whether the given kind corresponds to a placeholder type.
2480 static bool isPlaceholderTypeKind(Kind K) {
2481 return K >= Overload;
2484 /// Determines whether this type is a placeholder type, i.e. a type
2485 /// which cannot appear in arbitrary positions in a fully-formed
2487 bool isPlaceholderType() const {
2488 return isPlaceholderTypeKind(getKind());
2491 /// Determines whether this type is a placeholder type other than
2492 /// Overload. Most placeholder types require only syntactic
2493 /// information about their context in order to be resolved (e.g.
2494 /// whether it is a call expression), which means they can (and
2495 /// should) be resolved in an earlier "phase" of analysis.
2496 /// Overload expressions sometimes pick up further information
2497 /// from their context, like whether the context expects a
2498 /// specific function-pointer type, and so frequently need
2499 /// special treatment.
2500 bool isNonOverloadPlaceholderType() const {
2501 return getKind() > Overload;
2504 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2507 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2508 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2509 class ComplexType : public Type, public llvm::FoldingSetNode {
2510 friend class ASTContext; // ASTContext creates these.
2512 QualType ElementType;
2514 ComplexType(QualType Element, QualType CanonicalPtr)
2515 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2516 Element->isInstantiationDependentType(),
2517 Element->isVariablyModifiedType(),
2518 Element->containsUnexpandedParameterPack()),
2519 ElementType(Element) {}
2522 QualType getElementType() const { return ElementType; }
2524 bool isSugared() const { return false; }
2525 QualType desugar() const { return QualType(this, 0); }
2527 void Profile(llvm::FoldingSetNodeID &ID) {
2528 Profile(ID, getElementType());
2531 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2532 ID.AddPointer(Element.getAsOpaquePtr());
2535 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2538 /// Sugar for parentheses used when specifying types.
2539 class ParenType : public Type, public llvm::FoldingSetNode {
2540 friend class ASTContext; // ASTContext creates these.
2544 ParenType(QualType InnerType, QualType CanonType)
2545 : Type(Paren, CanonType, InnerType->isDependentType(),
2546 InnerType->isInstantiationDependentType(),
2547 InnerType->isVariablyModifiedType(),
2548 InnerType->containsUnexpandedParameterPack()),
2552 QualType getInnerType() const { return Inner; }
2554 bool isSugared() const { return true; }
2555 QualType desugar() const { return getInnerType(); }
2557 void Profile(llvm::FoldingSetNodeID &ID) {
2558 Profile(ID, getInnerType());
2561 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2565 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2568 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2569 class PointerType : public Type, public llvm::FoldingSetNode {
2570 friend class ASTContext; // ASTContext creates these.
2572 QualType PointeeType;
2574 PointerType(QualType Pointee, QualType CanonicalPtr)
2575 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2576 Pointee->isInstantiationDependentType(),
2577 Pointee->isVariablyModifiedType(),
2578 Pointee->containsUnexpandedParameterPack()),
2579 PointeeType(Pointee) {}
2582 QualType getPointeeType() const { return PointeeType; }
2584 /// Returns true if address spaces of pointers overlap.
2585 /// OpenCL v2.0 defines conversion rules for pointers to different
2586 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2589 /// address spaces overlap iff they are they same.
2591 /// __generic overlaps with any address space except for __constant.
2592 bool isAddressSpaceOverlapping(const PointerType &other) const {
2593 Qualifiers thisQuals = PointeeType.getQualifiers();
2594 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2595 // Address spaces overlap if at least one of them is a superset of another
2596 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2597 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2600 bool isSugared() const { return false; }
2601 QualType desugar() const { return QualType(this, 0); }
2603 void Profile(llvm::FoldingSetNodeID &ID) {
2604 Profile(ID, getPointeeType());
2607 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2608 ID.AddPointer(Pointee.getAsOpaquePtr());
2611 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2614 /// Represents a type which was implicitly adjusted by the semantic
2615 /// engine for arbitrary reasons. For example, array and function types can
2616 /// decay, and function types can have their calling conventions adjusted.
2617 class AdjustedType : public Type, public llvm::FoldingSetNode {
2618 QualType OriginalTy;
2619 QualType AdjustedTy;
2622 friend class ASTContext; // ASTContext creates these.
2624 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2625 QualType CanonicalPtr)
2626 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2627 OriginalTy->isInstantiationDependentType(),
2628 OriginalTy->isVariablyModifiedType(),
2629 OriginalTy->containsUnexpandedParameterPack()),
2630 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2633 QualType getOriginalType() const { return OriginalTy; }
2634 QualType getAdjustedType() const { return AdjustedTy; }
2636 bool isSugared() const { return true; }
2637 QualType desugar() const { return AdjustedTy; }
2639 void Profile(llvm::FoldingSetNodeID &ID) {
2640 Profile(ID, OriginalTy, AdjustedTy);
2643 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2644 ID.AddPointer(Orig.getAsOpaquePtr());
2645 ID.AddPointer(New.getAsOpaquePtr());
2648 static bool classof(const Type *T) {
2649 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2653 /// Represents a pointer type decayed from an array or function type.
2654 class DecayedType : public AdjustedType {
2655 friend class ASTContext; // ASTContext creates these.
2658 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2661 QualType getDecayedType() const { return getAdjustedType(); }
2663 inline QualType getPointeeType() const;
2665 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2668 /// Pointer to a block type.
2669 /// This type is to represent types syntactically represented as
2670 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2671 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2672 friend class ASTContext; // ASTContext creates these.
2674 // Block is some kind of pointer type
2675 QualType PointeeType;
2677 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2678 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2679 Pointee->isInstantiationDependentType(),
2680 Pointee->isVariablyModifiedType(),
2681 Pointee->containsUnexpandedParameterPack()),
2682 PointeeType(Pointee) {}
2685 // Get the pointee type. Pointee is required to always be a function type.
2686 QualType getPointeeType() const { return PointeeType; }
2688 bool isSugared() const { return false; }
2689 QualType desugar() const { return QualType(this, 0); }
2691 void Profile(llvm::FoldingSetNodeID &ID) {
2692 Profile(ID, getPointeeType());
2695 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2696 ID.AddPointer(Pointee.getAsOpaquePtr());
2699 static bool classof(const Type *T) {
2700 return T->getTypeClass() == BlockPointer;
2704 /// Base for LValueReferenceType and RValueReferenceType
2705 class ReferenceType : public Type, public llvm::FoldingSetNode {
2706 QualType PointeeType;
2709 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2710 bool SpelledAsLValue)
2711 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2712 Referencee->isInstantiationDependentType(),
2713 Referencee->isVariablyModifiedType(),
2714 Referencee->containsUnexpandedParameterPack()),
2715 PointeeType(Referencee) {
2716 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2717 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2721 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2722 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2724 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2726 QualType getPointeeType() const {
2727 // FIXME: this might strip inner qualifiers; okay?
2728 const ReferenceType *T = this;
2729 while (T->isInnerRef())
2730 T = T->PointeeType->castAs<ReferenceType>();
2731 return T->PointeeType;
2734 void Profile(llvm::FoldingSetNodeID &ID) {
2735 Profile(ID, PointeeType, isSpelledAsLValue());
2738 static void Profile(llvm::FoldingSetNodeID &ID,
2739 QualType Referencee,
2740 bool SpelledAsLValue) {
2741 ID.AddPointer(Referencee.getAsOpaquePtr());
2742 ID.AddBoolean(SpelledAsLValue);
2745 static bool classof(const Type *T) {
2746 return T->getTypeClass() == LValueReference ||
2747 T->getTypeClass() == RValueReference;
2751 /// An lvalue reference type, per C++11 [dcl.ref].
2752 class LValueReferenceType : public ReferenceType {
2753 friend class ASTContext; // ASTContext creates these
2755 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2756 bool SpelledAsLValue)
2757 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2761 bool isSugared() const { return false; }
2762 QualType desugar() const { return QualType(this, 0); }
2764 static bool classof(const Type *T) {
2765 return T->getTypeClass() == LValueReference;
2769 /// An rvalue reference type, per C++11 [dcl.ref].
2770 class RValueReferenceType : public ReferenceType {
2771 friend class ASTContext; // ASTContext creates these
2773 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2774 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2777 bool isSugared() const { return false; }
2778 QualType desugar() const { return QualType(this, 0); }
2780 static bool classof(const Type *T) {
2781 return T->getTypeClass() == RValueReference;
2785 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2787 /// This includes both pointers to data members and pointer to member functions.
2788 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2789 friend class ASTContext; // ASTContext creates these.
2791 QualType PointeeType;
2793 /// The class of which the pointee is a member. Must ultimately be a
2794 /// RecordType, but could be a typedef or a template parameter too.
2797 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2798 : Type(MemberPointer, CanonicalPtr,
2799 Cls->isDependentType() || Pointee->isDependentType(),
2800 (Cls->isInstantiationDependentType() ||
2801 Pointee->isInstantiationDependentType()),
2802 Pointee->isVariablyModifiedType(),
2803 (Cls->containsUnexpandedParameterPack() ||
2804 Pointee->containsUnexpandedParameterPack())),
2805 PointeeType(Pointee), Class(Cls) {}
2808 QualType getPointeeType() const { return PointeeType; }
2810 /// Returns true if the member type (i.e. the pointee type) is a
2811 /// function type rather than a data-member type.
2812 bool isMemberFunctionPointer() const {
2813 return PointeeType->isFunctionProtoType();
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// data type rather than a function type.
2818 bool isMemberDataPointer() const {
2819 return !PointeeType->isFunctionProtoType();
2822 const Type *getClass() const { return Class; }
2823 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2825 bool isSugared() const { return false; }
2826 QualType desugar() const { return QualType(this, 0); }
2828 void Profile(llvm::FoldingSetNodeID &ID) {
2829 Profile(ID, getPointeeType(), getClass());
2832 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2833 const Type *Class) {
2834 ID.AddPointer(Pointee.getAsOpaquePtr());
2835 ID.AddPointer(Class);
2838 static bool classof(const Type *T) {
2839 return T->getTypeClass() == MemberPointer;
2843 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2844 class ArrayType : public Type, public llvm::FoldingSetNode {
2846 /// Capture whether this is a normal array (e.g. int X[4])
2847 /// an array with a static size (e.g. int X[static 4]), or an array
2848 /// with a star size (e.g. int X[*]).
2849 /// 'static' is only allowed on function parameters.
2850 enum ArraySizeModifier {
2851 Normal, Static, Star
2855 /// The element type of the array.
2856 QualType ElementType;
2859 friend class ASTContext; // ASTContext creates these.
2861 // C++ [temp.dep.type]p1:
2862 // A type is dependent if it is...
2863 // - an array type constructed from any dependent type or whose
2864 // size is specified by a constant expression that is
2866 ArrayType(TypeClass tc, QualType et, QualType can,
2867 ArraySizeModifier sm, unsigned tq,
2868 bool ContainsUnexpandedParameterPack)
2869 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2870 et->isInstantiationDependentType() || tc == DependentSizedArray,
2871 (tc == VariableArray || et->isVariablyModifiedType()),
2872 ContainsUnexpandedParameterPack),
2874 ArrayTypeBits.IndexTypeQuals = tq;
2875 ArrayTypeBits.SizeModifier = sm;
2879 QualType getElementType() const { return ElementType; }
2881 ArraySizeModifier getSizeModifier() const {
2882 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2885 Qualifiers getIndexTypeQualifiers() const {
2886 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2889 unsigned getIndexTypeCVRQualifiers() const {
2890 return ArrayTypeBits.IndexTypeQuals;
2893 static bool classof(const Type *T) {
2894 return T->getTypeClass() == ConstantArray ||
2895 T->getTypeClass() == VariableArray ||
2896 T->getTypeClass() == IncompleteArray ||
2897 T->getTypeClass() == DependentSizedArray;
2901 /// Represents the canonical version of C arrays with a specified constant size.
2902 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2903 /// ConstantArrayType where the element type is 'int' and the size is 404.
2904 class ConstantArrayType : public ArrayType {
2905 llvm::APInt Size; // Allows us to unique the type.
2907 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2908 ArraySizeModifier sm, unsigned tq)
2909 : ArrayType(ConstantArray, et, can, sm, tq,
2910 et->containsUnexpandedParameterPack()),
2914 friend class ASTContext; // ASTContext creates these.
2916 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2917 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2918 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2922 const llvm::APInt &getSize() const { return Size; }
2923 bool isSugared() const { return false; }
2924 QualType desugar() const { return QualType(this, 0); }
2926 /// Determine the number of bits required to address a member of
2927 // an array with the given element type and number of elements.
2928 static unsigned getNumAddressingBits(const ASTContext &Context,
2929 QualType ElementType,
2930 const llvm::APInt &NumElements);
2932 /// Determine the maximum number of active bits that an array's size
2933 /// can require, which limits the maximum size of the array.
2934 static unsigned getMaxSizeBits(const ASTContext &Context);
2936 void Profile(llvm::FoldingSetNodeID &ID) {
2937 Profile(ID, getElementType(), getSize(),
2938 getSizeModifier(), getIndexTypeCVRQualifiers());
2941 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2942 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2943 unsigned TypeQuals) {
2944 ID.AddPointer(ET.getAsOpaquePtr());
2945 ID.AddInteger(ArraySize.getZExtValue());
2946 ID.AddInteger(SizeMod);
2947 ID.AddInteger(TypeQuals);
2950 static bool classof(const Type *T) {
2951 return T->getTypeClass() == ConstantArray;
2955 /// Represents a C array with an unspecified size. For example 'int A[]' has
2956 /// an IncompleteArrayType where the element type is 'int' and the size is
2958 class IncompleteArrayType : public ArrayType {
2959 friend class ASTContext; // ASTContext creates these.
2961 IncompleteArrayType(QualType et, QualType can,
2962 ArraySizeModifier sm, unsigned tq)
2963 : ArrayType(IncompleteArray, et, can, sm, tq,
2964 et->containsUnexpandedParameterPack()) {}
2967 friend class StmtIteratorBase;
2969 bool isSugared() const { return false; }
2970 QualType desugar() const { return QualType(this, 0); }
2972 static bool classof(const Type *T) {
2973 return T->getTypeClass() == IncompleteArray;
2976 void Profile(llvm::FoldingSetNodeID &ID) {
2977 Profile(ID, getElementType(), getSizeModifier(),
2978 getIndexTypeCVRQualifiers());
2981 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2982 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2983 ID.AddPointer(ET.getAsOpaquePtr());
2984 ID.AddInteger(SizeMod);
2985 ID.AddInteger(TypeQuals);
2989 /// Represents a C array with a specified size that is not an
2990 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2991 /// Since the size expression is an arbitrary expression, we store it as such.
2993 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2994 /// should not be: two lexically equivalent variable array types could mean
2995 /// different things, for example, these variables do not have the same type
2998 /// void foo(int x) {
3003 class VariableArrayType : public ArrayType {
3004 friend class ASTContext; // ASTContext creates these.
3006 /// An assignment-expression. VLA's are only permitted within
3007 /// a function block.
3010 /// The range spanned by the left and right array brackets.
3011 SourceRange Brackets;
3013 VariableArrayType(QualType et, QualType can, Expr *e,
3014 ArraySizeModifier sm, unsigned tq,
3015 SourceRange brackets)
3016 : ArrayType(VariableArray, et, can, sm, tq,
3017 et->containsUnexpandedParameterPack()),
3018 SizeExpr((Stmt*) e), Brackets(brackets) {}
3021 friend class StmtIteratorBase;
3023 Expr *getSizeExpr() const {
3024 // We use C-style casts instead of cast<> here because we do not wish
3025 // to have a dependency of Type.h on Stmt.h/Expr.h.
3026 return (Expr*) SizeExpr;
3029 SourceRange getBracketsRange() const { return Brackets; }
3030 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3031 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3033 bool isSugared() const { return false; }
3034 QualType desugar() const { return QualType(this, 0); }
3036 static bool classof(const Type *T) {
3037 return T->getTypeClass() == VariableArray;
3040 void Profile(llvm::FoldingSetNodeID &ID) {
3041 llvm_unreachable("Cannot unique VariableArrayTypes.");
3045 /// Represents an array type in C++ whose size is a value-dependent expression.
3049 /// template<typename T, int Size>
3055 /// For these types, we won't actually know what the array bound is
3056 /// until template instantiation occurs, at which point this will
3057 /// become either a ConstantArrayType or a VariableArrayType.
3058 class DependentSizedArrayType : public ArrayType {
3059 friend class ASTContext; // ASTContext creates these.
3061 const ASTContext &Context;
3063 /// An assignment expression that will instantiate to the
3064 /// size of the array.
3066 /// The expression itself might be null, in which case the array
3067 /// type will have its size deduced from an initializer.
3070 /// The range spanned by the left and right array brackets.
3071 SourceRange Brackets;
3073 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3074 Expr *e, ArraySizeModifier sm, unsigned tq,
3075 SourceRange brackets);
3078 friend class StmtIteratorBase;
3080 Expr *getSizeExpr() const {
3081 // We use C-style casts instead of cast<> here because we do not wish
3082 // to have a dependency of Type.h on Stmt.h/Expr.h.
3083 return (Expr*) SizeExpr;
3086 SourceRange getBracketsRange() const { return Brackets; }
3087 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3088 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3090 bool isSugared() const { return false; }
3091 QualType desugar() const { return QualType(this, 0); }
3093 static bool classof(const Type *T) {
3094 return T->getTypeClass() == DependentSizedArray;
3097 void Profile(llvm::FoldingSetNodeID &ID) {
3098 Profile(ID, Context, getElementType(),
3099 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3102 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3103 QualType ET, ArraySizeModifier SizeMod,
3104 unsigned TypeQuals, Expr *E);
3107 /// Represents an extended address space qualifier where the input address space
3108 /// value is dependent. Non-dependent address spaces are not represented with a
3109 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3113 /// template<typename T, int AddrSpace>
3114 /// class AddressSpace {
3115 /// typedef T __attribute__((address_space(AddrSpace))) type;
3118 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3119 friend class ASTContext;
3121 const ASTContext &Context;
3122 Expr *AddrSpaceExpr;
3123 QualType PointeeType;
3126 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3127 QualType can, Expr *AddrSpaceExpr,
3128 SourceLocation loc);
3131 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3132 QualType getPointeeType() const { return PointeeType; }
3133 SourceLocation getAttributeLoc() const { return loc; }
3135 bool isSugared() const { return false; }
3136 QualType desugar() const { return QualType(this, 0); }
3138 static bool classof(const Type *T) {
3139 return T->getTypeClass() == DependentAddressSpace;
3142 void Profile(llvm::FoldingSetNodeID &ID) {
3143 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3146 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3147 QualType PointeeType, Expr *AddrSpaceExpr);
3150 /// Represents an extended vector type where either the type or size is
3155 /// template<typename T, int Size>
3157 /// typedef T __attribute__((ext_vector_type(Size))) type;
3160 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3161 friend class ASTContext;
3163 const ASTContext &Context;
3166 /// The element type of the array.
3167 QualType ElementType;
3171 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3172 QualType can, Expr *SizeExpr, SourceLocation loc);
3175 Expr *getSizeExpr() const { return SizeExpr; }
3176 QualType getElementType() const { return ElementType; }
3177 SourceLocation getAttributeLoc() const { return loc; }
3179 bool isSugared() const { return false; }
3180 QualType desugar() const { return QualType(this, 0); }
3182 static bool classof(const Type *T) {
3183 return T->getTypeClass() == DependentSizedExtVector;
3186 void Profile(llvm::FoldingSetNodeID &ID) {
3187 Profile(ID, Context, getElementType(), getSizeExpr());
3190 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3191 QualType ElementType, Expr *SizeExpr);
3195 /// Represents a GCC generic vector type. This type is created using
3196 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3197 /// bytes; or from an Altivec __vector or vector declaration.
3198 /// Since the constructor takes the number of vector elements, the
3199 /// client is responsible for converting the size into the number of elements.
3200 class VectorType : public Type, public llvm::FoldingSetNode {
3203 /// not a target-specific vector type
3206 /// is AltiVec vector
3209 /// is AltiVec 'vector Pixel'
3212 /// is AltiVec 'vector bool ...'
3215 /// is ARM Neon vector
3218 /// is ARM Neon polynomial vector
3223 friend class ASTContext; // ASTContext creates these.
3225 /// The element type of the vector.
3226 QualType ElementType;
3228 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3229 VectorKind vecKind);
3231 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3232 QualType canonType, VectorKind vecKind);
3235 QualType getElementType() const { return ElementType; }
3236 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3238 static bool isVectorSizeTooLarge(unsigned NumElements) {
3239 return NumElements > VectorTypeBitfields::MaxNumElements;
3242 bool isSugared() const { return false; }
3243 QualType desugar() const { return QualType(this, 0); }
3245 VectorKind getVectorKind() const {
3246 return VectorKind(VectorTypeBits.VecKind);
3249 void Profile(llvm::FoldingSetNodeID &ID) {
3250 Profile(ID, getElementType(), getNumElements(),
3251 getTypeClass(), getVectorKind());
3254 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3255 unsigned NumElements, TypeClass TypeClass,
3256 VectorKind VecKind) {
3257 ID.AddPointer(ElementType.getAsOpaquePtr());
3258 ID.AddInteger(NumElements);
3259 ID.AddInteger(TypeClass);
3260 ID.AddInteger(VecKind);
3263 static bool classof(const Type *T) {
3264 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3268 /// Represents a vector type where either the type or size is dependent.
3272 /// template<typename T, int Size>
3274 /// typedef T __attribute__((vector_size(Size))) type;
3277 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3278 friend class ASTContext;
3280 const ASTContext &Context;
3281 QualType ElementType;
3285 DependentVectorType(const ASTContext &Context, QualType ElementType,
3286 QualType CanonType, Expr *SizeExpr,
3287 SourceLocation Loc, VectorType::VectorKind vecKind);
3290 Expr *getSizeExpr() const { return SizeExpr; }
3291 QualType getElementType() const { return ElementType; }
3292 SourceLocation getAttributeLoc() const { return Loc; }
3293 VectorType::VectorKind getVectorKind() const {
3294 return VectorType::VectorKind(VectorTypeBits.VecKind);
3297 bool isSugared() const { return false; }
3298 QualType desugar() const { return QualType(this, 0); }
3300 static bool classof(const Type *T) {
3301 return T->getTypeClass() == DependentVector;
3304 void Profile(llvm::FoldingSetNodeID &ID) {
3305 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3308 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3309 QualType ElementType, const Expr *SizeExpr,
3310 VectorType::VectorKind VecKind);
3313 /// ExtVectorType - Extended vector type. This type is created using
3314 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3315 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3316 /// class enables syntactic extensions, like Vector Components for accessing
3317 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3318 /// Shading Language).
3319 class ExtVectorType : public VectorType {
3320 friend class ASTContext; // ASTContext creates these.
3322 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3323 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3326 static int getPointAccessorIdx(char c) {
3329 case 'x': case 'r': return 0;
3330 case 'y': case 'g': return 1;
3331 case 'z': case 'b': return 2;
3332 case 'w': case 'a': return 3;
3336 static int getNumericAccessorIdx(char c) {
3350 case 'a': return 10;
3352 case 'b': return 11;
3354 case 'c': return 12;
3356 case 'd': return 13;
3358 case 'e': return 14;
3360 case 'f': return 15;
3364 static int getAccessorIdx(char c, bool isNumericAccessor) {
3365 if (isNumericAccessor)
3366 return getNumericAccessorIdx(c);
3368 return getPointAccessorIdx(c);
3371 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3372 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3373 return unsigned(idx-1) < getNumElements();
3377 bool isSugared() const { return false; }
3378 QualType desugar() const { return QualType(this, 0); }
3380 static bool classof(const Type *T) {
3381 return T->getTypeClass() == ExtVector;
3385 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3386 /// class of FunctionNoProtoType and FunctionProtoType.
3387 class FunctionType : public Type {
3388 // The type returned by the function.
3389 QualType ResultType;
3392 /// Interesting information about a specific parameter that can't simply
3393 /// be reflected in parameter's type. This is only used by FunctionProtoType
3394 /// but is in FunctionType to make this class available during the
3395 /// specification of the bases of FunctionProtoType.
3397 /// It makes sense to model language features this way when there's some
3398 /// sort of parameter-specific override (such as an attribute) that
3399 /// affects how the function is called. For example, the ARC ns_consumed
3400 /// attribute changes whether a parameter is passed at +0 (the default)
3401 /// or +1 (ns_consumed). This must be reflected in the function type,
3402 /// but isn't really a change to the parameter type.
3404 /// One serious disadvantage of modelling language features this way is
3405 /// that they generally do not work with language features that attempt
3406 /// to destructure types. For example, template argument deduction will
3407 /// not be able to match a parameter declared as
3409 /// against an argument of type
3410 /// void (*)(__attribute__((ns_consumed)) id)
3411 /// because the substitution of T=void, U=id into the former will
3412 /// not produce the latter.
3413 class ExtParameterInfo {
3417 HasPassObjSize = 0x20,
3420 unsigned char Data = 0;
3423 ExtParameterInfo() = default;
3425 /// Return the ABI treatment of this parameter.
3426 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3427 ExtParameterInfo withABI(ParameterABI kind) const {
3428 ExtParameterInfo copy = *this;
3429 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3433 /// Is this parameter considered "consumed" by Objective-C ARC?
3434 /// Consumed parameters must have retainable object type.
3435 bool isConsumed() const { return (Data & IsConsumed); }
3436 ExtParameterInfo withIsConsumed(bool consumed) const {
3437 ExtParameterInfo copy = *this;
3439 copy.Data |= IsConsumed;
3441 copy.Data &= ~IsConsumed;
3445 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3446 ExtParameterInfo withHasPassObjectSize() const {
3447 ExtParameterInfo Copy = *this;
3448 Copy.Data |= HasPassObjSize;
3452 bool isNoEscape() const { return Data & IsNoEscape; }
3453 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3454 ExtParameterInfo Copy = *this;
3456 Copy.Data |= IsNoEscape;
3458 Copy.Data &= ~IsNoEscape;
3462 unsigned char getOpaqueValue() const { return Data; }
3463 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3464 ExtParameterInfo result;
3469 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3470 return lhs.Data == rhs.Data;
3473 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3474 return lhs.Data != rhs.Data;
3478 /// A class which abstracts out some details necessary for
3481 /// It is not actually used directly for storing this information in
3482 /// a FunctionType, although FunctionType does currently use the
3483 /// same bit-pattern.
3485 // If you add a field (say Foo), other than the obvious places (both,
3486 // constructors, compile failures), what you need to update is
3490 // * functionType. Add Foo, getFoo.
3491 // * ASTContext::getFooType
3492 // * ASTContext::mergeFunctionTypes
3493 // * FunctionNoProtoType::Profile
3494 // * FunctionProtoType::Profile
3495 // * TypePrinter::PrintFunctionProto
3496 // * AST read and write
3499 friend class FunctionType;
3501 // Feel free to rearrange or add bits, but if you go over 12,
3502 // you'll need to adjust both the Bits field below and
3503 // Type::FunctionTypeBitfields.
3505 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3506 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3508 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3509 enum { CallConvMask = 0x1F };
3510 enum { NoReturnMask = 0x20 };
3511 enum { ProducesResultMask = 0x40 };
3512 enum { NoCallerSavedRegsMask = 0x80 };
3513 enum { NoCfCheckMask = 0x800 };
3515 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3516 NoCallerSavedRegsMask | NoCfCheckMask),
3518 }; // Assumed to be the last field
3519 uint16_t Bits = CC_C;
3521 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3524 // Constructor with no defaults. Use this when you know that you
3525 // have all the elements (when reading an AST file for example).
3526 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3527 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3528 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3529 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3530 (producesResult ? ProducesResultMask : 0) |
3531 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3532 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3533 (NoCfCheck ? NoCfCheckMask : 0);
3536 // Constructor with all defaults. Use when for example creating a
3537 // function known to use defaults.
3538 ExtInfo() = default;
3540 // Constructor with just the calling convention, which is an important part
3541 // of the canonical type.
3542 ExtInfo(CallingConv CC) : Bits(CC) {}
3544 bool getNoReturn() const { return Bits & NoReturnMask; }
3545 bool getProducesResult() const { return Bits & ProducesResultMask; }
3546 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3547 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3548 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3550 unsigned getRegParm() const {
3551 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3557 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3559 bool operator==(ExtInfo Other) const {
3560 return Bits == Other.Bits;
3562 bool operator!=(ExtInfo Other) const {
3563 return Bits != Other.Bits;
3566 // Note that we don't have setters. That is by design, use
3567 // the following with methods instead of mutating these objects.
3569 ExtInfo withNoReturn(bool noReturn) const {
3571 return ExtInfo(Bits | NoReturnMask);
3573 return ExtInfo(Bits & ~NoReturnMask);
3576 ExtInfo withProducesResult(bool producesResult) const {
3578 return ExtInfo(Bits | ProducesResultMask);
3580 return ExtInfo(Bits & ~ProducesResultMask);
3583 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3584 if (noCallerSavedRegs)
3585 return ExtInfo(Bits | NoCallerSavedRegsMask);
3587 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3590 ExtInfo withNoCfCheck(bool noCfCheck) const {
3592 return ExtInfo(Bits | NoCfCheckMask);
3594 return ExtInfo(Bits & ~NoCfCheckMask);
3597 ExtInfo withRegParm(unsigned RegParm) const {
3598 assert(RegParm < 7 && "Invalid regparm value");
3599 return ExtInfo((Bits & ~RegParmMask) |
3600 ((RegParm + 1) << RegParmOffset));
3603 ExtInfo withCallingConv(CallingConv cc) const {
3604 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3607 void Profile(llvm::FoldingSetNodeID &ID) const {
3608 ID.AddInteger(Bits);
3612 /// A simple holder for a QualType representing a type in an
3613 /// exception specification. Unfortunately needed by FunctionProtoType
3614 /// because TrailingObjects cannot handle repeated types.
3615 struct ExceptionType { QualType Type; };
3617 /// A simple holder for various uncommon bits which do not fit in
3618 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3619 /// alignment of subsequent objects in TrailingObjects. You must update
3620 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3621 struct alignas(void *) FunctionTypeExtraBitfields {
3622 /// The number of types in the exception specification.
3623 /// A whole unsigned is not needed here and according to
3624 /// [implimits] 8 bits would be enough here.
3625 unsigned NumExceptionType;
3629 FunctionType(TypeClass tc, QualType res,
3630 QualType Canonical, bool Dependent,
3631 bool InstantiationDependent,
3632 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3634 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3635 ContainsUnexpandedParameterPack),
3637 FunctionTypeBits.ExtInfo = Info.Bits;
3640 Qualifiers getFastTypeQuals() const {
3641 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3645 QualType getReturnType() const { return ResultType; }
3647 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3648 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3650 /// Determine whether this function type includes the GNU noreturn
3651 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3653 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3655 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3656 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3658 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3659 "Const, volatile and restrict are assumed to be a subset of "
3660 "the fast qualifiers.");
3662 bool isConst() const { return getFastTypeQuals().hasConst(); }
3663 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3664 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3666 /// Determine the type of an expression that calls a function of
3668 QualType getCallResultType(const ASTContext &Context) const {
3669 return getReturnType().getNonLValueExprType(Context);
3672 static StringRef getNameForCallConv(CallingConv CC);
3674 static bool classof(const Type *T) {
3675 return T->getTypeClass() == FunctionNoProto ||
3676 T->getTypeClass() == FunctionProto;
3680 /// Represents a K&R-style 'int foo()' function, which has
3681 /// no information available about its arguments.
3682 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3683 friend class ASTContext; // ASTContext creates these.
3685 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3686 : FunctionType(FunctionNoProto, Result, Canonical,
3687 /*Dependent=*/false, /*InstantiationDependent=*/false,
3688 Result->isVariablyModifiedType(),
3689 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3692 // No additional state past what FunctionType provides.
3694 bool isSugared() const { return false; }
3695 QualType desugar() const { return QualType(this, 0); }
3697 void Profile(llvm::FoldingSetNodeID &ID) {
3698 Profile(ID, getReturnType(), getExtInfo());
3701 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3704 ID.AddPointer(ResultType.getAsOpaquePtr());
3707 static bool classof(const Type *T) {
3708 return T->getTypeClass() == FunctionNoProto;
3712 /// Represents a prototype with parameter type info, e.g.
3713 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3714 /// parameters, not as having a single void parameter. Such a type can have
3715 /// an exception specification, but this specification is not part of the
3716 /// canonical type. FunctionProtoType has several trailing objects, some of
3717 /// which optional. For more information about the trailing objects see
3718 /// the first comment inside FunctionProtoType.
3719 class FunctionProtoType final
3720 : public FunctionType,
3721 public llvm::FoldingSetNode,
3722 private llvm::TrailingObjects<
3723 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3724 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3725 FunctionType::ExtParameterInfo, Qualifiers> {
3726 friend class ASTContext; // ASTContext creates these.
3727 friend TrailingObjects;
3729 // FunctionProtoType is followed by several trailing objects, some of
3730 // which optional. They are in order:
3732 // * An array of getNumParams() QualType holding the parameter types.
3733 // Always present. Note that for the vast majority of FunctionProtoType,
3734 // these will be the only trailing objects.
3736 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3737 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3738 // a single FunctionTypeExtraBitfields. Present if and only if
3739 // hasExtraBitfields() is true.
3741 // * Optionally exactly one of:
3742 // * an array of getNumExceptions() ExceptionType,
3743 // * a single Expr *,
3744 // * a pair of FunctionDecl *,
3745 // * a single FunctionDecl *
3746 // used to store information about the various types of exception
3747 // specification. See getExceptionSpecSize for the details.
3749 // * Optionally an array of getNumParams() ExtParameterInfo holding
3750 // an ExtParameterInfo for each of the parameters. Present if and
3751 // only if hasExtParameterInfos() is true.
3753 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3754 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3755 // if hasExtQualifiers() is true.
3757 // The optional FunctionTypeExtraBitfields has to be before the data
3758 // related to the exception specification since it contains the number
3759 // of exception types.
3761 // We put the ExtParameterInfos last. If all were equal, it would make
3762 // more sense to put these before the exception specification, because
3763 // it's much easier to skip past them compared to the elaborate switch
3764 // required to skip the exception specification. However, all is not
3765 // equal; ExtParameterInfos are used to model very uncommon features,
3766 // and it's better not to burden the more common paths.
3769 /// Holds information about the various types of exception specification.
3770 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3771 /// used to group together the various bits of information about the
3772 /// exception specification.
3773 struct ExceptionSpecInfo {
3774 /// The kind of exception specification this is.
3775 ExceptionSpecificationType Type = EST_None;
3777 /// Explicitly-specified list of exception types.
3778 ArrayRef<QualType> Exceptions;
3780 /// Noexcept expression, if this is a computed noexcept specification.
3781 Expr *NoexceptExpr = nullptr;
3783 /// The function whose exception specification this is, for
3784 /// EST_Unevaluated and EST_Uninstantiated.
3785 FunctionDecl *SourceDecl = nullptr;
3787 /// The function template whose exception specification this is instantiated
3788 /// from, for EST_Uninstantiated.
3789 FunctionDecl *SourceTemplate = nullptr;
3791 ExceptionSpecInfo() = default;
3793 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3796 /// Extra information about a function prototype. ExtProtoInfo is not
3797 /// stored as such in FunctionProtoType but is used to group together
3798 /// the various bits of extra information about a function prototype.
3799 struct ExtProtoInfo {
3800 FunctionType::ExtInfo ExtInfo;
3802 bool HasTrailingReturn : 1;
3803 Qualifiers TypeQuals;
3804 RefQualifierKind RefQualifier = RQ_None;
3805 ExceptionSpecInfo ExceptionSpec;
3806 const ExtParameterInfo *ExtParameterInfos = nullptr;
3808 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3810 ExtProtoInfo(CallingConv CC)
3811 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3813 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3814 ExtProtoInfo Result(*this);
3815 Result.ExceptionSpec = ESI;
3821 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3822 return getNumParams();
3825 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3826 return hasExtraBitfields();
3829 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3830 return getExceptionSpecSize().NumExceptionType;
3833 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3834 return getExceptionSpecSize().NumExprPtr;
3837 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3838 return getExceptionSpecSize().NumFunctionDeclPtr;
3841 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3842 return hasExtParameterInfos() ? getNumParams() : 0;
3845 /// Determine whether there are any argument types that
3846 /// contain an unexpanded parameter pack.
3847 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3849 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3850 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3856 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3857 QualType canonical, const ExtProtoInfo &epi);
3859 /// This struct is returned by getExceptionSpecSize and is used to
3860 /// translate an ExceptionSpecificationType to the number and kind
3861 /// of trailing objects related to the exception specification.
3862 struct ExceptionSpecSizeHolder {
3863 unsigned NumExceptionType;
3864 unsigned NumExprPtr;
3865 unsigned NumFunctionDeclPtr;
3868 /// Return the number and kind of trailing objects
3869 /// related to the exception specification.
3870 static ExceptionSpecSizeHolder
3871 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3874 case EST_DynamicNone:
3876 case EST_BasicNoexcept:
3882 return {NumExceptions, 0, 0};
3884 case EST_DependentNoexcept:
3885 case EST_NoexceptFalse:
3886 case EST_NoexceptTrue:
3889 case EST_Uninstantiated:
3892 case EST_Unevaluated:
3895 llvm_unreachable("bad exception specification kind");
3898 /// Return the number and kind of trailing objects
3899 /// related to the exception specification.
3900 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3901 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3904 /// Whether the trailing FunctionTypeExtraBitfields is present.
3905 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3906 // If the exception spec type is EST_Dynamic then we have > 0 exception
3907 // types and the exact number is stored in FunctionTypeExtraBitfields.
3908 return EST == EST_Dynamic;
3911 /// Whether the trailing FunctionTypeExtraBitfields is present.
3912 bool hasExtraBitfields() const {
3913 return hasExtraBitfields(getExceptionSpecType());
3916 bool hasExtQualifiers() const {
3917 return FunctionTypeBits.HasExtQuals;
3921 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3923 QualType getParamType(unsigned i) const {
3924 assert(i < getNumParams() && "invalid parameter index");
3925 return param_type_begin()[i];
3928 ArrayRef<QualType> getParamTypes() const {
3929 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3932 ExtProtoInfo getExtProtoInfo() const {
3934 EPI.ExtInfo = getExtInfo();
3935 EPI.Variadic = isVariadic();
3936 EPI.HasTrailingReturn = hasTrailingReturn();
3937 EPI.ExceptionSpec.Type = getExceptionSpecType();
3938 EPI.TypeQuals = getMethodQuals();
3939 EPI.RefQualifier = getRefQualifier();
3940 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3941 EPI.ExceptionSpec.Exceptions = exceptions();
3942 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3943 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3944 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3945 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3946 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3947 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3948 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3950 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3954 /// Get the kind of exception specification on this function.
3955 ExceptionSpecificationType getExceptionSpecType() const {
3956 return static_cast<ExceptionSpecificationType>(
3957 FunctionTypeBits.ExceptionSpecType);
3960 /// Return whether this function has any kind of exception spec.
3961 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3963 /// Return whether this function has a dynamic (throw) exception spec.
3964 bool hasDynamicExceptionSpec() const {
3965 return isDynamicExceptionSpec(getExceptionSpecType());
3968 /// Return whether this function has a noexcept exception spec.
3969 bool hasNoexceptExceptionSpec() const {
3970 return isNoexceptExceptionSpec(getExceptionSpecType());
3973 /// Return whether this function has a dependent exception spec.
3974 bool hasDependentExceptionSpec() const;
3976 /// Return whether this function has an instantiation-dependent exception
3978 bool hasInstantiationDependentExceptionSpec() const;
3980 /// Return the number of types in the exception specification.
3981 unsigned getNumExceptions() const {
3982 return getExceptionSpecType() == EST_Dynamic
3983 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3988 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3989 QualType getExceptionType(unsigned i) const {
3990 assert(i < getNumExceptions() && "Invalid exception number!");
3991 return exception_begin()[i];
3994 /// Return the expression inside noexcept(expression), or a null pointer
3995 /// if there is none (because the exception spec is not of this form).
3996 Expr *getNoexceptExpr() const {
3997 if (!isComputedNoexcept(getExceptionSpecType()))
3999 return *getTrailingObjects<Expr *>();
4002 /// If this function type has an exception specification which hasn't
4003 /// been determined yet (either because it has not been evaluated or because
4004 /// it has not been instantiated), this is the function whose exception
4005 /// specification is represented by this type.
4006 FunctionDecl *getExceptionSpecDecl() const {
4007 if (getExceptionSpecType() != EST_Uninstantiated &&
4008 getExceptionSpecType() != EST_Unevaluated)
4010 return getTrailingObjects<FunctionDecl *>()[0];
4013 /// If this function type has an uninstantiated exception
4014 /// specification, this is the function whose exception specification
4015 /// should be instantiated to find the exception specification for
4017 FunctionDecl *getExceptionSpecTemplate() const {
4018 if (getExceptionSpecType() != EST_Uninstantiated)
4020 return getTrailingObjects<FunctionDecl *>()[1];
4023 /// Determine whether this function type has a non-throwing exception
4025 CanThrowResult canThrow() const;
4027 /// Determine whether this function type has a non-throwing exception
4028 /// specification. If this depends on template arguments, returns
4029 /// \c ResultIfDependent.
4030 bool isNothrow(bool ResultIfDependent = false) const {
4031 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4034 /// Whether this function prototype is variadic.
4035 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4037 /// Determines whether this function prototype contains a
4038 /// parameter pack at the end.
4040 /// A function template whose last parameter is a parameter pack can be
4041 /// called with an arbitrary number of arguments, much like a variadic
4043 bool isTemplateVariadic() const;
4045 /// Whether this function prototype has a trailing return type.
4046 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4048 Qualifiers getMethodQuals() const {
4049 if (hasExtQualifiers())
4050 return *getTrailingObjects<Qualifiers>();
4052 return getFastTypeQuals();
4055 /// Retrieve the ref-qualifier associated with this function type.
4056 RefQualifierKind getRefQualifier() const {
4057 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4060 using param_type_iterator = const QualType *;
4061 using param_type_range = llvm::iterator_range<param_type_iterator>;
4063 param_type_range param_types() const {
4064 return param_type_range(param_type_begin(), param_type_end());
4067 param_type_iterator param_type_begin() const {
4068 return getTrailingObjects<QualType>();
4071 param_type_iterator param_type_end() const {
4072 return param_type_begin() + getNumParams();
4075 using exception_iterator = const QualType *;
4077 ArrayRef<QualType> exceptions() const {
4078 return llvm::makeArrayRef(exception_begin(), exception_end());
4081 exception_iterator exception_begin() const {
4082 return reinterpret_cast<exception_iterator>(
4083 getTrailingObjects<ExceptionType>());
4086 exception_iterator exception_end() const {
4087 return exception_begin() + getNumExceptions();
4090 /// Is there any interesting extra information for any of the parameters
4091 /// of this function type?
4092 bool hasExtParameterInfos() const {
4093 return FunctionTypeBits.HasExtParameterInfos;
4096 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4097 assert(hasExtParameterInfos());
4098 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4102 /// Return a pointer to the beginning of the array of extra parameter
4103 /// information, if present, or else null if none of the parameters
4104 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4105 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4106 if (!hasExtParameterInfos())
4108 return getTrailingObjects<ExtParameterInfo>();
4111 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4112 assert(I < getNumParams() && "parameter index out of range");
4113 if (hasExtParameterInfos())
4114 return getTrailingObjects<ExtParameterInfo>()[I];
4115 return ExtParameterInfo();
4118 ParameterABI getParameterABI(unsigned I) const {
4119 assert(I < getNumParams() && "parameter index out of range");
4120 if (hasExtParameterInfos())
4121 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4122 return ParameterABI::Ordinary;
4125 bool isParamConsumed(unsigned I) const {
4126 assert(I < getNumParams() && "parameter index out of range");
4127 if (hasExtParameterInfos())
4128 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4132 bool isSugared() const { return false; }
4133 QualType desugar() const { return QualType(this, 0); }
4135 void printExceptionSpecification(raw_ostream &OS,
4136 const PrintingPolicy &Policy) const;
4138 static bool classof(const Type *T) {
4139 return T->getTypeClass() == FunctionProto;
4142 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4143 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4144 param_type_iterator ArgTys, unsigned NumArgs,
4145 const ExtProtoInfo &EPI, const ASTContext &Context,
4149 /// Represents the dependent type named by a dependently-scoped
4150 /// typename using declaration, e.g.
4151 /// using typename Base<T>::foo;
4153 /// Template instantiation turns these into the underlying type.
4154 class UnresolvedUsingType : public Type {
4155 friend class ASTContext; // ASTContext creates these.
4157 UnresolvedUsingTypenameDecl *Decl;
4159 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4160 : Type(UnresolvedUsing, QualType(), true, true, false,
4161 /*ContainsUnexpandedParameterPack=*/false),
4162 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4165 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4167 bool isSugared() const { return false; }
4168 QualType desugar() const { return QualType(this, 0); }
4170 static bool classof(const Type *T) {
4171 return T->getTypeClass() == UnresolvedUsing;
4174 void Profile(llvm::FoldingSetNodeID &ID) {
4175 return Profile(ID, Decl);
4178 static void Profile(llvm::FoldingSetNodeID &ID,
4179 UnresolvedUsingTypenameDecl *D) {
4184 class TypedefType : public Type {
4185 TypedefNameDecl *Decl;
4188 friend class ASTContext; // ASTContext creates these.
4190 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4191 : Type(tc, can, can->isDependentType(),
4192 can->isInstantiationDependentType(),
4193 can->isVariablyModifiedType(),
4194 /*ContainsUnexpandedParameterPack=*/false),
4195 Decl(const_cast<TypedefNameDecl*>(D)) {
4196 assert(!isa<TypedefType>(can) && "Invalid canonical type");
4200 TypedefNameDecl *getDecl() const { return Decl; }
4202 bool isSugared() const { return true; }
4203 QualType desugar() const;
4205 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4208 /// Sugar type that represents a type that was qualified by a qualifier written
4209 /// as a macro invocation.
4210 class MacroQualifiedType : public Type {
4211 friend class ASTContext; // ASTContext creates these.
4213 QualType UnderlyingTy;
4214 const IdentifierInfo *MacroII;
4216 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4217 const IdentifierInfo *MacroII)
4218 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4219 UnderlyingTy->isInstantiationDependentType(),
4220 UnderlyingTy->isVariablyModifiedType(),
4221 UnderlyingTy->containsUnexpandedParameterPack()),
4222 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4223 assert(isa<AttributedType>(UnderlyingTy) &&
4224 "Expected a macro qualified type to only wrap attributed types.");
4228 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4229 QualType getUnderlyingType() const { return UnderlyingTy; }
4231 /// Return this attributed type's modified type with no qualifiers attached to
4233 QualType getModifiedType() const;
4235 bool isSugared() const { return true; }
4236 QualType desugar() const;
4238 static bool classof(const Type *T) {
4239 return T->getTypeClass() == MacroQualified;
4243 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4244 class TypeOfExprType : public Type {
4248 friend class ASTContext; // ASTContext creates these.
4250 TypeOfExprType(Expr *E, QualType can = QualType());
4253 Expr *getUnderlyingExpr() const { return TOExpr; }
4255 /// Remove a single level of sugar.
4256 QualType desugar() const;
4258 /// Returns whether this type directly provides sugar.
4259 bool isSugared() const;
4261 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4264 /// Internal representation of canonical, dependent
4265 /// `typeof(expr)` types.
4267 /// This class is used internally by the ASTContext to manage
4268 /// canonical, dependent types, only. Clients will only see instances
4269 /// of this class via TypeOfExprType nodes.
4270 class DependentTypeOfExprType
4271 : public TypeOfExprType, public llvm::FoldingSetNode {
4272 const ASTContext &Context;
4275 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4276 : TypeOfExprType(E), Context(Context) {}
4278 void Profile(llvm::FoldingSetNodeID &ID) {
4279 Profile(ID, Context, getUnderlyingExpr());
4282 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4286 /// Represents `typeof(type)`, a GCC extension.
4287 class TypeOfType : public Type {
4288 friend class ASTContext; // ASTContext creates these.
4292 TypeOfType(QualType T, QualType can)
4293 : Type(TypeOf, can, T->isDependentType(),
4294 T->isInstantiationDependentType(),
4295 T->isVariablyModifiedType(),
4296 T->containsUnexpandedParameterPack()),
4298 assert(!isa<TypedefType>(can) && "Invalid canonical type");
4302 QualType getUnderlyingType() const { return TOType; }
4304 /// Remove a single level of sugar.
4305 QualType desugar() const { return getUnderlyingType(); }
4307 /// Returns whether this type directly provides sugar.
4308 bool isSugared() const { return true; }
4310 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4313 /// Represents the type `decltype(expr)` (C++11).
4314 class DecltypeType : public Type {
4316 QualType UnderlyingType;
4319 friend class ASTContext; // ASTContext creates these.
4321 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4324 Expr *getUnderlyingExpr() const { return E; }
4325 QualType getUnderlyingType() const { return UnderlyingType; }
4327 /// Remove a single level of sugar.
4328 QualType desugar() const;
4330 /// Returns whether this type directly provides sugar.
4331 bool isSugared() const;
4333 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4336 /// Internal representation of canonical, dependent
4337 /// decltype(expr) types.
4339 /// This class is used internally by the ASTContext to manage
4340 /// canonical, dependent types, only. Clients will only see instances
4341 /// of this class via DecltypeType nodes.
4342 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4343 const ASTContext &Context;
4346 DependentDecltypeType(const ASTContext &Context, Expr *E);
4348 void Profile(llvm::FoldingSetNodeID &ID) {
4349 Profile(ID, Context, getUnderlyingExpr());
4352 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4356 /// A unary type transform, which is a type constructed from another.
4357 class UnaryTransformType : public Type {
4364 /// The untransformed type.
4367 /// The transformed type if not dependent, otherwise the same as BaseType.
4368 QualType UnderlyingType;
4373 friend class ASTContext;
4375 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4376 QualType CanonicalTy);
4379 bool isSugared() const { return !isDependentType(); }
4380 QualType desugar() const { return UnderlyingType; }
4382 QualType getUnderlyingType() const { return UnderlyingType; }
4383 QualType getBaseType() const { return BaseType; }
4385 UTTKind getUTTKind() const { return UKind; }
4387 static bool classof(const Type *T) {
4388 return T->getTypeClass() == UnaryTransform;
4392 /// Internal representation of canonical, dependent
4393 /// __underlying_type(type) types.
4395 /// This class is used internally by the ASTContext to manage
4396 /// canonical, dependent types, only. Clients will only see instances
4397 /// of this class via UnaryTransformType nodes.
4398 class DependentUnaryTransformType : public UnaryTransformType,
4399 public llvm::FoldingSetNode {
4401 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4404 void Profile(llvm::FoldingSetNodeID &ID) {
4405 Profile(ID, getBaseType(), getUTTKind());
4408 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4410 ID.AddPointer(BaseType.getAsOpaquePtr());
4411 ID.AddInteger((unsigned)UKind);
4415 class TagType : public Type {
4416 friend class ASTReader;
4418 /// Stores the TagDecl associated with this type. The decl may point to any
4419 /// TagDecl that declares the entity.
4423 TagType(TypeClass TC, const TagDecl *D, QualType can);
4426 TagDecl *getDecl() const;
4428 /// Determines whether this type is in the process of being defined.
4429 bool isBeingDefined() const;
4431 static bool classof(const Type *T) {
4432 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4436 /// A helper class that allows the use of isa/cast/dyncast
4437 /// to detect TagType objects of structs/unions/classes.
4438 class RecordType : public TagType {
4440 friend class ASTContext; // ASTContext creates these.
4442 explicit RecordType(const RecordDecl *D)
4443 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4444 explicit RecordType(TypeClass TC, RecordDecl *D)
4445 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4448 RecordDecl *getDecl() const {
4449 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4452 /// Recursively check all fields in the record for const-ness. If any field
4453 /// is declared const, return true. Otherwise, return false.
4454 bool hasConstFields() const;
4456 bool isSugared() const { return false; }
4457 QualType desugar() const { return QualType(this, 0); }
4459 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4462 /// A helper class that allows the use of isa/cast/dyncast
4463 /// to detect TagType objects of enums.
4464 class EnumType : public TagType {
4465 friend class ASTContext; // ASTContext creates these.
4467 explicit EnumType(const EnumDecl *D)
4468 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4471 EnumDecl *getDecl() const {
4472 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4475 bool isSugared() const { return false; }
4476 QualType desugar() const { return QualType(this, 0); }
4478 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4481 /// An attributed type is a type to which a type attribute has been applied.
4483 /// The "modified type" is the fully-sugared type to which the attributed
4484 /// type was applied; generally it is not canonically equivalent to the
4485 /// attributed type. The "equivalent type" is the minimally-desugared type
4486 /// which the type is canonically equivalent to.
4488 /// For example, in the following attributed type:
4489 /// int32_t __attribute__((vector_size(16)))
4490 /// - the modified type is the TypedefType for int32_t
4491 /// - the equivalent type is VectorType(16, int32_t)
4492 /// - the canonical type is VectorType(16, int)
4493 class AttributedType : public Type, public llvm::FoldingSetNode {
4495 using Kind = attr::Kind;
4498 friend class ASTContext; // ASTContext creates these
4500 QualType ModifiedType;
4501 QualType EquivalentType;
4503 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4504 QualType equivalent)
4505 : Type(Attributed, canon, equivalent->isDependentType(),
4506 equivalent->isInstantiationDependentType(),
4507 equivalent->isVariablyModifiedType(),
4508 equivalent->containsUnexpandedParameterPack()),
4509 ModifiedType(modified), EquivalentType(equivalent) {
4510 AttributedTypeBits.AttrKind = attrKind;
4514 Kind getAttrKind() const {
4515 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4518 QualType getModifiedType() const { return ModifiedType; }
4519 QualType getEquivalentType() const { return EquivalentType; }
4521 bool isSugared() const { return true; }
4522 QualType desugar() const { return getEquivalentType(); }
4524 /// Does this attribute behave like a type qualifier?
4526 /// A type qualifier adjusts a type to provide specialized rules for
4527 /// a specific object, like the standard const and volatile qualifiers.
4528 /// This includes attributes controlling things like nullability,
4529 /// address spaces, and ARC ownership. The value of the object is still
4530 /// largely described by the modified type.
4532 /// In contrast, many type attributes "rewrite" their modified type to
4533 /// produce a fundamentally different type, not necessarily related in any
4534 /// formalizable way to the original type. For example, calling convention
4535 /// and vector attributes are not simple type qualifiers.
4537 /// Type qualifiers are often, but not always, reflected in the canonical
4539 bool isQualifier() const;
4541 bool isMSTypeSpec() const;
4543 bool isCallingConv() const;
4545 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4547 /// Retrieve the attribute kind corresponding to the given
4548 /// nullability kind.
4549 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4551 case NullabilityKind::NonNull:
4552 return attr::TypeNonNull;
4554 case NullabilityKind::Nullable:
4555 return attr::TypeNullable;
4557 case NullabilityKind::Unspecified:
4558 return attr::TypeNullUnspecified;
4560 llvm_unreachable("Unknown nullability kind.");
4563 /// Strip off the top-level nullability annotation on the given
4564 /// type, if it's there.
4566 /// \param T The type to strip. If the type is exactly an
4567 /// AttributedType specifying nullability (without looking through
4568 /// type sugar), the nullability is returned and this type changed
4569 /// to the underlying modified type.
4571 /// \returns the top-level nullability, if present.
4572 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4574 void Profile(llvm::FoldingSetNodeID &ID) {
4575 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4578 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4579 QualType modified, QualType equivalent) {
4580 ID.AddInteger(attrKind);
4581 ID.AddPointer(modified.getAsOpaquePtr());
4582 ID.AddPointer(equivalent.getAsOpaquePtr());
4585 static bool classof(const Type *T) {
4586 return T->getTypeClass() == Attributed;
4590 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4591 friend class ASTContext; // ASTContext creates these
4593 // Helper data collector for canonical types.
4594 struct CanonicalTTPTInfo {
4595 unsigned Depth : 15;
4596 unsigned ParameterPack : 1;
4597 unsigned Index : 16;
4601 // Info for the canonical type.
4602 CanonicalTTPTInfo CanTTPTInfo;
4604 // Info for the non-canonical type.
4605 TemplateTypeParmDecl *TTPDecl;
4608 /// Build a non-canonical type.
4609 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4610 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4611 /*InstantiationDependent=*/true,
4612 /*VariablyModified=*/false,
4613 Canon->containsUnexpandedParameterPack()),
4616 /// Build the canonical type.
4617 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4618 : Type(TemplateTypeParm, QualType(this, 0),
4620 /*InstantiationDependent=*/true,
4621 /*VariablyModified=*/false, PP) {
4622 CanTTPTInfo.Depth = D;
4623 CanTTPTInfo.Index = I;
4624 CanTTPTInfo.ParameterPack = PP;
4627 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4628 QualType Can = getCanonicalTypeInternal();
4629 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4633 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4634 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4635 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4637 TemplateTypeParmDecl *getDecl() const {
4638 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4641 IdentifierInfo *getIdentifier() const;
4643 bool isSugared() const { return false; }
4644 QualType desugar() const { return QualType(this, 0); }
4646 void Profile(llvm::FoldingSetNodeID &ID) {
4647 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4650 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4651 unsigned Index, bool ParameterPack,
4652 TemplateTypeParmDecl *TTPDecl) {
4653 ID.AddInteger(Depth);
4654 ID.AddInteger(Index);
4655 ID.AddBoolean(ParameterPack);
4656 ID.AddPointer(TTPDecl);
4659 static bool classof(const Type *T) {
4660 return T->getTypeClass() == TemplateTypeParm;
4664 /// Represents the result of substituting a type for a template
4667 /// Within an instantiated template, all template type parameters have
4668 /// been replaced with these. They are used solely to record that a
4669 /// type was originally written as a template type parameter;
4670 /// therefore they are never canonical.
4671 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4672 friend class ASTContext;
4674 // The original type parameter.
4675 const TemplateTypeParmType *Replaced;
4677 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4678 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4679 Canon->isInstantiationDependentType(),
4680 Canon->isVariablyModifiedType(),
4681 Canon->containsUnexpandedParameterPack()),
4685 /// Gets the template parameter that was substituted for.
4686 const TemplateTypeParmType *getReplacedParameter() const {
4690 /// Gets the type that was substituted for the template
4692 QualType getReplacementType() const {
4693 return getCanonicalTypeInternal();
4696 bool isSugared() const { return true; }
4697 QualType desugar() const { return getReplacementType(); }
4699 void Profile(llvm::FoldingSetNodeID &ID) {
4700 Profile(ID, getReplacedParameter(), getReplacementType());
4703 static void Profile(llvm::FoldingSetNodeID &ID,
4704 const TemplateTypeParmType *Replaced,
4705 QualType Replacement) {
4706 ID.AddPointer(Replaced);
4707 ID.AddPointer(Replacement.getAsOpaquePtr());
4710 static bool classof(const Type *T) {
4711 return T->getTypeClass() == SubstTemplateTypeParm;
4715 /// Represents the result of substituting a set of types for a template
4716 /// type parameter pack.
4718 /// When a pack expansion in the source code contains multiple parameter packs
4719 /// and those parameter packs correspond to different levels of template
4720 /// parameter lists, this type node is used to represent a template type
4721 /// parameter pack from an outer level, which has already had its argument pack
4722 /// substituted but that still lives within a pack expansion that itself
4723 /// could not be instantiated. When actually performing a substitution into
4724 /// that pack expansion (e.g., when all template parameters have corresponding
4725 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4726 /// at the current pack substitution index.
4727 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4728 friend class ASTContext;
4730 /// The original type parameter.
4731 const TemplateTypeParmType *Replaced;
4733 /// A pointer to the set of template arguments that this
4734 /// parameter pack is instantiated with.
4735 const TemplateArgument *Arguments;
4737 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4739 const TemplateArgument &ArgPack);
4742 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4744 /// Gets the template parameter that was substituted for.
4745 const TemplateTypeParmType *getReplacedParameter() const {
4749 unsigned getNumArgs() const {
4750 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4753 bool isSugared() const { return false; }
4754 QualType desugar() const { return QualType(this, 0); }
4756 TemplateArgument getArgumentPack() const;
4758 void Profile(llvm::FoldingSetNodeID &ID);
4759 static void Profile(llvm::FoldingSetNodeID &ID,
4760 const TemplateTypeParmType *Replaced,
4761 const TemplateArgument &ArgPack);
4763 static bool classof(const Type *T) {
4764 return T->getTypeClass() == SubstTemplateTypeParmPack;
4768 /// Common base class for placeholders for types that get replaced by
4769 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4770 /// class template types, and (eventually) constrained type names from the C++
4773 /// These types are usually a placeholder for a deduced type. However, before
4774 /// the initializer is attached, or (usually) if the initializer is
4775 /// type-dependent, there is no deduced type and the type is canonical. In
4776 /// the latter case, it is also a dependent type.
4777 class DeducedType : public Type {
4779 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4780 bool IsInstantiationDependent, bool ContainsParameterPack)
4782 // FIXME: Retain the sugared deduced type?
4783 DeducedAsType.isNull() ? QualType(this, 0)
4784 : DeducedAsType.getCanonicalType(),
4785 IsDependent, IsInstantiationDependent,
4786 /*VariablyModified=*/false, ContainsParameterPack) {
4787 if (!DeducedAsType.isNull()) {
4788 if (DeducedAsType->isDependentType())
4790 if (DeducedAsType->isInstantiationDependentType())
4791 setInstantiationDependent();
4792 if (DeducedAsType->containsUnexpandedParameterPack())
4793 setContainsUnexpandedParameterPack();
4798 bool isSugared() const { return !isCanonicalUnqualified(); }
4799 QualType desugar() const { return getCanonicalTypeInternal(); }
4801 /// Get the type deduced for this placeholder type, or null if it's
4802 /// either not been deduced or was deduced to a dependent type.
4803 QualType getDeducedType() const {
4804 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4806 bool isDeduced() const {
4807 return !isCanonicalUnqualified() || isDependentType();
4810 static bool classof(const Type *T) {
4811 return T->getTypeClass() == Auto ||
4812 T->getTypeClass() == DeducedTemplateSpecialization;
4816 /// Represents a C++11 auto or C++14 decltype(auto) type.
4817 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4818 friend class ASTContext; // ASTContext creates these
4820 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4821 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4822 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4823 IsDeducedAsDependent, IsDeducedAsPack) {
4824 AutoTypeBits.Keyword = (unsigned)Keyword;
4828 bool isDecltypeAuto() const {
4829 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4832 AutoTypeKeyword getKeyword() const {
4833 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4836 void Profile(llvm::FoldingSetNodeID &ID) {
4837 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4838 containsUnexpandedParameterPack());
4841 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4842 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4843 ID.AddPointer(Deduced.getAsOpaquePtr());
4844 ID.AddInteger((unsigned)Keyword);
4845 ID.AddBoolean(IsDependent);
4846 ID.AddBoolean(IsPack);
4849 static bool classof(const Type *T) {
4850 return T->getTypeClass() == Auto;
4854 /// Represents a C++17 deduced template specialization type.
4855 class DeducedTemplateSpecializationType : public DeducedType,
4856 public llvm::FoldingSetNode {
4857 friend class ASTContext; // ASTContext creates these
4859 /// The name of the template whose arguments will be deduced.
4860 TemplateName Template;
4862 DeducedTemplateSpecializationType(TemplateName Template,
4863 QualType DeducedAsType,
4864 bool IsDeducedAsDependent)
4865 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4866 IsDeducedAsDependent || Template.isDependent(),
4867 IsDeducedAsDependent || Template.isInstantiationDependent(),
4868 Template.containsUnexpandedParameterPack()),
4869 Template(Template) {}
4872 /// Retrieve the name of the template that we are deducing.
4873 TemplateName getTemplateName() const { return Template;}
4875 void Profile(llvm::FoldingSetNodeID &ID) {
4876 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4879 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4880 QualType Deduced, bool IsDependent) {
4881 Template.Profile(ID);
4882 ID.AddPointer(Deduced.getAsOpaquePtr());
4883 ID.AddBoolean(IsDependent);
4886 static bool classof(const Type *T) {
4887 return T->getTypeClass() == DeducedTemplateSpecialization;
4891 /// Represents a type template specialization; the template
4892 /// must be a class template, a type alias template, or a template
4893 /// template parameter. A template which cannot be resolved to one of
4894 /// these, e.g. because it is written with a dependent scope
4895 /// specifier, is instead represented as a
4896 /// @c DependentTemplateSpecializationType.
4898 /// A non-dependent template specialization type is always "sugar",
4899 /// typically for a \c RecordType. For example, a class template
4900 /// specialization type of \c vector<int> will refer to a tag type for
4901 /// the instantiation \c std::vector<int, std::allocator<int>>
4903 /// Template specializations are dependent if either the template or
4904 /// any of the template arguments are dependent, in which case the
4905 /// type may also be canonical.
4907 /// Instances of this type are allocated with a trailing array of
4908 /// TemplateArguments, followed by a QualType representing the
4909 /// non-canonical aliased type when the template is a type alias
4911 class alignas(8) TemplateSpecializationType
4913 public llvm::FoldingSetNode {
4914 friend class ASTContext; // ASTContext creates these
4916 /// The name of the template being specialized. This is
4917 /// either a TemplateName::Template (in which case it is a
4918 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4919 /// TypeAliasTemplateDecl*), a
4920 /// TemplateName::SubstTemplateTemplateParmPack, or a
4921 /// TemplateName::SubstTemplateTemplateParm (in which case the
4922 /// replacement must, recursively, be one of these).
4923 TemplateName Template;
4925 TemplateSpecializationType(TemplateName T,
4926 ArrayRef<TemplateArgument> Args,
4931 /// Determine whether any of the given template arguments are dependent.
4932 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4933 bool &InstantiationDependent);
4935 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4936 bool &InstantiationDependent);
4938 /// True if this template specialization type matches a current
4939 /// instantiation in the context in which it is found.
4940 bool isCurrentInstantiation() const {
4941 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4944 /// Determine if this template specialization type is for a type alias
4945 /// template that has been substituted.
4947 /// Nearly every template specialization type whose template is an alias
4948 /// template will be substituted. However, this is not the case when
4949 /// the specialization contains a pack expansion but the template alias
4950 /// does not have a corresponding parameter pack, e.g.,
4953 /// template<typename T, typename U, typename V> struct S;
4954 /// template<typename T, typename U> using A = S<T, int, U>;
4955 /// template<typename... Ts> struct X {
4956 /// typedef A<Ts...> type; // not a type alias
4959 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4961 /// Get the aliased type, if this is a specialization of a type alias
4963 QualType getAliasedType() const {
4964 assert(isTypeAlias() && "not a type alias template specialization");
4965 return *reinterpret_cast<const QualType*>(end());
4968 using iterator = const TemplateArgument *;
4970 iterator begin() const { return getArgs(); }
4971 iterator end() const; // defined inline in TemplateBase.h
4973 /// Retrieve the name of the template that we are specializing.
4974 TemplateName getTemplateName() const { return Template; }
4976 /// Retrieve the template arguments.
4977 const TemplateArgument *getArgs() const {
4978 return reinterpret_cast<const TemplateArgument *>(this + 1);
4981 /// Retrieve the number of template arguments.
4982 unsigned getNumArgs() const {
4983 return TemplateSpecializationTypeBits.NumArgs;
4986 /// Retrieve a specific template argument as a type.
4987 /// \pre \c isArgType(Arg)
4988 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4990 ArrayRef<TemplateArgument> template_arguments() const {
4991 return {getArgs(), getNumArgs()};
4994 bool isSugared() const {
4995 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4998 QualType desugar() const {
4999 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5002 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5003 Profile(ID, Template, template_arguments(), Ctx);
5005 getAliasedType().Profile(ID);
5008 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5009 ArrayRef<TemplateArgument> Args,
5010 const ASTContext &Context);
5012 static bool classof(const Type *T) {
5013 return T->getTypeClass() == TemplateSpecialization;
5017 /// Print a template argument list, including the '<' and '>'
5018 /// enclosing the template arguments.
5019 void printTemplateArgumentList(raw_ostream &OS,
5020 ArrayRef<TemplateArgument> Args,
5021 const PrintingPolicy &Policy);
5023 void printTemplateArgumentList(raw_ostream &OS,
5024 ArrayRef<TemplateArgumentLoc> Args,
5025 const PrintingPolicy &Policy);
5027 void printTemplateArgumentList(raw_ostream &OS,
5028 const TemplateArgumentListInfo &Args,
5029 const PrintingPolicy &Policy);
5031 /// The injected class name of a C++ class template or class
5032 /// template partial specialization. Used to record that a type was
5033 /// spelled with a bare identifier rather than as a template-id; the
5034 /// equivalent for non-templated classes is just RecordType.
5036 /// Injected class name types are always dependent. Template
5037 /// instantiation turns these into RecordTypes.
5039 /// Injected class name types are always canonical. This works
5040 /// because it is impossible to compare an injected class name type
5041 /// with the corresponding non-injected template type, for the same
5042 /// reason that it is impossible to directly compare template
5043 /// parameters from different dependent contexts: injected class name
5044 /// types can only occur within the scope of a particular templated
5045 /// declaration, and within that scope every template specialization
5046 /// will canonicalize to the injected class name (when appropriate
5047 /// according to the rules of the language).
5048 class InjectedClassNameType : public Type {
5049 friend class ASTContext; // ASTContext creates these.
5050 friend class ASTNodeImporter;
5051 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5052 // currently suitable for AST reading, too much
5053 // interdependencies.
5055 CXXRecordDecl *Decl;
5057 /// The template specialization which this type represents.
5059 /// template <class T> class A { ... };
5060 /// this is A<T>, whereas in
5061 /// template <class X, class Y> class A<B<X,Y> > { ... };
5062 /// this is A<B<X,Y> >.
5064 /// It is always unqualified, always a template specialization type,
5065 /// and always dependent.
5066 QualType InjectedType;
5068 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5069 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5070 /*InstantiationDependent=*/true,
5071 /*VariablyModified=*/false,
5072 /*ContainsUnexpandedParameterPack=*/false),
5073 Decl(D), InjectedType(TST) {
5074 assert(isa<TemplateSpecializationType>(TST));
5075 assert(!TST.hasQualifiers());
5076 assert(TST->isDependentType());
5080 QualType getInjectedSpecializationType() const { return InjectedType; }
5082 const TemplateSpecializationType *getInjectedTST() const {
5083 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5086 TemplateName getTemplateName() const {
5087 return getInjectedTST()->getTemplateName();
5090 CXXRecordDecl *getDecl() const;
5092 bool isSugared() const { return false; }
5093 QualType desugar() const { return QualType(this, 0); }
5095 static bool classof(const Type *T) {
5096 return T->getTypeClass() == InjectedClassName;
5100 /// The kind of a tag type.
5102 /// The "struct" keyword.
5105 /// The "__interface" keyword.
5108 /// The "union" keyword.
5111 /// The "class" keyword.
5114 /// The "enum" keyword.
5118 /// The elaboration keyword that precedes a qualified type name or
5119 /// introduces an elaborated-type-specifier.
5120 enum ElaboratedTypeKeyword {
5121 /// The "struct" keyword introduces the elaborated-type-specifier.
5124 /// The "__interface" keyword introduces the elaborated-type-specifier.
5127 /// The "union" keyword introduces the elaborated-type-specifier.
5130 /// The "class" keyword introduces the elaborated-type-specifier.
5133 /// The "enum" keyword introduces the elaborated-type-specifier.
5136 /// The "typename" keyword precedes the qualified type name, e.g.,
5137 /// \c typename T::type.
5140 /// No keyword precedes the qualified type name.
5144 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
5145 /// The keyword in stored in the free bits of the base class.
5146 /// Also provides a few static helpers for converting and printing
5147 /// elaborated type keyword and tag type kind enumerations.
5148 class TypeWithKeyword : public Type {
5150 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5151 QualType Canonical, bool Dependent,
5152 bool InstantiationDependent, bool VariablyModified,
5153 bool ContainsUnexpandedParameterPack)
5154 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5155 ContainsUnexpandedParameterPack) {
5156 TypeWithKeywordBits.Keyword = Keyword;
5160 ElaboratedTypeKeyword getKeyword() const {
5161 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5164 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5165 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5167 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5168 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5169 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5171 /// Converts a TagTypeKind into an elaborated type keyword.
5172 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5174 /// Converts an elaborated type keyword into a TagTypeKind.
5175 /// It is an error to provide an elaborated type keyword
5176 /// which *isn't* a tag kind here.
5177 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5179 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5181 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5183 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5184 return getKeywordName(getKeywordForTagTypeKind(Kind));
5187 class CannotCastToThisType {};
5188 static CannotCastToThisType classof(const Type *);
5191 /// Represents a type that was referred to using an elaborated type
5192 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5195 /// This type is used to keep track of a type name as written in the
5196 /// source code, including tag keywords and any nested-name-specifiers.
5197 /// The type itself is always "sugar", used to express what was written
5198 /// in the source code but containing no additional semantic information.
5199 class ElaboratedType final
5200 : public TypeWithKeyword,
5201 public llvm::FoldingSetNode,
5202 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5203 friend class ASTContext; // ASTContext creates these
5204 friend TrailingObjects;
5206 /// The nested name specifier containing the qualifier.
5207 NestedNameSpecifier *NNS;
5209 /// The type that this qualified name refers to.
5212 /// The (re)declaration of this tag type owned by this occurrence is stored
5213 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5214 /// it, or obtain a null pointer if there is none.
5216 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5217 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5218 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5219 NamedType->isDependentType(),
5220 NamedType->isInstantiationDependentType(),
5221 NamedType->isVariablyModifiedType(),
5222 NamedType->containsUnexpandedParameterPack()),
5223 NNS(NNS), NamedType(NamedType) {
5224 ElaboratedTypeBits.HasOwnedTagDecl = false;
5226 ElaboratedTypeBits.HasOwnedTagDecl = true;
5227 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5229 assert(!(Keyword == ETK_None && NNS == nullptr) &&
5230 "ElaboratedType cannot have elaborated type keyword "
5231 "and name qualifier both null.");
5235 /// Retrieve the qualification on this type.
5236 NestedNameSpecifier *getQualifier() const { return NNS; }
5238 /// Retrieve the type named by the qualified-id.
5239 QualType getNamedType() const { return NamedType; }
5241 /// Remove a single level of sugar.
5242 QualType desugar() const { return getNamedType(); }
5244 /// Returns whether this type directly provides sugar.
5245 bool isSugared() const { return true; }
5247 /// Return the (re)declaration of this type owned by this occurrence of this
5248 /// type, or nullptr if there is none.
5249 TagDecl *getOwnedTagDecl() const {
5250 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5254 void Profile(llvm::FoldingSetNodeID &ID) {
5255 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5258 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5259 NestedNameSpecifier *NNS, QualType NamedType,
5260 TagDecl *OwnedTagDecl) {
5261 ID.AddInteger(Keyword);
5263 NamedType.Profile(ID);
5264 ID.AddPointer(OwnedTagDecl);
5267 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5270 /// Represents a qualified type name for which the type name is
5273 /// DependentNameType represents a class of dependent types that involve a
5274 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5275 /// name of a type. The DependentNameType may start with a "typename" (for a
5276 /// typename-specifier), "class", "struct", "union", or "enum" (for a
5277 /// dependent elaborated-type-specifier), or nothing (in contexts where we
5278 /// know that we must be referring to a type, e.g., in a base class specifier).
5279 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5280 /// mode, this type is used with non-dependent names to delay name lookup until
5282 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5283 friend class ASTContext; // ASTContext creates these
5285 /// The nested name specifier containing the qualifier.
5286 NestedNameSpecifier *NNS;
5288 /// The type that this typename specifier refers to.
5289 const IdentifierInfo *Name;
5291 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5292 const IdentifierInfo *Name, QualType CanonType)
5293 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5294 /*InstantiationDependent=*/true,
5295 /*VariablyModified=*/false,
5296 NNS->containsUnexpandedParameterPack()),
5297 NNS(NNS), Name(Name) {}
5300 /// Retrieve the qualification on this type.
5301 NestedNameSpecifier *getQualifier() const { return NNS; }
5303 /// Retrieve the type named by the typename specifier as an identifier.
5305 /// This routine will return a non-NULL identifier pointer when the
5306 /// form of the original typename was terminated by an identifier,
5307 /// e.g., "typename T::type".
5308 const IdentifierInfo *getIdentifier() const {
5312 bool isSugared() const { return false; }
5313 QualType desugar() const { return QualType(this, 0); }
5315 void Profile(llvm::FoldingSetNodeID &ID) {
5316 Profile(ID, getKeyword(), NNS, Name);
5319 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5320 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5321 ID.AddInteger(Keyword);
5323 ID.AddPointer(Name);
5326 static bool classof(const Type *T) {
5327 return T->getTypeClass() == DependentName;
5331 /// Represents a template specialization type whose template cannot be
5333 /// A<T>::template B<T>
5334 class alignas(8) DependentTemplateSpecializationType
5335 : public TypeWithKeyword,
5336 public llvm::FoldingSetNode {
5337 friend class ASTContext; // ASTContext creates these
5339 /// The nested name specifier containing the qualifier.
5340 NestedNameSpecifier *NNS;
5342 /// The identifier of the template.
5343 const IdentifierInfo *Name;
5345 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5346 NestedNameSpecifier *NNS,
5347 const IdentifierInfo *Name,
5348 ArrayRef<TemplateArgument> Args,
5351 const TemplateArgument *getArgBuffer() const {
5352 return reinterpret_cast<const TemplateArgument*>(this+1);
5355 TemplateArgument *getArgBuffer() {
5356 return reinterpret_cast<TemplateArgument*>(this+1);
5360 NestedNameSpecifier *getQualifier() const { return NNS; }
5361 const IdentifierInfo *getIdentifier() const { return Name; }
5363 /// Retrieve the template arguments.
5364 const TemplateArgument *getArgs() const {
5365 return getArgBuffer();
5368 /// Retrieve the number of template arguments.
5369 unsigned getNumArgs() const {
5370 return DependentTemplateSpecializationTypeBits.NumArgs;
5373 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5375 ArrayRef<TemplateArgument> template_arguments() const {
5376 return {getArgs(), getNumArgs()};
5379 using iterator = const TemplateArgument *;
5381 iterator begin() const { return getArgs(); }
5382 iterator end() const; // inline in TemplateBase.h
5384 bool isSugared() const { return false; }
5385 QualType desugar() const { return QualType(this, 0); }
5387 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5388 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5391 static void Profile(llvm::FoldingSetNodeID &ID,
5392 const ASTContext &Context,
5393 ElaboratedTypeKeyword Keyword,
5394 NestedNameSpecifier *Qualifier,
5395 const IdentifierInfo *Name,
5396 ArrayRef<TemplateArgument> Args);
5398 static bool classof(const Type *T) {
5399 return T->getTypeClass() == DependentTemplateSpecialization;
5403 /// Represents a pack expansion of types.
5405 /// Pack expansions are part of C++11 variadic templates. A pack
5406 /// expansion contains a pattern, which itself contains one or more
5407 /// "unexpanded" parameter packs. When instantiated, a pack expansion
5408 /// produces a series of types, each instantiated from the pattern of
5409 /// the expansion, where the Ith instantiation of the pattern uses the
5410 /// Ith arguments bound to each of the unexpanded parameter packs. The
5411 /// pack expansion is considered to "expand" these unexpanded
5412 /// parameter packs.
5415 /// template<typename ...Types> struct tuple;
5417 /// template<typename ...Types>
5418 /// struct tuple_of_references {
5419 /// typedef tuple<Types&...> type;
5423 /// Here, the pack expansion \c Types&... is represented via a
5424 /// PackExpansionType whose pattern is Types&.
5425 class PackExpansionType : public Type, public llvm::FoldingSetNode {
5426 friend class ASTContext; // ASTContext creates these
5428 /// The pattern of the pack expansion.
5431 PackExpansionType(QualType Pattern, QualType Canon,
5432 Optional<unsigned> NumExpansions)
5433 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5434 /*InstantiationDependent=*/true,
5435 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5436 /*ContainsUnexpandedParameterPack=*/false),
5438 PackExpansionTypeBits.NumExpansions =
5439 NumExpansions ? *NumExpansions + 1 : 0;
5443 /// Retrieve the pattern of this pack expansion, which is the
5444 /// type that will be repeatedly instantiated when instantiating the
5445 /// pack expansion itself.
5446 QualType getPattern() const { return Pattern; }
5448 /// Retrieve the number of expansions that this pack expansion will
5449 /// generate, if known.
5450 Optional<unsigned> getNumExpansions() const {
5451 if (PackExpansionTypeBits.NumExpansions)
5452 return PackExpansionTypeBits.NumExpansions - 1;
5456 bool isSugared() const { return !Pattern->isDependentType(); }
5457 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5459 void Profile(llvm::FoldingSetNodeID &ID) {
5460 Profile(ID, getPattern(), getNumExpansions());
5463 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5464 Optional<unsigned> NumExpansions) {
5465 ID.AddPointer(Pattern.getAsOpaquePtr());
5466 ID.AddBoolean(NumExpansions.hasValue());
5468 ID.AddInteger(*NumExpansions);
5471 static bool classof(const Type *T) {
5472 return T->getTypeClass() == PackExpansion;
5476 /// This class wraps the list of protocol qualifiers. For types that can
5477 /// take ObjC protocol qualifers, they can subclass this class.
5479 class ObjCProtocolQualifiers {
5481 ObjCProtocolQualifiers() = default;
5483 ObjCProtocolDecl * const *getProtocolStorage() const {
5484 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5487 ObjCProtocolDecl **getProtocolStorage() {
5488 return static_cast<T*>(this)->getProtocolStorageImpl();
5491 void setNumProtocols(unsigned N) {
5492 static_cast<T*>(this)->setNumProtocolsImpl(N);
5495 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5496 setNumProtocols(protocols.size());
5497 assert(getNumProtocols() == protocols.size() &&
5498 "bitfield overflow in protocol count");
5499 if (!protocols.empty())
5500 memcpy(getProtocolStorage(), protocols.data(),
5501 protocols.size() * sizeof(ObjCProtocolDecl*));
5505 using qual_iterator = ObjCProtocolDecl * const *;
5506 using qual_range = llvm::iterator_range<qual_iterator>;
5508 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5509 qual_iterator qual_begin() const { return getProtocolStorage(); }
5510 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5512 bool qual_empty() const { return getNumProtocols() == 0; }
5514 /// Return the number of qualifying protocols in this type, or 0 if
5516 unsigned getNumProtocols() const {
5517 return static_cast<const T*>(this)->getNumProtocolsImpl();
5520 /// Fetch a protocol by index.
5521 ObjCProtocolDecl *getProtocol(unsigned I) const {
5522 assert(I < getNumProtocols() && "Out-of-range protocol access");
5523 return qual_begin()[I];
5526 /// Retrieve all of the protocol qualifiers.
5527 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5528 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5532 /// Represents a type parameter type in Objective C. It can take
5533 /// a list of protocols.
5534 class ObjCTypeParamType : public Type,
5535 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5536 public llvm::FoldingSetNode {
5537 friend class ASTContext;
5538 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5540 /// The number of protocols stored on this type.
5541 unsigned NumProtocols : 6;
5543 ObjCTypeParamDecl *OTPDecl;
5545 /// The protocols are stored after the ObjCTypeParamType node. In the
5546 /// canonical type, the list of protocols are sorted alphabetically
5548 ObjCProtocolDecl **getProtocolStorageImpl();
5550 /// Return the number of qualifying protocols in this interface type,
5551 /// or 0 if there are none.
5552 unsigned getNumProtocolsImpl() const {
5553 return NumProtocols;
5556 void setNumProtocolsImpl(unsigned N) {
5560 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5562 ArrayRef<ObjCProtocolDecl *> protocols);
5565 bool isSugared() const { return true; }
5566 QualType desugar() const { return getCanonicalTypeInternal(); }
5568 static bool classof(const Type *T) {
5569 return T->getTypeClass() == ObjCTypeParam;
5572 void Profile(llvm::FoldingSetNodeID &ID);
5573 static void Profile(llvm::FoldingSetNodeID &ID,
5574 const ObjCTypeParamDecl *OTPDecl,
5575 ArrayRef<ObjCProtocolDecl *> protocols);
5577 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5580 /// Represents a class type in Objective C.
5582 /// Every Objective C type is a combination of a base type, a set of
5583 /// type arguments (optional, for parameterized classes) and a list of
5586 /// Given the following declarations:
5592 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5593 /// with base C and no protocols.
5595 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5596 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5598 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5599 /// and protocol list [P].
5601 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5602 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5603 /// and no protocols.
5605 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5606 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5607 /// this should get its own sugar class to better represent the source.
5608 class ObjCObjectType : public Type,
5609 public ObjCProtocolQualifiers<ObjCObjectType> {
5610 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5612 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5613 // after the ObjCObjectPointerType node.
5614 // ObjCObjectType.NumProtocols - the number of protocols stored
5615 // after the type arguments of ObjCObjectPointerType node.
5617 // These protocols are those written directly on the type. If
5618 // protocol qualifiers ever become additive, the iterators will need
5619 // to get kindof complicated.
5621 // In the canonical object type, these are sorted alphabetically
5624 /// Either a BuiltinType or an InterfaceType or sugar for either.
5627 /// Cached superclass type.
5628 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5629 CachedSuperClassType;
5631 QualType *getTypeArgStorage();
5632 const QualType *getTypeArgStorage() const {
5633 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5636 ObjCProtocolDecl **getProtocolStorageImpl();
5637 /// Return the number of qualifying protocols in this interface type,
5638 /// or 0 if there are none.
5639 unsigned getNumProtocolsImpl() const {
5640 return ObjCObjectTypeBits.NumProtocols;
5642 void setNumProtocolsImpl(unsigned N) {
5643 ObjCObjectTypeBits.NumProtocols = N;
5647 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5649 ObjCObjectType(QualType Canonical, QualType Base,
5650 ArrayRef<QualType> typeArgs,
5651 ArrayRef<ObjCProtocolDecl *> protocols,
5654 ObjCObjectType(enum Nonce_ObjCInterface)
5655 : Type(ObjCInterface, QualType(), false, false, false, false),
5656 BaseType(QualType(this_(), 0)) {
5657 ObjCObjectTypeBits.NumProtocols = 0;
5658 ObjCObjectTypeBits.NumTypeArgs = 0;
5659 ObjCObjectTypeBits.IsKindOf = 0;
5662 void computeSuperClassTypeSlow() const;
5665 /// Gets the base type of this object type. This is always (possibly
5666 /// sugar for) one of:
5667 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5668 /// user, which is a typedef for an ObjCObjectPointerType)
5669 /// - the 'Class' builtin type (same caveat)
5670 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5671 QualType getBaseType() const { return BaseType; }
5673 bool isObjCId() const {
5674 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5677 bool isObjCClass() const {
5678 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5681 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5682 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5683 bool isObjCUnqualifiedIdOrClass() const {
5684 if (!qual_empty()) return false;
5685 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5686 return T->getKind() == BuiltinType::ObjCId ||
5687 T->getKind() == BuiltinType::ObjCClass;
5690 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5691 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5693 /// Gets the interface declaration for this object type, if the base type
5694 /// really is an interface.
5695 ObjCInterfaceDecl *getInterface() const;
5697 /// Determine whether this object type is "specialized", meaning
5698 /// that it has type arguments.
5699 bool isSpecialized() const;
5701 /// Determine whether this object type was written with type arguments.
5702 bool isSpecializedAsWritten() const {
5703 return ObjCObjectTypeBits.NumTypeArgs > 0;
5706 /// Determine whether this object type is "unspecialized", meaning
5707 /// that it has no type arguments.
5708 bool isUnspecialized() const { return !isSpecialized(); }
5710 /// Determine whether this object type is "unspecialized" as
5711 /// written, meaning that it has no type arguments.
5712 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5714 /// Retrieve the type arguments of this object type (semantically).
5715 ArrayRef<QualType> getTypeArgs() const;
5717 /// Retrieve the type arguments of this object type as they were
5719 ArrayRef<QualType> getTypeArgsAsWritten() const {
5720 return llvm::makeArrayRef(getTypeArgStorage(),
5721 ObjCObjectTypeBits.NumTypeArgs);
5724 /// Whether this is a "__kindof" type as written.
5725 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5727 /// Whether this ia a "__kindof" type (semantically).
5728 bool isKindOfType() const;
5730 /// Retrieve the type of the superclass of this object type.
5732 /// This operation substitutes any type arguments into the
5733 /// superclass of the current class type, potentially producing a
5734 /// specialization of the superclass type. Produces a null type if
5735 /// there is no superclass.
5736 QualType getSuperClassType() const {
5737 if (!CachedSuperClassType.getInt())
5738 computeSuperClassTypeSlow();
5740 assert(CachedSuperClassType.getInt() && "Superclass not set?");
5741 return QualType(CachedSuperClassType.getPointer(), 0);
5744 /// Strip off the Objective-C "kindof" type and (with it) any
5745 /// protocol qualifiers.
5746 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5748 bool isSugared() const { return false; }
5749 QualType desugar() const { return QualType(this, 0); }
5751 static bool classof(const Type *T) {
5752 return T->getTypeClass() == ObjCObject ||
5753 T->getTypeClass() == ObjCInterface;
5757 /// A class providing a concrete implementation
5758 /// of ObjCObjectType, so as to not increase the footprint of
5759 /// ObjCInterfaceType. Code outside of ASTContext and the core type
5760 /// system should not reference this type.
5761 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5762 friend class ASTContext;
5764 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5765 // will need to be modified.
5767 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5768 ArrayRef<QualType> typeArgs,
5769 ArrayRef<ObjCProtocolDecl *> protocols,
5771 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5774 void Profile(llvm::FoldingSetNodeID &ID);
5775 static void Profile(llvm::FoldingSetNodeID &ID,
5777 ArrayRef<QualType> typeArgs,
5778 ArrayRef<ObjCProtocolDecl *> protocols,
5782 inline QualType *ObjCObjectType::getTypeArgStorage() {
5783 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5786 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5787 return reinterpret_cast<ObjCProtocolDecl**>(
5788 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5791 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5792 return reinterpret_cast<ObjCProtocolDecl**>(
5793 static_cast<ObjCTypeParamType*>(this)+1);
5796 /// Interfaces are the core concept in Objective-C for object oriented design.
5797 /// They basically correspond to C++ classes. There are two kinds of interface
5798 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5799 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5801 /// ObjCInterfaceType guarantees the following properties when considered
5802 /// as a subtype of its superclass, ObjCObjectType:
5803 /// - There are no protocol qualifiers. To reinforce this, code which
5804 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5805 /// fail to compile.
5806 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5807 /// T->getBaseType() == QualType(T, 0).
5808 class ObjCInterfaceType : public ObjCObjectType {
5809 friend class ASTContext; // ASTContext creates these.
5810 friend class ASTReader;
5811 friend class ObjCInterfaceDecl;
5813 mutable ObjCInterfaceDecl *Decl;
5815 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5816 : ObjCObjectType(Nonce_ObjCInterface),
5817 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5820 /// Get the declaration of this interface.
5821 ObjCInterfaceDecl *getDecl() const { return Decl; }
5823 bool isSugared() const { return false; }
5824 QualType desugar() const { return QualType(this, 0); }
5826 static bool classof(const Type *T) {
5827 return T->getTypeClass() == ObjCInterface;
5830 // Nonsense to "hide" certain members of ObjCObjectType within this
5831 // class. People asking for protocols on an ObjCInterfaceType are
5832 // not going to get what they want: ObjCInterfaceTypes are
5833 // guaranteed to have no protocols.
5843 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5844 QualType baseType = getBaseType();
5845 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5846 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5847 return T->getDecl();
5849 baseType = ObjT->getBaseType();
5855 /// Represents a pointer to an Objective C object.
5857 /// These are constructed from pointer declarators when the pointee type is
5858 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5859 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5860 /// and 'Class<P>' are translated into these.
5862 /// Pointers to pointers to Objective C objects are still PointerTypes;
5863 /// only the first level of pointer gets it own type implementation.
5864 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5865 friend class ASTContext; // ASTContext creates these.
5867 QualType PointeeType;
5869 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5870 : Type(ObjCObjectPointer, Canonical,
5871 Pointee->isDependentType(),
5872 Pointee->isInstantiationDependentType(),
5873 Pointee->isVariablyModifiedType(),
5874 Pointee->containsUnexpandedParameterPack()),
5875 PointeeType(Pointee) {}
5878 /// Gets the type pointed to by this ObjC pointer.
5879 /// The result will always be an ObjCObjectType or sugar thereof.
5880 QualType getPointeeType() const { return PointeeType; }
5882 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5884 /// This method is equivalent to getPointeeType() except that
5885 /// it discards any typedefs (or other sugar) between this
5886 /// type and the "outermost" object type. So for:
5888 /// \@class A; \@protocol P; \@protocol Q;
5889 /// typedef A<P> AP;
5891 /// typedef A1<P> A1P;
5892 /// typedef A1P<Q> A1PQ;
5894 /// For 'A*', getObjectType() will return 'A'.
5895 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5896 /// For 'AP*', getObjectType() will return 'A<P>'.
5897 /// For 'A1*', getObjectType() will return 'A'.
5898 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5899 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5900 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5901 /// adding protocols to a protocol-qualified base discards the
5902 /// old qualifiers (for now). But if it didn't, getObjectType()
5903 /// would return 'A1P<Q>' (and we'd have to make iterating over
5904 /// qualifiers more complicated).
5905 const ObjCObjectType *getObjectType() const {
5906 return PointeeType->castAs<ObjCObjectType>();
5909 /// If this pointer points to an Objective C
5910 /// \@interface type, gets the type for that interface. Any protocol
5911 /// qualifiers on the interface are ignored.
5913 /// \return null if the base type for this pointer is 'id' or 'Class'
5914 const ObjCInterfaceType *getInterfaceType() const;
5916 /// If this pointer points to an Objective \@interface
5917 /// type, gets the declaration for that interface.
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 ObjCInterfaceDecl *getInterfaceDecl() const {
5921 return getObjectType()->getInterface();
5924 /// True if this is equivalent to the 'id' type, i.e. if
5925 /// its object type is the primitive 'id' type with no protocols.
5926 bool isObjCIdType() const {
5927 return getObjectType()->isObjCUnqualifiedId();
5930 /// True if this is equivalent to the 'Class' type,
5931 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5932 bool isObjCClassType() const {
5933 return getObjectType()->isObjCUnqualifiedClass();
5936 /// True if this is equivalent to the 'id' or 'Class' type,
5937 bool isObjCIdOrClassType() const {
5938 return getObjectType()->isObjCUnqualifiedIdOrClass();
5941 /// True if this is equivalent to 'id<P>' for some non-empty set of
5943 bool isObjCQualifiedIdType() const {
5944 return getObjectType()->isObjCQualifiedId();
5947 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5949 bool isObjCQualifiedClassType() const {
5950 return getObjectType()->isObjCQualifiedClass();
5953 /// Whether this is a "__kindof" type.
5954 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5956 /// Whether this type is specialized, meaning that it has type arguments.
5957 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5959 /// Whether this type is specialized, meaning that it has type arguments.
5960 bool isSpecializedAsWritten() const {
5961 return getObjectType()->isSpecializedAsWritten();
5964 /// Whether this type is unspecialized, meaning that is has no type arguments.
5965 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5967 /// Determine whether this object type is "unspecialized" as
5968 /// written, meaning that it has no type arguments.
5969 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5971 /// Retrieve the type arguments for this type.
5972 ArrayRef<QualType> getTypeArgs() const {
5973 return getObjectType()->getTypeArgs();
5976 /// Retrieve the type arguments for this type.
5977 ArrayRef<QualType> getTypeArgsAsWritten() const {
5978 return getObjectType()->getTypeArgsAsWritten();
5981 /// An iterator over the qualifiers on the object type. Provided
5982 /// for convenience. This will always iterate over the full set of
5983 /// protocols on a type, not just those provided directly.
5984 using qual_iterator = ObjCObjectType::qual_iterator;
5985 using qual_range = llvm::iterator_range<qual_iterator>;
5987 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5989 qual_iterator qual_begin() const {
5990 return getObjectType()->qual_begin();
5993 qual_iterator qual_end() const {
5994 return getObjectType()->qual_end();
5997 bool qual_empty() const { return getObjectType()->qual_empty(); }
5999 /// Return the number of qualifying protocols on the object type.
6000 unsigned getNumProtocols() const {
6001 return getObjectType()->getNumProtocols();
6004 /// Retrieve a qualifying protocol by index on the object type.
6005 ObjCProtocolDecl *getProtocol(unsigned I) const {
6006 return getObjectType()->getProtocol(I);
6009 bool isSugared() const { return false; }
6010 QualType desugar() const { return QualType(this, 0); }
6012 /// Retrieve the type of the superclass of this object pointer type.
6014 /// This operation substitutes any type arguments into the
6015 /// superclass of the current class type, potentially producing a
6016 /// pointer to a specialization of the superclass type. Produces a
6017 /// null type if there is no superclass.
6018 QualType getSuperClassType() const;
6020 /// Strip off the Objective-C "kindof" type and (with it) any
6021 /// protocol qualifiers.
6022 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6023 const ASTContext &ctx) const;
6025 void Profile(llvm::FoldingSetNodeID &ID) {
6026 Profile(ID, getPointeeType());
6029 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6030 ID.AddPointer(T.getAsOpaquePtr());
6033 static bool classof(const Type *T) {
6034 return T->getTypeClass() == ObjCObjectPointer;
6038 class AtomicType : public Type, public llvm::FoldingSetNode {
6039 friend class ASTContext; // ASTContext creates these.
6043 AtomicType(QualType ValTy, QualType Canonical)
6044 : Type(Atomic, Canonical, ValTy->isDependentType(),
6045 ValTy->isInstantiationDependentType(),
6046 ValTy->isVariablyModifiedType(),
6047 ValTy->containsUnexpandedParameterPack()),
6051 /// Gets the type contained by this atomic type, i.e.
6052 /// the type returned by performing an atomic load of this atomic type.
6053 QualType getValueType() const { return ValueType; }
6055 bool isSugared() const { return false; }
6056 QualType desugar() const { return QualType(this, 0); }
6058 void Profile(llvm::FoldingSetNodeID &ID) {
6059 Profile(ID, getValueType());
6062 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6063 ID.AddPointer(T.getAsOpaquePtr());
6066 static bool classof(const Type *T) {
6067 return T->getTypeClass() == Atomic;
6071 /// PipeType - OpenCL20.
6072 class PipeType : public Type, public llvm::FoldingSetNode {
6073 friend class ASTContext; // ASTContext creates these.
6075 QualType ElementType;
6078 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6079 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6080 elemType->isInstantiationDependentType(),
6081 elemType->isVariablyModifiedType(),
6082 elemType->containsUnexpandedParameterPack()),
6083 ElementType(elemType), isRead(isRead) {}
6086 QualType getElementType() const { return ElementType; }
6088 bool isSugared() const { return false; }
6090 QualType desugar() const { return QualType(this, 0); }
6092 void Profile(llvm::FoldingSetNodeID &ID) {
6093 Profile(ID, getElementType(), isReadOnly());
6096 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6097 ID.AddPointer(T.getAsOpaquePtr());
6098 ID.AddBoolean(isRead);
6101 static bool classof(const Type *T) {
6102 return T->getTypeClass() == Pipe;
6105 bool isReadOnly() const { return isRead; }
6108 /// A qualifier set is used to build a set of qualifiers.
6109 class QualifierCollector : public Qualifiers {
6111 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6113 /// Collect any qualifiers on the given type and return an
6114 /// unqualified type. The qualifiers are assumed to be consistent
6115 /// with those already in the type.
6116 const Type *strip(QualType type) {
6117 addFastQualifiers(type.getLocalFastQualifiers());
6118 if (!type.hasLocalNonFastQualifiers())
6119 return type.getTypePtrUnsafe();
6121 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6122 addConsistentQualifiers(extQuals->getQualifiers());
6123 return extQuals->getBaseType();
6126 /// Apply the collected qualifiers to the given type.
6127 QualType apply(const ASTContext &Context, QualType QT) const;
6129 /// Apply the collected qualifiers to the given type.
6130 QualType apply(const ASTContext &Context, const Type* T) const;
6133 // Inline function definitions.
6135 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6136 SplitQualType desugar =
6137 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6138 desugar.Quals.addConsistentQualifiers(Quals);
6142 inline const Type *QualType::getTypePtr() const {
6143 return getCommonPtr()->BaseType;
6146 inline const Type *QualType::getTypePtrOrNull() const {
6147 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6150 inline SplitQualType QualType::split() const {
6151 if (!hasLocalNonFastQualifiers())
6152 return SplitQualType(getTypePtrUnsafe(),
6153 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6155 const ExtQuals *eq = getExtQualsUnsafe();
6156 Qualifiers qs = eq->getQualifiers();
6157 qs.addFastQualifiers(getLocalFastQualifiers());
6158 return SplitQualType(eq->getBaseType(), qs);
6161 inline Qualifiers QualType::getLocalQualifiers() const {
6163 if (hasLocalNonFastQualifiers())
6164 Quals = getExtQualsUnsafe()->getQualifiers();
6165 Quals.addFastQualifiers(getLocalFastQualifiers());
6169 inline Qualifiers QualType::getQualifiers() const {
6170 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6171 quals.addFastQualifiers(getLocalFastQualifiers());
6175 inline unsigned QualType::getCVRQualifiers() const {
6176 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6177 cvr |= getLocalCVRQualifiers();
6181 inline QualType QualType::getCanonicalType() const {
6182 QualType canon = getCommonPtr()->CanonicalType;
6183 return canon.withFastQualifiers(getLocalFastQualifiers());
6186 inline bool QualType::isCanonical() const {
6187 return getTypePtr()->isCanonicalUnqualified();
6190 inline bool QualType::isCanonicalAsParam() const {
6191 if (!isCanonical()) return false;
6192 if (hasLocalQualifiers()) return false;
6194 const Type *T = getTypePtr();
6195 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6198 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6201 inline bool QualType::isConstQualified() const {
6202 return isLocalConstQualified() ||
6203 getCommonPtr()->CanonicalType.isLocalConstQualified();
6206 inline bool QualType::isRestrictQualified() const {
6207 return isLocalRestrictQualified() ||
6208 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6212 inline bool QualType::isVolatileQualified() const {
6213 return isLocalVolatileQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6217 inline bool QualType::hasQualifiers() const {
6218 return hasLocalQualifiers() ||
6219 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6222 inline QualType QualType::getUnqualifiedType() const {
6223 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6224 return QualType(getTypePtr(), 0);
6226 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6229 inline SplitQualType QualType::getSplitUnqualifiedType() const {
6230 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6233 return getSplitUnqualifiedTypeImpl(*this);
6236 inline void QualType::removeLocalConst() {
6237 removeLocalFastQualifiers(Qualifiers::Const);
6240 inline void QualType::removeLocalRestrict() {
6241 removeLocalFastQualifiers(Qualifiers::Restrict);
6244 inline void QualType::removeLocalVolatile() {
6245 removeLocalFastQualifiers(Qualifiers::Volatile);
6248 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6249 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
6250 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6251 "Fast bits differ from CVR bits!");
6253 // Fast path: we don't need to touch the slow qualifiers.
6254 removeLocalFastQualifiers(Mask);
6257 /// Return the address space of this type.
6258 inline LangAS QualType::getAddressSpace() const {
6259 return getQualifiers().getAddressSpace();
6262 /// Return the gc attribute of this type.
6263 inline Qualifiers::GC QualType::getObjCGCAttr() const {
6264 return getQualifiers().getObjCGCAttr();
6267 inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6268 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6269 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6273 inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6279 inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6285 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6286 if (const auto *PT = t.getAs<PointerType>()) {
6287 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6288 return FT->getExtInfo();
6289 } else if (const auto *FT = t.getAs<FunctionType>())
6290 return FT->getExtInfo();
6292 return FunctionType::ExtInfo();
6295 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6296 return getFunctionExtInfo(*t);
6299 /// Determine whether this type is more
6300 /// qualified than the Other type. For example, "const volatile int"
6301 /// is more qualified than "const int", "volatile int", and
6302 /// "int". However, it is not more qualified than "const volatile
6304 inline bool QualType::isMoreQualifiedThan(QualType other) const {
6305 Qualifiers MyQuals = getQualifiers();
6306 Qualifiers OtherQuals = other.getQualifiers();
6307 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6310 /// Determine whether this type is at last
6311 /// as qualified as the Other type. For example, "const volatile
6312 /// int" is at least as qualified as "const int", "volatile int",
6313 /// "int", and "const volatile int".
6314 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6315 Qualifiers OtherQuals = other.getQualifiers();
6317 // Ignore __unaligned qualifier if this type is a void.
6318 if (getUnqualifiedType()->isVoidType())
6319 OtherQuals.removeUnaligned();
6321 return getQualifiers().compatiblyIncludes(OtherQuals);
6324 /// If Type is a reference type (e.g., const
6325 /// int&), returns the type that the reference refers to ("const
6326 /// int"). Otherwise, returns the type itself. This routine is used
6327 /// throughout Sema to implement C++ 5p6:
6329 /// If an expression initially has the type "reference to T" (8.3.2,
6330 /// 8.5.3), the type is adjusted to "T" prior to any further
6331 /// analysis, the expression designates the object or function
6332 /// denoted by the reference, and the expression is an lvalue.
6333 inline QualType QualType::getNonReferenceType() const {
6334 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6335 return RefType->getPointeeType();
6340 inline bool QualType::isCForbiddenLValueType() const {
6341 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6342 getTypePtr()->isFunctionType());
6345 /// Tests whether the type is categorized as a fundamental type.
6347 /// \returns True for types specified in C++0x [basic.fundamental].
6348 inline bool Type::isFundamentalType() const {
6349 return isVoidType() ||
6350 // FIXME: It's really annoying that we don't have an
6351 // 'isArithmeticType()' which agrees with the standard definition.
6352 (isArithmeticType() && !isEnumeralType());
6355 /// Tests whether the type is categorized as a compound type.
6357 /// \returns True for types specified in C++0x [basic.compound].
6358 inline bool Type::isCompoundType() const {
6359 // C++0x [basic.compound]p1:
6360 // Compound types can be constructed in the following ways:
6361 // -- arrays of objects of a given type [...];
6362 return isArrayType() ||
6363 // -- functions, which have parameters of given types [...];
6365 // -- pointers to void or objects or functions [...];
6367 // -- references to objects or functions of a given type. [...]
6368 isReferenceType() ||
6369 // -- classes containing a sequence of objects of various types, [...];
6371 // -- unions, which are classes capable of containing objects of different
6372 // types at different times;
6374 // -- enumerations, which comprise a set of named constant values. [...];
6376 // -- pointers to non-static class members, [...].
6377 isMemberPointerType();
6380 inline bool Type::isFunctionType() const {
6381 return isa<FunctionType>(CanonicalType);
6384 inline bool Type::isPointerType() const {
6385 return isa<PointerType>(CanonicalType);
6388 inline bool Type::isAnyPointerType() const {
6389 return isPointerType() || isObjCObjectPointerType();
6392 inline bool Type::isBlockPointerType() const {
6393 return isa<BlockPointerType>(CanonicalType);
6396 inline bool Type::isReferenceType() const {
6397 return isa<ReferenceType>(CanonicalType);
6400 inline bool Type::isLValueReferenceType() const {
6401 return isa<LValueReferenceType>(CanonicalType);
6404 inline bool Type::isRValueReferenceType() const {
6405 return isa<RValueReferenceType>(CanonicalType);
6408 inline bool Type::isFunctionPointerType() const {
6409 if (const auto *T = getAs<PointerType>())
6410 return T->getPointeeType()->isFunctionType();
6415 inline bool Type::isFunctionReferenceType() const {
6416 if (const auto *T = getAs<ReferenceType>())
6417 return T->getPointeeType()->isFunctionType();
6422 inline bool Type::isMemberPointerType() const {
6423 return isa<MemberPointerType>(CanonicalType);
6426 inline bool Type::isMemberFunctionPointerType() const {
6427 if (const auto *T = getAs<MemberPointerType>())
6428 return T->isMemberFunctionPointer();
6433 inline bool Type::isMemberDataPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberDataPointer();
6440 inline bool Type::isArrayType() const {
6441 return isa<ArrayType>(CanonicalType);
6444 inline bool Type::isConstantArrayType() const {
6445 return isa<ConstantArrayType>(CanonicalType);
6448 inline bool Type::isIncompleteArrayType() const {
6449 return isa<IncompleteArrayType>(CanonicalType);
6452 inline bool Type::isVariableArrayType() const {
6453 return isa<VariableArrayType>(CanonicalType);
6456 inline bool Type::isDependentSizedArrayType() const {
6457 return isa<DependentSizedArrayType>(CanonicalType);
6460 inline bool Type::isBuiltinType() const {
6461 return isa<BuiltinType>(CanonicalType);
6464 inline bool Type::isRecordType() const {
6465 return isa<RecordType>(CanonicalType);
6468 inline bool Type::isEnumeralType() const {
6469 return isa<EnumType>(CanonicalType);
6472 inline bool Type::isAnyComplexType() const {
6473 return isa<ComplexType>(CanonicalType);
6476 inline bool Type::isVectorType() const {
6477 return isa<VectorType>(CanonicalType);
6480 inline bool Type::isExtVectorType() const {
6481 return isa<ExtVectorType>(CanonicalType);
6484 inline bool Type::isDependentAddressSpaceType() const {
6485 return isa<DependentAddressSpaceType>(CanonicalType);
6488 inline bool Type::isObjCObjectPointerType() const {
6489 return isa<ObjCObjectPointerType>(CanonicalType);
6492 inline bool Type::isObjCObjectType() const {
6493 return isa<ObjCObjectType>(CanonicalType);
6496 inline bool Type::isObjCObjectOrInterfaceType() const {
6497 return isa<ObjCInterfaceType>(CanonicalType) ||
6498 isa<ObjCObjectType>(CanonicalType);
6501 inline bool Type::isAtomicType() const {
6502 return isa<AtomicType>(CanonicalType);
6505 inline bool Type::isObjCQualifiedIdType() const {
6506 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6507 return OPT->isObjCQualifiedIdType();
6511 inline bool Type::isObjCQualifiedClassType() const {
6512 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6513 return OPT->isObjCQualifiedClassType();
6517 inline bool Type::isObjCIdType() const {
6518 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6519 return OPT->isObjCIdType();
6523 inline bool Type::isObjCClassType() const {
6524 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6525 return OPT->isObjCClassType();
6529 inline bool Type::isObjCSelType() const {
6530 if (const auto *OPT = getAs<PointerType>())
6531 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6535 inline bool Type::isObjCBuiltinType() const {
6536 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6539 inline bool Type::isDecltypeType() const {
6540 return isa<DecltypeType>(this);
6543 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6544 inline bool Type::is##Id##Type() const { \
6545 return isSpecificBuiltinType(BuiltinType::Id); \
6547 #include "clang/Basic/OpenCLImageTypes.def"
6549 inline bool Type::isSamplerT() const {
6550 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6553 inline bool Type::isEventT() const {
6554 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6557 inline bool Type::isClkEventT() const {
6558 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6561 inline bool Type::isQueueT() const {
6562 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6565 inline bool Type::isReserveIDT() const {
6566 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6569 inline bool Type::isImageType() const {
6570 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6572 #include "clang/Basic/OpenCLImageTypes.def"
6573 false; // end boolean or operation
6576 inline bool Type::isPipeType() const {
6577 return isa<PipeType>(CanonicalType);
6580 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6581 inline bool Type::is##Id##Type() const { \
6582 return isSpecificBuiltinType(BuiltinType::Id); \
6584 #include "clang/Basic/OpenCLExtensionTypes.def"
6586 inline bool Type::isOCLIntelSubgroupAVCType() const {
6587 #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6588 isOCLIntelSubgroupAVC##Id##Type() ||
6590 #include "clang/Basic/OpenCLExtensionTypes.def"
6591 false; // end of boolean or operation
6594 inline bool Type::isOCLExtOpaqueType() const {
6595 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6597 #include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6601 inline bool Type::isOpenCLSpecificType() const {
6602 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6603 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6606 inline bool Type::isTemplateTypeParmType() const {
6607 return isa<TemplateTypeParmType>(CanonicalType);
6610 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6611 if (const BuiltinType *BT = getAs<BuiltinType>())
6612 if (BT->getKind() == (BuiltinType::Kind) K)
6617 inline bool Type::isPlaceholderType() const {
6618 if (const auto *BT = dyn_cast<BuiltinType>(this))
6619 return BT->isPlaceholderType();
6623 inline const BuiltinType *Type::getAsPlaceholderType() const {
6624 if (const auto *BT = dyn_cast<BuiltinType>(this))
6625 if (BT->isPlaceholderType())
6630 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6631 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6632 if (const auto *BT = dyn_cast<BuiltinType>(this))
6633 return (BT->getKind() == (BuiltinType::Kind) K);
6637 inline bool Type::isNonOverloadPlaceholderType() const {
6638 if (const auto *BT = dyn_cast<BuiltinType>(this))
6639 return BT->isNonOverloadPlaceholderType();
6643 inline bool Type::isVoidType() const {
6644 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6645 return BT->getKind() == BuiltinType::Void;
6649 inline bool Type::isHalfType() const {
6650 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6651 return BT->getKind() == BuiltinType::Half;
6652 // FIXME: Should we allow complex __fp16? Probably not.
6656 inline bool Type::isFloat16Type() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Float16;
6662 inline bool Type::isFloat128Type() const {
6663 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6664 return BT->getKind() == BuiltinType::Float128;
6668 inline bool Type::isNullPtrType() const {
6669 if (const auto *BT = getAs<BuiltinType>())
6670 return BT->getKind() == BuiltinType::NullPtr;
6674 bool IsEnumDeclComplete(EnumDecl *);
6675 bool IsEnumDeclScoped(EnumDecl *);
6677 inline bool Type::isIntegerType() const {
6678 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6679 return BT->getKind() >= BuiltinType::Bool &&
6680 BT->getKind() <= BuiltinType::Int128;
6681 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6682 // Incomplete enum types are not treated as integer types.
6683 // FIXME: In C++, enum types are never integer types.
6684 return IsEnumDeclComplete(ET->getDecl()) &&
6685 !IsEnumDeclScoped(ET->getDecl());
6690 inline bool Type::isFixedPointType() const {
6691 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6692 return BT->getKind() >= BuiltinType::ShortAccum &&
6693 BT->getKind() <= BuiltinType::SatULongFract;
6698 inline bool Type::isFixedPointOrIntegerType() const {
6699 return isFixedPointType() || isIntegerType();
6702 inline bool Type::isSaturatedFixedPointType() const {
6703 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6704 return BT->getKind() >= BuiltinType::SatShortAccum &&
6705 BT->getKind() <= BuiltinType::SatULongFract;
6710 inline bool Type::isUnsaturatedFixedPointType() const {
6711 return isFixedPointType() && !isSaturatedFixedPointType();
6714 inline bool Type::isSignedFixedPointType() const {
6715 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6716 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6717 BT->getKind() <= BuiltinType::LongAccum) ||
6718 (BT->getKind() >= BuiltinType::ShortFract &&
6719 BT->getKind() <= BuiltinType::LongFract) ||
6720 (BT->getKind() >= BuiltinType::SatShortAccum &&
6721 BT->getKind() <= BuiltinType::SatLongAccum) ||
6722 (BT->getKind() >= BuiltinType::SatShortFract &&
6723 BT->getKind() <= BuiltinType::SatLongFract));
6728 inline bool Type::isUnsignedFixedPointType() const {
6729 return isFixedPointType() && !isSignedFixedPointType();
6732 inline bool Type::isScalarType() const {
6733 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6734 return BT->getKind() > BuiltinType::Void &&
6735 BT->getKind() <= BuiltinType::NullPtr;
6736 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6737 // Enums are scalar types, but only if they are defined. Incomplete enums
6738 // are not treated as scalar types.
6739 return IsEnumDeclComplete(ET->getDecl());
6740 return isa<PointerType>(CanonicalType) ||
6741 isa<BlockPointerType>(CanonicalType) ||
6742 isa<MemberPointerType>(CanonicalType) ||
6743 isa<ComplexType>(CanonicalType) ||
6744 isa<ObjCObjectPointerType>(CanonicalType);
6747 inline bool Type::isIntegralOrEnumerationType() const {
6748 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6749 return BT->getKind() >= BuiltinType::Bool &&
6750 BT->getKind() <= BuiltinType::Int128;
6752 // Check for a complete enum type; incomplete enum types are not properly an
6753 // enumeration type in the sense required here.
6754 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6755 return IsEnumDeclComplete(ET->getDecl());
6760 inline bool Type::isBooleanType() const {
6761 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6762 return BT->getKind() == BuiltinType::Bool;
6766 inline bool Type::isUndeducedType() const {
6767 auto *DT = getContainedDeducedType();
6768 return DT && !DT->isDeduced();
6771 /// Determines whether this is a type for which one can define
6772 /// an overloaded operator.
6773 inline bool Type::isOverloadableType() const {
6774 return isDependentType() || isRecordType() || isEnumeralType();
6777 /// Determines whether this type can decay to a pointer type.
6778 inline bool Type::canDecayToPointerType() const {
6779 return isFunctionType() || isArrayType();
6782 inline bool Type::hasPointerRepresentation() const {
6783 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6784 isObjCObjectPointerType() || isNullPtrType());
6787 inline bool Type::hasObjCPointerRepresentation() const {
6788 return isObjCObjectPointerType();
6791 inline const Type *Type::getBaseElementTypeUnsafe() const {
6792 const Type *type = this;
6793 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6794 type = arrayType->getElementType().getTypePtr();
6798 inline const Type *Type::getPointeeOrArrayElementType() const {
6799 const Type *type = this;
6800 if (type->isAnyPointerType())
6801 return type->getPointeeType().getTypePtr();
6802 else if (type->isArrayType())
6803 return type->getBaseElementTypeUnsafe();
6807 /// Insertion operator for diagnostics. This allows sending Qualifiers into a
6808 /// diagnostic with <<.
6809 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6811 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6812 DiagnosticsEngine::ArgumentKind::ak_qual);
6816 /// Insertion operator for partial diagnostics. This allows sending Qualifiers
6817 /// into a diagnostic with <<.
6818 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6820 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6821 DiagnosticsEngine::ArgumentKind::ak_qual);
6825 /// Insertion operator for diagnostics. This allows sending QualType's into a
6826 /// diagnostic with <<.
6827 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6829 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6830 DiagnosticsEngine::ak_qualtype);
6834 /// Insertion operator for partial diagnostics. This allows sending QualType's
6835 /// into a diagnostic with <<.
6836 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6838 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6839 DiagnosticsEngine::ak_qualtype);
6843 // Helper class template that is used by Type::getAs to ensure that one does
6844 // not try to look through a qualified type to get to an array type.
6845 template <typename T>
6846 using TypeIsArrayType =
6847 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6848 std::is_base_of<ArrayType, T>::value>;
6850 // Member-template getAs<specific type>'.
6851 template <typename T> const T *Type::getAs() const {
6852 static_assert(!TypeIsArrayType<T>::value,
6853 "ArrayType cannot be used with getAs!");
6855 // If this is directly a T type, return it.
6856 if (const auto *Ty = dyn_cast<T>(this))
6859 // If the canonical form of this type isn't the right kind, reject it.
6860 if (!isa<T>(CanonicalType))
6863 // If this is a typedef for the type, strip the typedef off without
6864 // losing all typedef information.
6865 return cast<T>(getUnqualifiedDesugaredType());
6868 template <typename T> const T *Type::getAsAdjusted() const {
6869 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6871 // If this is directly a T type, return it.
6872 if (const auto *Ty = dyn_cast<T>(this))
6875 // If the canonical form of this type isn't the right kind, reject it.
6876 if (!isa<T>(CanonicalType))
6879 // Strip off type adjustments that do not modify the underlying nature of the
6881 const Type *Ty = this;
6883 if (const auto *A = dyn_cast<AttributedType>(Ty))
6884 Ty = A->getModifiedType().getTypePtr();
6885 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6886 Ty = E->desugar().getTypePtr();
6887 else if (const auto *P = dyn_cast<ParenType>(Ty))
6888 Ty = P->desugar().getTypePtr();
6889 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6890 Ty = A->desugar().getTypePtr();
6891 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6892 Ty = M->desugar().getTypePtr();
6897 // Just because the canonical type is correct does not mean we can use cast<>,
6898 // since we may not have stripped off all the sugar down to the base type.
6899 return dyn_cast<T>(Ty);
6902 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6903 // If this is directly an array type, return it.
6904 if (const auto *arr = dyn_cast<ArrayType>(this))
6907 // If the canonical form of this type isn't the right kind, reject it.
6908 if (!isa<ArrayType>(CanonicalType))
6911 // If this is a typedef for the type, strip the typedef off without
6912 // losing all typedef information.
6913 return cast<ArrayType>(getUnqualifiedDesugaredType());
6916 template <typename T> const T *Type::castAs() const {
6917 static_assert(!TypeIsArrayType<T>::value,
6918 "ArrayType cannot be used with castAs!");
6920 if (const auto *ty = dyn_cast<T>(this)) return ty;
6921 assert(isa<T>(CanonicalType));
6922 return cast<T>(getUnqualifiedDesugaredType());
6925 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6926 assert(isa<ArrayType>(CanonicalType));
6927 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6928 return cast<ArrayType>(getUnqualifiedDesugaredType());
6931 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6932 QualType CanonicalPtr)
6933 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6935 QualType Adjusted = getAdjustedType();
6936 (void)AttributedType::stripOuterNullability(Adjusted);
6937 assert(isa<PointerType>(Adjusted));
6941 QualType DecayedType::getPointeeType() const {
6942 QualType Decayed = getDecayedType();
6943 (void)AttributedType::stripOuterNullability(Decayed);
6944 return cast<PointerType>(Decayed)->getPointeeType();
6947 // Get the decimal string representation of a fixed point type, represented
6948 // as a scaled integer.
6949 // TODO: At some point, we should change the arguments to instead just accept an
6950 // APFixedPoint instead of APSInt and scale.
6951 void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6954 } // namespace clang
6956 #endif // LLVM_CLANG_AST_TYPE_H