1 //===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// C Language Family Type Representation
13 /// This file defines the clang::Type interface and subclasses, used to
14 /// represent types for languages in the C family.
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_CLANG_AST_TYPE_H
19 #define LLVM_CLANG_AST_TYPE_H
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/TemplateName.h"
23 #include "clang/Basic/AddressSpaces.h"
24 #include "clang/Basic/AttrKinds.h"
25 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/ExceptionSpecificationType.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/Linkage.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceLocation.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/Visibility.h"
33 #include "llvm/ADT/APInt.h"
34 #include "llvm/ADT/APSInt.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/FoldingSet.h"
37 #include "llvm/ADT/None.h"
38 #include "llvm/ADT/Optional.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/PointerUnion.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/ADT/iterator_range.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/PointerLikeTypeTraits.h"
48 #include "llvm/Support/type_traits.h"
49 #include "llvm/Support/TrailingObjects.h"
55 #include <type_traits>
66 TypeAlignmentInBits = 4,
67 TypeAlignment = 1 << TypeAlignmentInBits
75 struct PointerLikeTypeTraits;
77 struct PointerLikeTypeTraits< ::clang::Type*> {
78 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
80 static inline ::clang::Type *getFromVoidPointer(void *P) {
81 return static_cast< ::clang::Type*>(P);
84 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
88 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
89 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
91 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
92 return static_cast< ::clang::ExtQuals*>(P);
95 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
99 struct isPodLike<clang::QualType> { static const bool value = true; };
106 template <typename> class CanQual;
111 class ExtQualsTypeCommonBase;
113 class IdentifierInfo;
115 class ObjCInterfaceDecl;
116 class ObjCProtocolDecl;
117 class ObjCTypeParamDecl;
118 struct PrintingPolicy;
122 class TemplateArgument;
123 class TemplateArgumentListInfo;
124 class TemplateArgumentLoc;
125 class TemplateTypeParmDecl;
126 class TypedefNameDecl;
127 class UnresolvedUsingTypenameDecl;
129 using CanQualType = CanQual<Type>;
131 // Provide forward declarations for all of the *Type classes.
132 #define TYPE(Class, Base) class Class##Type;
133 #include "clang/AST/TypeNodes.def"
135 /// The collection of all-type qualifiers we support.
136 /// Clang supports five independent qualifiers:
137 /// * C99: const, volatile, and restrict
138 /// * MS: __unaligned
139 /// * Embedded C (TR18037): address spaces
140 /// * Objective C: the GC attributes (none, weak, or strong)
143 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 CVRMask = Const | Volatile | Restrict
157 /// There is no lifetime qualification on this type.
160 /// This object can be modified without requiring retains or
164 /// Assigning into this object requires the old value to be
165 /// released and the new value to be retained. The timing of the
166 /// release of the old value is inexact: it may be moved to
167 /// immediately after the last known point where the value is
171 /// Reading or writing from this object requires a barrier call.
174 /// Assigning into this object requires a lifetime extension.
179 /// The maximum supported address space number.
180 /// 23 bits should be enough for anyone.
181 MaxAddressSpace = 0x7fffffu,
183 /// The width of the "fast" qualifier mask.
186 /// The fast qualifier mask.
187 FastMask = (1 << FastWidth) - 1
190 /// Returns the common set of qualifiers while removing them from
192 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
193 // If both are only CVR-qualified, bit operations are sufficient.
194 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
196 Q.Mask = L.Mask & R.Mask;
203 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
204 Q.addCVRQualifiers(CommonCRV);
205 L.removeCVRQualifiers(CommonCRV);
206 R.removeCVRQualifiers(CommonCRV);
208 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
209 Q.setObjCGCAttr(L.getObjCGCAttr());
210 L.removeObjCGCAttr();
211 R.removeObjCGCAttr();
214 if (L.getObjCLifetime() == R.getObjCLifetime()) {
215 Q.setObjCLifetime(L.getObjCLifetime());
216 L.removeObjCLifetime();
217 R.removeObjCLifetime();
220 if (L.getAddressSpace() == R.getAddressSpace()) {
221 Q.setAddressSpace(L.getAddressSpace());
222 L.removeAddressSpace();
223 R.removeAddressSpace();
228 static Qualifiers fromFastMask(unsigned Mask) {
230 Qs.addFastQualifiers(Mask);
234 static Qualifiers fromCVRMask(unsigned CVR) {
236 Qs.addCVRQualifiers(CVR);
240 static Qualifiers fromCVRUMask(unsigned CVRU) {
242 Qs.addCVRUQualifiers(CVRU);
246 // Deserialize qualifiers from an opaque representation.
247 static Qualifiers fromOpaqueValue(unsigned opaque) {
253 // Serialize these qualifiers into an opaque representation.
254 unsigned getAsOpaqueValue() const {
258 bool hasConst() const { return Mask & Const; }
259 bool hasOnlyConst() const { return Mask == Const; }
260 void removeConst() { Mask &= ~Const; }
261 void addConst() { Mask |= Const; }
263 bool hasVolatile() const { return Mask & Volatile; }
264 bool hasOnlyVolatile() const { return Mask == Volatile; }
265 void removeVolatile() { Mask &= ~Volatile; }
266 void addVolatile() { Mask |= Volatile; }
268 bool hasRestrict() const { return Mask & Restrict; }
269 bool hasOnlyRestrict() const { return Mask == Restrict; }
270 void removeRestrict() { Mask &= ~Restrict; }
271 void addRestrict() { Mask |= Restrict; }
273 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
274 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
275 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
277 void setCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
279 Mask = (Mask & ~CVRMask) | mask;
281 void removeCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
285 void removeCVRQualifiers() {
286 removeCVRQualifiers(CVRMask);
288 void addCVRQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
292 void addCVRUQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
297 bool hasUnaligned() const { return Mask & UMask; }
298 void setUnaligned(bool flag) {
299 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
301 void removeUnaligned() { Mask &= ~UMask; }
302 void addUnaligned() { Mask |= UMask; }
304 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
305 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
306 void setObjCGCAttr(GC type) {
307 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
309 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
310 void addObjCGCAttr(GC type) {
314 Qualifiers withoutObjCGCAttr() const {
315 Qualifiers qs = *this;
316 qs.removeObjCGCAttr();
319 Qualifiers withoutObjCLifetime() const {
320 Qualifiers qs = *this;
321 qs.removeObjCLifetime();
325 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
326 ObjCLifetime getObjCLifetime() const {
327 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 void setObjCLifetime(ObjCLifetime type) {
330 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
333 void addObjCLifetime(ObjCLifetime type) {
335 assert(!hasObjCLifetime());
336 Mask |= (type << LifetimeShift);
339 /// True if the lifetime is neither None or ExplicitNone.
340 bool hasNonTrivialObjCLifetime() const {
341 ObjCLifetime lifetime = getObjCLifetime();
342 return (lifetime > OCL_ExplicitNone);
345 /// True if the lifetime is either strong or weak.
346 bool hasStrongOrWeakObjCLifetime() const {
347 ObjCLifetime lifetime = getObjCLifetime();
348 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
351 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
352 LangAS getAddressSpace() const {
353 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 bool hasTargetSpecificAddressSpace() const {
356 return isTargetAddressSpace(getAddressSpace());
358 /// Get the address space attribute value to be printed by diagnostics.
359 unsigned getAddressSpaceAttributePrintValue() const {
360 auto Addr = getAddressSpace();
361 // This function is not supposed to be used with language specific
362 // address spaces. If that happens, the diagnostic message should consider
363 // printing the QualType instead of the address space value.
364 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
365 if (Addr != LangAS::Default)
366 return toTargetAddressSpace(Addr);
367 // TODO: The diagnostic messages where Addr may be 0 should be fixed
368 // since it cannot differentiate the situation where 0 denotes the default
369 // address space or user specified __attribute__((address_space(0))).
372 void setAddressSpace(LangAS space) {
373 assert((unsigned)space <= MaxAddressSpace);
374 Mask = (Mask & ~AddressSpaceMask)
375 | (((uint32_t) space) << AddressSpaceShift);
377 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
378 void addAddressSpace(LangAS space) {
379 assert(space != LangAS::Default);
380 setAddressSpace(space);
383 // Fast qualifiers are those that can be allocated directly
384 // on a QualType object.
385 bool hasFastQualifiers() const { return getFastQualifiers(); }
386 unsigned getFastQualifiers() const { return Mask & FastMask; }
387 void setFastQualifiers(unsigned mask) {
388 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
389 Mask = (Mask & ~FastMask) | mask;
391 void removeFastQualifiers(unsigned mask) {
392 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
395 void removeFastQualifiers() {
396 removeFastQualifiers(FastMask);
398 void addFastQualifiers(unsigned mask) {
399 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
403 /// Return true if the set contains any qualifiers which require an ExtQuals
404 /// node to be allocated.
405 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
406 Qualifiers getNonFastQualifiers() const {
407 Qualifiers Quals = *this;
408 Quals.setFastQualifiers(0);
412 /// Return true if the set contains any qualifiers.
413 bool hasQualifiers() const { return Mask; }
414 bool empty() const { return !Mask; }
416 /// Add the qualifiers from the given set to this set.
417 void addQualifiers(Qualifiers Q) {
418 // If the other set doesn't have any non-boolean qualifiers, just
420 if (!(Q.Mask & ~CVRMask))
423 Mask |= (Q.Mask & CVRMask);
424 if (Q.hasAddressSpace())
425 addAddressSpace(Q.getAddressSpace());
426 if (Q.hasObjCGCAttr())
427 addObjCGCAttr(Q.getObjCGCAttr());
428 if (Q.hasObjCLifetime())
429 addObjCLifetime(Q.getObjCLifetime());
433 /// Remove the qualifiers from the given set from this set.
434 void removeQualifiers(Qualifiers Q) {
435 // If the other set doesn't have any non-boolean qualifiers, just
436 // bit-and the inverse in.
437 if (!(Q.Mask & ~CVRMask))
440 Mask &= ~(Q.Mask & CVRMask);
441 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 if (getObjCLifetime() == Q.getObjCLifetime())
444 removeObjCLifetime();
445 if (getAddressSpace() == Q.getAddressSpace())
446 removeAddressSpace();
450 /// Add the qualifiers from the given set to this set, given that
451 /// they don't conflict.
452 void addConsistentQualifiers(Qualifiers qs) {
453 assert(getAddressSpace() == qs.getAddressSpace() ||
454 !hasAddressSpace() || !qs.hasAddressSpace());
455 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
456 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
457 assert(getObjCLifetime() == qs.getObjCLifetime() ||
458 !hasObjCLifetime() || !qs.hasObjCLifetime());
462 /// Returns true if this address space is a superset of the other one.
463 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
464 /// overlapping address spaces.
466 /// every address space is a superset of itself.
468 /// __generic is a superset of any address space except for __constant.
469 bool isAddressSpaceSupersetOf(Qualifiers other) const {
471 // Address spaces must match exactly.
472 getAddressSpace() == other.getAddressSpace() ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (getAddressSpace() == LangAS::opencl_generic &&
476 other.getAddressSpace() != LangAS::opencl_constant);
479 /// Determines if these qualifiers compatibly include another set.
480 /// Generally this answers the question of whether an object with the other
481 /// qualifiers can be safely used as an object with these qualifiers.
482 bool compatiblyIncludes(Qualifiers other) const {
483 return isAddressSpaceSupersetOf(other) &&
484 // ObjC GC qualifiers can match, be added, or be removed, but can't
486 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
487 !other.hasObjCGCAttr()) &&
488 // ObjC lifetime qualifiers must match exactly.
489 getObjCLifetime() == other.getObjCLifetime() &&
490 // CVR qualifiers may subset.
491 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
492 // U qualifier may superset.
493 (!other.hasUnaligned() || hasUnaligned());
496 /// Determines if these qualifiers compatibly include another set of
497 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
499 /// One set of Objective-C lifetime qualifiers compatibly includes the other
500 /// if the lifetime qualifiers match, or if both are non-__weak and the
501 /// including set also contains the 'const' qualifier, or both are non-__weak
502 /// and one is None (which can only happen in non-ARC modes).
503 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
504 if (getObjCLifetime() == other.getObjCLifetime())
507 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
510 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 /// Determine whether this set of qualifiers is a strict superset of
517 /// another set of qualifiers, not considering qualifier compatibility.
518 bool isStrictSupersetOf(Qualifiers Other) const;
520 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
521 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
523 explicit operator bool() const { return hasQualifiers(); }
525 Qualifiers &operator+=(Qualifiers R) {
530 // Union two qualifier sets. If an enumerated qualifier appears
531 // in both sets, use the one from the right.
532 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
537 Qualifiers &operator-=(Qualifiers R) {
542 /// Compute the difference between two qualifier sets.
543 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
548 std::string getAsString() const;
549 std::string getAsString(const PrintingPolicy &Policy) const;
551 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
552 void print(raw_ostream &OS, const PrintingPolicy &Policy,
553 bool appendSpaceIfNonEmpty = false) const;
555 void Profile(llvm::FoldingSetNodeID &ID) const {
560 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
561 // |C R V|U|GCAttr|Lifetime|AddressSpace|
564 static const uint32_t UMask = 0x8;
565 static const uint32_t UShift = 3;
566 static const uint32_t GCAttrMask = 0x30;
567 static const uint32_t GCAttrShift = 4;
568 static const uint32_t LifetimeMask = 0x1C0;
569 static const uint32_t LifetimeShift = 6;
570 static const uint32_t AddressSpaceMask =
571 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
572 static const uint32_t AddressSpaceShift = 9;
575 /// A std::pair-like structure for storing a qualified type split
576 /// into its local qualifiers and its locally-unqualified type.
577 struct SplitQualType {
578 /// The locally-unqualified type.
579 const Type *Ty = nullptr;
581 /// The local qualifiers.
584 SplitQualType() = default;
585 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
587 SplitQualType getSingleStepDesugaredType() const; // end of this file
589 // Make std::tie work.
590 std::pair<const Type *,Qualifiers> asPair() const {
591 return std::pair<const Type *, Qualifiers>(Ty, Quals);
594 friend bool operator==(SplitQualType a, SplitQualType b) {
595 return a.Ty == b.Ty && a.Quals == b.Quals;
597 friend bool operator!=(SplitQualType a, SplitQualType b) {
598 return a.Ty != b.Ty || a.Quals != b.Quals;
602 /// The kind of type we are substituting Objective-C type arguments into.
604 /// The kind of substitution affects the replacement of type parameters when
605 /// no concrete type information is provided, e.g., when dealing with an
606 /// unspecialized type.
607 enum class ObjCSubstitutionContext {
608 /// An ordinary type.
611 /// The result type of a method or function.
614 /// The parameter type of a method or function.
617 /// The type of a property.
620 /// The superclass of a type.
624 /// A (possibly-)qualified type.
626 /// For efficiency, we don't store CV-qualified types as nodes on their
627 /// own: instead each reference to a type stores the qualifiers. This
628 /// greatly reduces the number of nodes we need to allocate for types (for
629 /// example we only need one for 'int', 'const int', 'volatile int',
630 /// 'const volatile int', etc).
632 /// As an added efficiency bonus, instead of making this a pair, we
633 /// just store the two bits we care about in the low bits of the
634 /// pointer. To handle the packing/unpacking, we make QualType be a
635 /// simple wrapper class that acts like a smart pointer. A third bit
636 /// indicates whether there are extended qualifiers present, in which
637 /// case the pointer points to a special structure.
639 friend class QualifierCollector;
641 // Thankfully, these are efficiently composable.
642 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
643 Qualifiers::FastWidth> Value;
645 const ExtQuals *getExtQualsUnsafe() const {
646 return Value.getPointer().get<const ExtQuals*>();
649 const Type *getTypePtrUnsafe() const {
650 return Value.getPointer().get<const Type*>();
653 const ExtQualsTypeCommonBase *getCommonPtr() const {
654 assert(!isNull() && "Cannot retrieve a NULL type pointer");
655 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
656 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
657 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
661 QualType() = default;
662 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
663 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
665 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
666 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
668 /// Retrieves a pointer to the underlying (unqualified) type.
670 /// This function requires that the type not be NULL. If the type might be
671 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
672 const Type *getTypePtr() const;
674 const Type *getTypePtrOrNull() const;
676 /// Retrieves a pointer to the name of the base type.
677 const IdentifierInfo *getBaseTypeIdentifier() const;
679 /// Divides a QualType into its unqualified type and a set of local
681 SplitQualType split() const;
683 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
685 static QualType getFromOpaquePtr(const void *Ptr) {
687 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
691 const Type &operator*() const {
692 return *getTypePtr();
695 const Type *operator->() const {
699 bool isCanonical() const;
700 bool isCanonicalAsParam() const;
702 /// Return true if this QualType doesn't point to a type yet.
703 bool isNull() const {
704 return Value.getPointer().isNull();
707 /// Determine whether this particular QualType instance has the
708 /// "const" qualifier set, without looking through typedefs that may have
709 /// added "const" at a different level.
710 bool isLocalConstQualified() const {
711 return (getLocalFastQualifiers() & Qualifiers::Const);
714 /// Determine whether this type is const-qualified.
715 bool isConstQualified() const;
717 /// Determine whether this particular QualType instance has the
718 /// "restrict" qualifier set, without looking through typedefs that may have
719 /// added "restrict" at a different level.
720 bool isLocalRestrictQualified() const {
721 return (getLocalFastQualifiers() & Qualifiers::Restrict);
724 /// Determine whether this type is restrict-qualified.
725 bool isRestrictQualified() const;
727 /// Determine whether this particular QualType instance has the
728 /// "volatile" qualifier set, without looking through typedefs that may have
729 /// added "volatile" at a different level.
730 bool isLocalVolatileQualified() const {
731 return (getLocalFastQualifiers() & Qualifiers::Volatile);
734 /// Determine whether this type is volatile-qualified.
735 bool isVolatileQualified() const;
737 /// Determine whether this particular QualType instance has any
738 /// qualifiers, without looking through any typedefs that might add
739 /// qualifiers at a different level.
740 bool hasLocalQualifiers() const {
741 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
744 /// Determine whether this type has any qualifiers.
745 bool hasQualifiers() const;
747 /// Determine whether this particular QualType instance has any
748 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
750 bool hasLocalNonFastQualifiers() const {
751 return Value.getPointer().is<const ExtQuals*>();
754 /// Retrieve the set of qualifiers local to this particular QualType
755 /// instance, not including any qualifiers acquired through typedefs or
757 Qualifiers getLocalQualifiers() const;
759 /// Retrieve the set of qualifiers applied to this type.
760 Qualifiers getQualifiers() const;
762 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
763 /// local to this particular QualType instance, not including any qualifiers
764 /// acquired through typedefs or other sugar.
765 unsigned getLocalCVRQualifiers() const {
766 return getLocalFastQualifiers();
769 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
770 /// applied to this type.
771 unsigned getCVRQualifiers() const;
773 bool isConstant(const ASTContext& Ctx) const {
774 return QualType::isConstant(*this, Ctx);
777 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
778 bool isPODType(const ASTContext &Context) const;
780 /// Return true if this is a POD type according to the rules of the C++98
781 /// standard, regardless of the current compilation's language.
782 bool isCXX98PODType(const ASTContext &Context) const;
784 /// Return true if this is a POD type according to the more relaxed rules
785 /// of the C++11 standard, regardless of the current compilation's language.
786 /// (C++0x [basic.types]p9). Note that, unlike
787 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
788 bool isCXX11PODType(const ASTContext &Context) const;
790 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
791 bool isTrivialType(const ASTContext &Context) const;
793 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
794 bool isTriviallyCopyableType(const ASTContext &Context) const;
797 /// Returns true if it is a class and it might be dynamic.
798 bool mayBeDynamicClass() const;
800 /// Returns true if it is not a class or if the class might not be dynamic.
801 bool mayBeNotDynamicClass() const;
803 // Don't promise in the API that anything besides 'const' can be
806 /// Add the `const` type qualifier to this QualType.
808 addFastQualifiers(Qualifiers::Const);
810 QualType withConst() const {
811 return withFastQualifiers(Qualifiers::Const);
814 /// Add the `volatile` type qualifier to this QualType.
816 addFastQualifiers(Qualifiers::Volatile);
818 QualType withVolatile() const {
819 return withFastQualifiers(Qualifiers::Volatile);
822 /// Add the `restrict` qualifier to this QualType.
824 addFastQualifiers(Qualifiers::Restrict);
826 QualType withRestrict() const {
827 return withFastQualifiers(Qualifiers::Restrict);
830 QualType withCVRQualifiers(unsigned CVR) const {
831 return withFastQualifiers(CVR);
834 void addFastQualifiers(unsigned TQs) {
835 assert(!(TQs & ~Qualifiers::FastMask)
836 && "non-fast qualifier bits set in mask!");
837 Value.setInt(Value.getInt() | TQs);
840 void removeLocalConst();
841 void removeLocalVolatile();
842 void removeLocalRestrict();
843 void removeLocalCVRQualifiers(unsigned Mask);
845 void removeLocalFastQualifiers() { Value.setInt(0); }
846 void removeLocalFastQualifiers(unsigned Mask) {
847 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
848 Value.setInt(Value.getInt() & ~Mask);
851 // Creates a type with the given qualifiers in addition to any
852 // qualifiers already on this type.
853 QualType withFastQualifiers(unsigned TQs) const {
855 T.addFastQualifiers(TQs);
859 // Creates a type with exactly the given fast qualifiers, removing
860 // any existing fast qualifiers.
861 QualType withExactLocalFastQualifiers(unsigned TQs) const {
862 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
865 // Removes fast qualifiers, but leaves any extended qualifiers in place.
866 QualType withoutLocalFastQualifiers() const {
868 T.removeLocalFastQualifiers();
872 QualType getCanonicalType() const;
874 /// Return this type with all of the instance-specific qualifiers
875 /// removed, but without removing any qualifiers that may have been applied
876 /// through typedefs.
877 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
879 /// Retrieve the unqualified variant of the given type,
880 /// removing as little sugar as possible.
882 /// This routine looks through various kinds of sugar to find the
883 /// least-desugared type that is unqualified. For example, given:
886 /// typedef int Integer;
887 /// typedef const Integer CInteger;
888 /// typedef CInteger DifferenceType;
891 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
892 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
894 /// The resulting type might still be qualified if it's sugar for an array
895 /// type. To strip qualifiers even from within a sugared array type, use
896 /// ASTContext::getUnqualifiedArrayType.
897 inline QualType getUnqualifiedType() const;
899 /// Retrieve the unqualified variant of the given type, removing as little
900 /// sugar as possible.
902 /// Like getUnqualifiedType(), but also returns the set of
903 /// qualifiers that were built up.
905 /// The resulting type might still be qualified if it's sugar for an array
906 /// type. To strip qualifiers even from within a sugared array type, use
907 /// ASTContext::getUnqualifiedArrayType.
908 inline SplitQualType getSplitUnqualifiedType() const;
910 /// Determine whether this type is more qualified than the other
911 /// given type, requiring exact equality for non-CVR qualifiers.
912 bool isMoreQualifiedThan(QualType Other) const;
914 /// Determine whether this type is at least as qualified as the other
915 /// given type, requiring exact equality for non-CVR qualifiers.
916 bool isAtLeastAsQualifiedAs(QualType Other) const;
918 QualType getNonReferenceType() const;
920 /// Determine the type of a (typically non-lvalue) expression with the
921 /// specified result type.
923 /// This routine should be used for expressions for which the return type is
924 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
925 /// an lvalue. It removes a top-level reference (since there are no
926 /// expressions of reference type) and deletes top-level cvr-qualifiers
927 /// from non-class types (in C++) or all types (in C).
928 QualType getNonLValueExprType(const ASTContext &Context) const;
930 /// Return the specified type with any "sugar" removed from
931 /// the type. This takes off typedefs, typeof's etc. If the outer level of
932 /// the type is already concrete, it returns it unmodified. This is similar
933 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
934 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
937 /// Qualifiers are left in place.
938 QualType getDesugaredType(const ASTContext &Context) const {
939 return getDesugaredType(*this, Context);
942 SplitQualType getSplitDesugaredType() const {
943 return getSplitDesugaredType(*this);
946 /// Return the specified type with one level of "sugar" removed from
949 /// This routine takes off the first typedef, typeof, etc. If the outer level
950 /// of the type is already concrete, it returns it unmodified.
951 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
952 return getSingleStepDesugaredTypeImpl(*this, Context);
955 /// Returns the specified type after dropping any
956 /// outer-level parentheses.
957 QualType IgnoreParens() const {
958 if (isa<ParenType>(*this))
959 return QualType::IgnoreParens(*this);
963 /// Indicate whether the specified types and qualifiers are identical.
964 friend bool operator==(const QualType &LHS, const QualType &RHS) {
965 return LHS.Value == RHS.Value;
967 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
968 return LHS.Value != RHS.Value;
971 static std::string getAsString(SplitQualType split,
972 const PrintingPolicy &Policy) {
973 return getAsString(split.Ty, split.Quals, Policy);
975 static std::string getAsString(const Type *ty, Qualifiers qs,
976 const PrintingPolicy &Policy);
978 std::string getAsString() const;
979 std::string getAsString(const PrintingPolicy &Policy) const;
981 void print(raw_ostream &OS, const PrintingPolicy &Policy,
982 const Twine &PlaceHolder = Twine(),
983 unsigned Indentation = 0) const;
985 static void print(SplitQualType split, raw_ostream &OS,
986 const PrintingPolicy &policy, const Twine &PlaceHolder,
987 unsigned Indentation = 0) {
988 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
991 static void print(const Type *ty, Qualifiers qs,
992 raw_ostream &OS, const PrintingPolicy &policy,
993 const Twine &PlaceHolder,
994 unsigned Indentation = 0);
996 void getAsStringInternal(std::string &Str,
997 const PrintingPolicy &Policy) const;
999 static void getAsStringInternal(SplitQualType split, std::string &out,
1000 const PrintingPolicy &policy) {
1001 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1004 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1006 const PrintingPolicy &policy);
1008 class StreamedQualTypeHelper {
1010 const PrintingPolicy &Policy;
1011 const Twine &PlaceHolder;
1012 unsigned Indentation;
1015 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1016 const Twine &PlaceHolder, unsigned Indentation)
1017 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1018 Indentation(Indentation) {}
1020 friend raw_ostream &operator<<(raw_ostream &OS,
1021 const StreamedQualTypeHelper &SQT) {
1022 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1027 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1028 const Twine &PlaceHolder = Twine(),
1029 unsigned Indentation = 0) const {
1030 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1033 void dump(const char *s) const;
1035 void dump(llvm::raw_ostream &OS) const;
1037 void Profile(llvm::FoldingSetNodeID &ID) const {
1038 ID.AddPointer(getAsOpaquePtr());
1041 /// Return the address space of this type.
1042 inline LangAS getAddressSpace() const;
1044 /// Returns gc attribute of this type.
1045 inline Qualifiers::GC getObjCGCAttr() const;
1047 /// true when Type is objc's weak.
1048 bool isObjCGCWeak() const {
1049 return getObjCGCAttr() == Qualifiers::Weak;
1052 /// true when Type is objc's strong.
1053 bool isObjCGCStrong() const {
1054 return getObjCGCAttr() == Qualifiers::Strong;
1057 /// Returns lifetime attribute of this type.
1058 Qualifiers::ObjCLifetime getObjCLifetime() const {
1059 return getQualifiers().getObjCLifetime();
1062 bool hasNonTrivialObjCLifetime() const {
1063 return getQualifiers().hasNonTrivialObjCLifetime();
1066 bool hasStrongOrWeakObjCLifetime() const {
1067 return getQualifiers().hasStrongOrWeakObjCLifetime();
1070 // true when Type is objc's weak and weak is enabled but ARC isn't.
1071 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1073 enum PrimitiveDefaultInitializeKind {
1074 /// The type does not fall into any of the following categories. Note that
1075 /// this case is zero-valued so that values of this enum can be used as a
1076 /// boolean condition for non-triviality.
1079 /// The type is an Objective-C retainable pointer type that is qualified
1080 /// with the ARC __strong qualifier.
1083 /// The type is an Objective-C retainable pointer type that is qualified
1084 /// with the ARC __weak qualifier.
1087 /// The type is a struct containing a field whose type is not PCK_Trivial.
1091 /// Functions to query basic properties of non-trivial C struct types.
1093 /// Check if this is a non-trivial type that would cause a C struct
1094 /// transitively containing this type to be non-trivial to default initialize
1095 /// and return the kind.
1096 PrimitiveDefaultInitializeKind
1097 isNonTrivialToPrimitiveDefaultInitialize() const;
1099 enum PrimitiveCopyKind {
1100 /// The type does not fall into any of the following categories. Note that
1101 /// this case is zero-valued so that values of this enum can be used as a
1102 /// boolean condition for non-triviality.
1105 /// The type would be trivial except that it is volatile-qualified. Types
1106 /// that fall into one of the other non-trivial cases may additionally be
1107 /// volatile-qualified.
1108 PCK_VolatileTrivial,
1110 /// The type is an Objective-C retainable pointer type that is qualified
1111 /// with the ARC __strong qualifier.
1114 /// The type is an Objective-C retainable pointer type that is qualified
1115 /// with the ARC __weak qualifier.
1118 /// The type is a struct containing a field whose type is neither
1119 /// PCK_Trivial nor PCK_VolatileTrivial.
1120 /// Note that a C++ struct type does not necessarily match this; C++ copying
1121 /// semantics are too complex to express here, in part because they depend
1122 /// on the exact constructor or assignment operator that is chosen by
1123 /// overload resolution to do the copy.
1127 /// Check if this is a non-trivial type that would cause a C struct
1128 /// transitively containing this type to be non-trivial to copy and return the
1130 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
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 destructively
1134 /// move and return the kind. Destructive move in this context is a C++-style
1135 /// move in which the source object is placed in a valid but unspecified state
1136 /// after it is moved, as opposed to a truly destructive move in which the
1137 /// source object is placed in an uninitialized state.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1140 enum DestructionKind {
1143 DK_objc_strong_lifetime,
1144 DK_objc_weak_lifetime,
1145 DK_nontrivial_c_struct
1148 /// Returns a nonzero value if objects of this type require
1149 /// non-trivial work to clean up after. Non-zero because it's
1150 /// conceivable that qualifiers (objc_gc(weak)?) could make
1151 /// something require destruction.
1152 DestructionKind isDestructedType() const {
1153 return isDestructedTypeImpl(*this);
1156 /// Determine whether expressions of the given type are forbidden
1157 /// from being lvalues in C.
1159 /// The expression types that are forbidden to be lvalues are:
1160 /// - 'void', but not qualified void
1161 /// - function types
1163 /// The exact rule here is C99 6.3.2.1:
1164 /// An lvalue is an expression with an object type or an incomplete
1165 /// type other than void.
1166 bool isCForbiddenLValueType() const;
1168 /// Substitute type arguments for the Objective-C type parameters used in the
1171 /// \param ctx ASTContext in which the type exists.
1173 /// \param typeArgs The type arguments that will be substituted for the
1174 /// Objective-C type parameters in the subject type, which are generally
1175 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1176 /// parameters will be replaced with their bounds or id/Class, as appropriate
1177 /// for the context.
1179 /// \param context The context in which the subject type was written.
1181 /// \returns the resulting type.
1182 QualType substObjCTypeArgs(ASTContext &ctx,
1183 ArrayRef<QualType> typeArgs,
1184 ObjCSubstitutionContext context) const;
1186 /// Substitute type arguments from an object type for the Objective-C type
1187 /// parameters used in the subject type.
1189 /// This operation combines the computation of type arguments for
1190 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1191 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1192 /// callers that need to perform a single substitution in isolation.
1194 /// \param objectType The type of the object whose member type we're
1195 /// substituting into. For example, this might be the receiver of a message
1196 /// or the base of a property access.
1198 /// \param dc The declaration context from which the subject type was
1199 /// retrieved, which indicates (for example) which type parameters should
1202 /// \param context The context in which the subject type was written.
1204 /// \returns the subject type after replacing all of the Objective-C type
1205 /// parameters with their corresponding arguments.
1206 QualType substObjCMemberType(QualType objectType,
1207 const DeclContext *dc,
1208 ObjCSubstitutionContext context) const;
1210 /// Strip Objective-C "__kindof" types from the given type.
1211 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1213 /// Remove all qualifiers including _Atomic.
1214 QualType getAtomicUnqualifiedType() const;
1217 // These methods are implemented in a separate translation unit;
1218 // "static"-ize them to avoid creating temporary QualTypes in the
1220 static bool isConstant(QualType T, const ASTContext& Ctx);
1221 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1222 static SplitQualType getSplitDesugaredType(QualType T);
1223 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1224 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1225 const ASTContext &C);
1226 static QualType IgnoreParens(QualType T);
1227 static DestructionKind isDestructedTypeImpl(QualType type);
1230 } // namespace clang
1234 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1235 /// to a specific Type class.
1236 template<> struct simplify_type< ::clang::QualType> {
1237 using SimpleType = const ::clang::Type *;
1239 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1240 return Val.getTypePtr();
1244 // Teach SmallPtrSet that QualType is "basically a pointer".
1246 struct PointerLikeTypeTraits<clang::QualType> {
1247 static inline void *getAsVoidPointer(clang::QualType P) {
1248 return P.getAsOpaquePtr();
1251 static inline clang::QualType getFromVoidPointer(void *P) {
1252 return clang::QualType::getFromOpaquePtr(P);
1255 // Various qualifiers go in low bits.
1256 enum { NumLowBitsAvailable = 0 };
1263 /// Base class that is common to both the \c ExtQuals and \c Type
1264 /// classes, which allows \c QualType to access the common fields between the
1266 class ExtQualsTypeCommonBase {
1267 friend class ExtQuals;
1268 friend class QualType;
1271 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1272 /// a self-referential pointer (for \c Type).
1274 /// This pointer allows an efficient mapping from a QualType to its
1275 /// underlying type pointer.
1276 const Type *const BaseType;
1278 /// The canonical type of this type. A QualType.
1279 QualType CanonicalType;
1281 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1282 : BaseType(baseType), CanonicalType(canon) {}
1285 /// We can encode up to four bits in the low bits of a
1286 /// type pointer, but there are many more type qualifiers that we want
1287 /// to be able to apply to an arbitrary type. Therefore we have this
1288 /// struct, intended to be heap-allocated and used by QualType to
1289 /// store qualifiers.
1291 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1292 /// in three low bits on the QualType pointer; a fourth bit records whether
1293 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1294 /// Objective-C GC attributes) are much more rare.
1295 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1296 // NOTE: changing the fast qualifiers should be straightforward as
1297 // long as you don't make 'const' non-fast.
1299 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1300 // Fast qualifiers must occupy the low-order bits.
1301 // b) Update Qualifiers::FastWidth and FastMask.
1303 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1304 // b) Update remove{Volatile,Restrict}, defined near the end of
1307 // a) Update get{Volatile,Restrict}Type.
1309 /// The immutable set of qualifiers applied by this node. Always contains
1310 /// extended qualifiers.
1313 ExtQuals *this_() { return this; }
1316 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1317 : ExtQualsTypeCommonBase(baseType,
1318 canon.isNull() ? QualType(this_(), 0) : canon),
1320 assert(Quals.hasNonFastQualifiers()
1321 && "ExtQuals created with no fast qualifiers");
1322 assert(!Quals.hasFastQualifiers()
1323 && "ExtQuals created with fast qualifiers");
1326 Qualifiers getQualifiers() const { return Quals; }
1328 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1329 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1331 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1332 Qualifiers::ObjCLifetime getObjCLifetime() const {
1333 return Quals.getObjCLifetime();
1336 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1337 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1339 const Type *getBaseType() const { return BaseType; }
1342 void Profile(llvm::FoldingSetNodeID &ID) const {
1343 Profile(ID, getBaseType(), Quals);
1346 static void Profile(llvm::FoldingSetNodeID &ID,
1347 const Type *BaseType,
1349 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1350 ID.AddPointer(BaseType);
1355 /// The kind of C++11 ref-qualifier associated with a function type.
1356 /// This determines whether a member function's "this" object can be an
1357 /// lvalue, rvalue, or neither.
1358 enum RefQualifierKind {
1359 /// No ref-qualifier was provided.
1362 /// An lvalue ref-qualifier was provided (\c &).
1365 /// An rvalue ref-qualifier was provided (\c &&).
1369 /// Which keyword(s) were used to create an AutoType.
1370 enum class AutoTypeKeyword {
1377 /// __auto_type (GNU extension)
1381 /// The base class of the type hierarchy.
1383 /// A central concept with types is that each type always has a canonical
1384 /// type. A canonical type is the type with any typedef names stripped out
1385 /// of it or the types it references. For example, consider:
1387 /// typedef int foo;
1388 /// typedef foo* bar;
1389 /// 'int *' 'foo *' 'bar'
1391 /// There will be a Type object created for 'int'. Since int is canonical, its
1392 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1393 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1394 /// there is a PointerType that represents 'int*', which, like 'int', is
1395 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1396 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1399 /// Non-canonical types are useful for emitting diagnostics, without losing
1400 /// information about typedefs being used. Canonical types are useful for type
1401 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1402 /// about whether something has a particular form (e.g. is a function type),
1403 /// because they implicitly, recursively, strip all typedefs out of a type.
1405 /// Types, once created, are immutable.
1407 class Type : public ExtQualsTypeCommonBase {
1410 #define TYPE(Class, Base) Class,
1411 #define LAST_TYPE(Class) TypeLast = Class,
1412 #define ABSTRACT_TYPE(Class, Base)
1413 #include "clang/AST/TypeNodes.def"
1414 TagFirst = Record, TagLast = Enum
1418 /// Bitfields required by the Type class.
1419 class TypeBitfields {
1421 template <class T> friend class TypePropertyCache;
1423 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1426 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1427 unsigned Dependent : 1;
1429 /// Whether this type somehow involves a template parameter, even
1430 /// if the resolution of the type does not depend on a template parameter.
1431 unsigned InstantiationDependent : 1;
1433 /// Whether this type is a variably-modified type (C99 6.7.5).
1434 unsigned VariablyModified : 1;
1436 /// Whether this type contains an unexpanded parameter pack
1437 /// (for C++11 variadic templates).
1438 unsigned ContainsUnexpandedParameterPack : 1;
1440 /// True if the cache (i.e. the bitfields here starting with
1441 /// 'Cache') is valid.
1442 mutable unsigned CacheValid : 1;
1444 /// Linkage of this type.
1445 mutable unsigned CachedLinkage : 3;
1447 /// Whether this type involves and local or unnamed types.
1448 mutable unsigned CachedLocalOrUnnamed : 1;
1450 /// Whether this type comes from an AST file.
1451 mutable unsigned FromAST : 1;
1453 bool isCacheValid() const {
1457 Linkage getLinkage() const {
1458 assert(isCacheValid() && "getting linkage from invalid cache");
1459 return static_cast<Linkage>(CachedLinkage);
1462 bool hasLocalOrUnnamedType() const {
1463 assert(isCacheValid() && "getting linkage from invalid cache");
1464 return CachedLocalOrUnnamed;
1467 enum { NumTypeBits = 18 };
1470 // These classes allow subclasses to somewhat cleanly pack bitfields
1473 class ArrayTypeBitfields {
1474 friend class ArrayType;
1476 unsigned : NumTypeBits;
1478 /// CVR qualifiers from declarations like
1479 /// 'int X[static restrict 4]'. For function parameters only.
1480 unsigned IndexTypeQuals : 3;
1482 /// Storage class qualifiers from declarations like
1483 /// 'int X[static restrict 4]'. For function parameters only.
1484 /// Actually an ArrayType::ArraySizeModifier.
1485 unsigned SizeModifier : 3;
1488 class BuiltinTypeBitfields {
1489 friend class BuiltinType;
1491 unsigned : NumTypeBits;
1493 /// The kind (BuiltinType::Kind) of builtin type this is.
1497 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1498 /// Only common bits are stored here. Additional uncommon bits are stored
1499 /// in a trailing object after FunctionProtoType.
1500 class FunctionTypeBitfields {
1501 friend class FunctionProtoType;
1502 friend class FunctionType;
1504 unsigned : NumTypeBits;
1506 /// Extra information which affects how the function is called, like
1507 /// regparm and the calling convention.
1508 unsigned ExtInfo : 12;
1510 /// The ref-qualifier associated with a \c FunctionProtoType.
1512 /// This is a value of type \c RefQualifierKind.
1513 unsigned RefQualifier : 2;
1515 /// Used only by FunctionProtoType, put here to pack with the
1516 /// other bitfields.
1517 /// The qualifiers are part of FunctionProtoType because...
1519 /// C++ 8.3.5p4: The return type, the parameter type list and the
1520 /// cv-qualifier-seq, [...], are part of the function type.
1521 unsigned FastTypeQuals : Qualifiers::FastWidth;
1522 /// Whether this function has extended Qualifiers.
1523 unsigned HasExtQuals : 1;
1525 /// The number of parameters this function has, not counting '...'.
1526 /// According to [implimits] 8 bits should be enough here but this is
1527 /// somewhat easy to exceed with metaprogramming and so we would like to
1528 /// keep NumParams as wide as reasonably possible.
1529 unsigned NumParams : 16;
1531 /// The type of exception specification this function has.
1532 unsigned ExceptionSpecType : 4;
1534 /// Whether this function has extended parameter information.
1535 unsigned HasExtParameterInfos : 1;
1537 /// Whether the function is variadic.
1538 unsigned Variadic : 1;
1540 /// Whether this function has a trailing return type.
1541 unsigned HasTrailingReturn : 1;
1544 class ObjCObjectTypeBitfields {
1545 friend class ObjCObjectType;
1547 unsigned : NumTypeBits;
1549 /// The number of type arguments stored directly on this object type.
1550 unsigned NumTypeArgs : 7;
1552 /// The number of protocols stored directly on this object type.
1553 unsigned NumProtocols : 6;
1555 /// Whether this is a "kindof" type.
1556 unsigned IsKindOf : 1;
1559 class ReferenceTypeBitfields {
1560 friend class ReferenceType;
1562 unsigned : NumTypeBits;
1564 /// True if the type was originally spelled with an lvalue sigil.
1565 /// This is never true of rvalue references but can also be false
1566 /// on lvalue references because of C++0x [dcl.typedef]p9,
1569 /// typedef int &ref; // lvalue, spelled lvalue
1570 /// typedef int &&rvref; // rvalue
1571 /// ref &a; // lvalue, inner ref, spelled lvalue
1572 /// ref &&a; // lvalue, inner ref
1573 /// rvref &a; // lvalue, inner ref, spelled lvalue
1574 /// rvref &&a; // rvalue, inner ref
1575 unsigned SpelledAsLValue : 1;
1577 /// True if the inner type is a reference type. This only happens
1578 /// in non-canonical forms.
1579 unsigned InnerRef : 1;
1582 class TypeWithKeywordBitfields {
1583 friend class TypeWithKeyword;
1585 unsigned : NumTypeBits;
1587 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1588 unsigned Keyword : 8;
1591 enum { NumTypeWithKeywordBits = 8 };
1593 class ElaboratedTypeBitfields {
1594 friend class ElaboratedType;
1596 unsigned : NumTypeBits;
1597 unsigned : NumTypeWithKeywordBits;
1599 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1600 unsigned HasOwnedTagDecl : 1;
1603 class VectorTypeBitfields {
1604 friend class VectorType;
1605 friend class DependentVectorType;
1607 unsigned : NumTypeBits;
1609 /// The kind of vector, either a generic vector type or some
1610 /// target-specific vector type such as for AltiVec or Neon.
1611 unsigned VecKind : 3;
1613 /// The number of elements in the vector.
1614 unsigned NumElements : 29 - NumTypeBits;
1616 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1619 class AttributedTypeBitfields {
1620 friend class AttributedType;
1622 unsigned : NumTypeBits;
1624 /// An AttributedType::Kind
1625 unsigned AttrKind : 32 - NumTypeBits;
1628 class AutoTypeBitfields {
1629 friend class AutoType;
1631 unsigned : NumTypeBits;
1633 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1634 /// or '__auto_type'? AutoTypeKeyword value.
1635 unsigned Keyword : 2;
1638 class SubstTemplateTypeParmPackTypeBitfields {
1639 friend class SubstTemplateTypeParmPackType;
1641 unsigned : NumTypeBits;
1643 /// The number of template arguments in \c Arguments, which is
1644 /// expected to be able to hold at least 1024 according to [implimits].
1645 /// However as this limit is somewhat easy to hit with template
1646 /// metaprogramming we'd prefer to keep it as large as possible.
1647 /// At the moment it has been left as a non-bitfield since this type
1648 /// safely fits in 64 bits as an unsigned, so there is no reason to
1649 /// introduce the performance impact of a bitfield.
1653 class TemplateSpecializationTypeBitfields {
1654 friend class TemplateSpecializationType;
1656 unsigned : NumTypeBits;
1658 /// Whether this template specialization type is a substituted type alias.
1659 unsigned TypeAlias : 1;
1661 /// The number of template arguments named in this class template
1662 /// specialization, which is expected to be able to hold at least 1024
1663 /// according to [implimits]. However, as this limit is somewhat easy to
1664 /// hit with template metaprogramming we'd prefer to keep it as large
1665 /// as possible. At the moment it has been left as a non-bitfield since
1666 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1667 /// to introduce the performance impact of a bitfield.
1671 class DependentTemplateSpecializationTypeBitfields {
1672 friend class DependentTemplateSpecializationType;
1674 unsigned : NumTypeBits;
1675 unsigned : NumTypeWithKeywordBits;
1677 /// The number of template arguments named in this class template
1678 /// specialization, which is expected to be able to hold at least 1024
1679 /// according to [implimits]. However, as this limit is somewhat easy to
1680 /// hit with template metaprogramming we'd prefer to keep it as large
1681 /// as possible. At the moment it has been left as a non-bitfield since
1682 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1683 /// to introduce the performance impact of a bitfield.
1687 class PackExpansionTypeBitfields {
1688 friend class PackExpansionType;
1690 unsigned : NumTypeBits;
1692 /// The number of expansions that this pack expansion will
1693 /// generate when substituted (+1), which is expected to be able to
1694 /// hold at least 1024 according to [implimits]. However, as this limit
1695 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1696 /// keep it as large as possible. At the moment it has been left as a
1697 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1698 /// there is no reason to introduce the performance impact of a bitfield.
1700 /// This field will only have a non-zero value when some of the parameter
1701 /// packs that occur within the pattern have been substituted but others
1703 unsigned NumExpansions;
1707 TypeBitfields TypeBits;
1708 ArrayTypeBitfields ArrayTypeBits;
1709 AttributedTypeBitfields AttributedTypeBits;
1710 AutoTypeBitfields AutoTypeBits;
1711 BuiltinTypeBitfields BuiltinTypeBits;
1712 FunctionTypeBitfields FunctionTypeBits;
1713 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1714 ReferenceTypeBitfields ReferenceTypeBits;
1715 TypeWithKeywordBitfields TypeWithKeywordBits;
1716 ElaboratedTypeBitfields ElaboratedTypeBits;
1717 VectorTypeBitfields VectorTypeBits;
1718 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1719 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1720 DependentTemplateSpecializationTypeBitfields
1721 DependentTemplateSpecializationTypeBits;
1722 PackExpansionTypeBitfields PackExpansionTypeBits;
1725 static_assert(sizeof(TypeBitfields) <= 8,
1726 "TypeBitfields is larger than 8 bytes!");
1727 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1728 "ArrayTypeBitfields is larger than 8 bytes!");
1729 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1730 "AttributedTypeBitfields is larger than 8 bytes!");
1731 static_assert(sizeof(AutoTypeBitfields) <= 8,
1732 "AutoTypeBitfields is larger than 8 bytes!");
1733 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1734 "BuiltinTypeBitfields is larger than 8 bytes!");
1735 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1736 "FunctionTypeBitfields is larger than 8 bytes!");
1737 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1738 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1739 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1740 "ReferenceTypeBitfields is larger than 8 bytes!");
1741 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1742 "TypeWithKeywordBitfields is larger than 8 bytes!");
1743 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1744 "ElaboratedTypeBitfields is larger than 8 bytes!");
1745 static_assert(sizeof(VectorTypeBitfields) <= 8,
1746 "VectorTypeBitfields is larger than 8 bytes!");
1747 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1748 "SubstTemplateTypeParmPackTypeBitfields is larger"
1750 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1751 "TemplateSpecializationTypeBitfields is larger"
1753 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1754 "DependentTemplateSpecializationTypeBitfields is larger"
1756 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1757 "PackExpansionTypeBitfields is larger than 8 bytes");
1760 template <class T> friend class TypePropertyCache;
1762 /// Set whether this type comes from an AST file.
1763 void setFromAST(bool V = true) const {
1764 TypeBits.FromAST = V;
1768 friend class ASTContext;
1770 Type(TypeClass tc, QualType canon, bool Dependent,
1771 bool InstantiationDependent, bool VariablyModified,
1772 bool ContainsUnexpandedParameterPack)
1773 : ExtQualsTypeCommonBase(this,
1774 canon.isNull() ? QualType(this_(), 0) : canon) {
1776 TypeBits.Dependent = Dependent;
1777 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1778 TypeBits.VariablyModified = VariablyModified;
1779 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1780 TypeBits.CacheValid = false;
1781 TypeBits.CachedLocalOrUnnamed = false;
1782 TypeBits.CachedLinkage = NoLinkage;
1783 TypeBits.FromAST = false;
1786 // silence VC++ warning C4355: 'this' : used in base member initializer list
1787 Type *this_() { return this; }
1789 void setDependent(bool D = true) {
1790 TypeBits.Dependent = D;
1792 TypeBits.InstantiationDependent = true;
1795 void setInstantiationDependent(bool D = true) {
1796 TypeBits.InstantiationDependent = D; }
1798 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1800 void setContainsUnexpandedParameterPack(bool PP = true) {
1801 TypeBits.ContainsUnexpandedParameterPack = PP;
1805 friend class ASTReader;
1806 friend class ASTWriter;
1808 Type(const Type &) = delete;
1809 Type &operator=(const Type &) = delete;
1811 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1813 /// Whether this type comes from an AST file.
1814 bool isFromAST() const { return TypeBits.FromAST; }
1816 /// Whether this type is or contains an unexpanded parameter
1817 /// pack, used to support C++0x variadic templates.
1819 /// A type that contains a parameter pack shall be expanded by the
1820 /// ellipsis operator at some point. For example, the typedef in the
1821 /// following example contains an unexpanded parameter pack 'T':
1824 /// template<typename ...T>
1826 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1830 /// Note that this routine does not specify which
1831 bool containsUnexpandedParameterPack() const {
1832 return TypeBits.ContainsUnexpandedParameterPack;
1835 /// Determines if this type would be canonical if it had no further
1837 bool isCanonicalUnqualified() const {
1838 return CanonicalType == QualType(this, 0);
1841 /// Pull a single level of sugar off of this locally-unqualified type.
1842 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1843 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1844 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1846 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1847 /// object types, function types, and incomplete types.
1849 /// Return true if this is an incomplete type.
1850 /// A type that can describe objects, but which lacks information needed to
1851 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1852 /// routine will need to determine if the size is actually required.
1854 /// Def If non-null, and the type refers to some kind of declaration
1855 /// that can be completed (such as a C struct, C++ class, or Objective-C
1856 /// class), will be set to the declaration.
1857 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1859 /// Return true if this is an incomplete or object
1860 /// type, in other words, not a function type.
1861 bool isIncompleteOrObjectType() const {
1862 return !isFunctionType();
1865 /// Determine whether this type is an object type.
1866 bool isObjectType() const {
1867 // C++ [basic.types]p8:
1868 // An object type is a (possibly cv-qualified) type that is not a
1869 // function type, not a reference type, and not a void type.
1870 return !isReferenceType() && !isFunctionType() && !isVoidType();
1873 /// Return true if this is a literal type
1874 /// (C++11 [basic.types]p10)
1875 bool isLiteralType(const ASTContext &Ctx) const;
1877 /// Test if this type is a standard-layout type.
1878 /// (C++0x [basic.type]p9)
1879 bool isStandardLayoutType() const;
1881 /// Helper methods to distinguish type categories. All type predicates
1882 /// operate on the canonical type, ignoring typedefs and qualifiers.
1884 /// Returns true if the type is a builtin type.
1885 bool isBuiltinType() const;
1887 /// Test for a particular builtin type.
1888 bool isSpecificBuiltinType(unsigned K) const;
1890 /// Test for a type which does not represent an actual type-system type but
1891 /// is instead used as a placeholder for various convenient purposes within
1892 /// Clang. All such types are BuiltinTypes.
1893 bool isPlaceholderType() const;
1894 const BuiltinType *getAsPlaceholderType() const;
1896 /// Test for a specific placeholder type.
1897 bool isSpecificPlaceholderType(unsigned K) const;
1899 /// Test for a placeholder type other than Overload; see
1900 /// BuiltinType::isNonOverloadPlaceholderType.
1901 bool isNonOverloadPlaceholderType() const;
1903 /// isIntegerType() does *not* include complex integers (a GCC extension).
1904 /// isComplexIntegerType() can be used to test for complex integers.
1905 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1906 bool isEnumeralType() const;
1908 /// Determine whether this type is a scoped enumeration type.
1909 bool isScopedEnumeralType() const;
1910 bool isBooleanType() const;
1911 bool isCharType() const;
1912 bool isWideCharType() const;
1913 bool isChar8Type() const;
1914 bool isChar16Type() const;
1915 bool isChar32Type() const;
1916 bool isAnyCharacterType() const;
1917 bool isIntegralType(const ASTContext &Ctx) const;
1919 /// Determine whether this type is an integral or enumeration type.
1920 bool isIntegralOrEnumerationType() const;
1922 /// Determine whether this type is an integral or unscoped enumeration type.
1923 bool isIntegralOrUnscopedEnumerationType() const;
1925 /// Floating point categories.
1926 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1927 /// isComplexType() does *not* include complex integers (a GCC extension).
1928 /// isComplexIntegerType() can be used to test for complex integers.
1929 bool isComplexType() const; // C99 6.2.5p11 (complex)
1930 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1931 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1932 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1933 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1934 bool isFloat128Type() const;
1935 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1936 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1937 bool isVoidType() const; // C99 6.2.5p19
1938 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1939 bool isAggregateType() const;
1940 bool isFundamentalType() const;
1941 bool isCompoundType() const;
1943 // Type Predicates: Check to see if this type is structurally the specified
1944 // type, ignoring typedefs and qualifiers.
1945 bool isFunctionType() const;
1946 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1947 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1948 bool isPointerType() const;
1949 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1950 bool isBlockPointerType() const;
1951 bool isVoidPointerType() const;
1952 bool isReferenceType() const;
1953 bool isLValueReferenceType() const;
1954 bool isRValueReferenceType() const;
1955 bool isFunctionPointerType() const;
1956 bool isMemberPointerType() const;
1957 bool isMemberFunctionPointerType() const;
1958 bool isMemberDataPointerType() const;
1959 bool isArrayType() const;
1960 bool isConstantArrayType() const;
1961 bool isIncompleteArrayType() const;
1962 bool isVariableArrayType() const;
1963 bool isDependentSizedArrayType() const;
1964 bool isRecordType() const;
1965 bool isClassType() const;
1966 bool isStructureType() const;
1967 bool isObjCBoxableRecordType() const;
1968 bool isInterfaceType() const;
1969 bool isStructureOrClassType() const;
1970 bool isUnionType() const;
1971 bool isComplexIntegerType() const; // GCC _Complex integer type.
1972 bool isVectorType() const; // GCC vector type.
1973 bool isExtVectorType() const; // Extended vector type.
1974 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1975 bool isObjCObjectPointerType() const; // pointer to ObjC object
1976 bool isObjCRetainableType() const; // ObjC object or block pointer
1977 bool isObjCLifetimeType() const; // (array of)* retainable type
1978 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1979 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1980 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1981 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1982 // for the common case.
1983 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1984 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1985 bool isObjCQualifiedIdType() const; // id<foo>
1986 bool isObjCQualifiedClassType() const; // Class<foo>
1987 bool isObjCObjectOrInterfaceType() const;
1988 bool isObjCIdType() const; // id
1990 /// Was this type written with the special inert-in-ARC __unsafe_unretained
1993 /// This approximates the answer to the following question: if this
1994 /// translation unit were compiled in ARC, would this type be qualified
1995 /// with __unsafe_unretained?
1996 bool isObjCInertUnsafeUnretainedType() const {
1997 return hasAttr(attr::ObjCInertUnsafeUnretained);
2000 /// Whether the type is Objective-C 'id' or a __kindof type of an
2001 /// object type, e.g., __kindof NSView * or __kindof id
2004 /// \param bound Will be set to the bound on non-id subtype types,
2005 /// which will be (possibly specialized) Objective-C class type, or
2007 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2008 const ObjCObjectType *&bound) const;
2010 bool isObjCClassType() const; // Class
2012 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2013 /// Class type, e.g., __kindof Class <NSCopying>.
2015 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2016 /// here because Objective-C's type system cannot express "a class
2017 /// object for a subclass of NSFoo".
2018 bool isObjCClassOrClassKindOfType() const;
2020 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2021 bool isObjCSelType() const; // Class
2022 bool isObjCBuiltinType() const; // 'id' or 'Class'
2023 bool isObjCARCBridgableType() const;
2024 bool isCARCBridgableType() const;
2025 bool isTemplateTypeParmType() const; // C++ template type parameter
2026 bool isNullPtrType() const; // C++11 std::nullptr_t
2027 bool isAlignValT() const; // C++17 std::align_val_t
2028 bool isStdByteType() const; // C++17 std::byte
2029 bool isAtomicType() const; // C11 _Atomic()
2031 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2032 bool is##Id##Type() const;
2033 #include "clang/Basic/OpenCLImageTypes.def"
2035 bool isImageType() const; // Any OpenCL image type
2037 bool isSamplerT() const; // OpenCL sampler_t
2038 bool isEventT() const; // OpenCL event_t
2039 bool isClkEventT() const; // OpenCL clk_event_t
2040 bool isQueueT() const; // OpenCL queue_t
2041 bool isReserveIDT() const; // OpenCL reserve_id_t
2043 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2044 bool is##Id##Type() const;
2045 #include "clang/Basic/OpenCLExtensionTypes.def"
2046 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2047 bool isOCLIntelSubgroupAVCType() const;
2048 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2050 bool isPipeType() const; // OpenCL pipe type
2051 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2053 /// Determines if this type, which must satisfy
2054 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2055 /// than implicitly __strong.
2056 bool isObjCARCImplicitlyUnretainedType() const;
2058 /// Return the implicit lifetime for this type, which must not be dependent.
2059 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2061 enum ScalarTypeKind {
2064 STK_ObjCObjectPointer,
2069 STK_IntegralComplex,
2070 STK_FloatingComplex,
2074 /// Given that this is a scalar type, classify it.
2075 ScalarTypeKind getScalarTypeKind() const;
2077 /// Whether this type is a dependent type, meaning that its definition
2078 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2079 bool isDependentType() const { return TypeBits.Dependent; }
2081 /// Determine whether this type is an instantiation-dependent type,
2082 /// meaning that the type involves a template parameter (even if the
2083 /// definition does not actually depend on the type substituted for that
2084 /// template parameter).
2085 bool isInstantiationDependentType() const {
2086 return TypeBits.InstantiationDependent;
2089 /// Determine whether this type is an undeduced type, meaning that
2090 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2092 bool isUndeducedType() const;
2094 /// Whether this type is a variably-modified type (C99 6.7.5).
2095 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2097 /// Whether this type involves a variable-length array type
2098 /// with a definite size.
2099 bool hasSizedVLAType() const;
2101 /// Whether this type is or contains a local or unnamed type.
2102 bool hasUnnamedOrLocalType() const;
2104 bool isOverloadableType() const;
2106 /// Determine wither this type is a C++ elaborated-type-specifier.
2107 bool isElaboratedTypeSpecifier() const;
2109 bool canDecayToPointerType() const;
2111 /// Whether this type is represented natively as a pointer. This includes
2112 /// pointers, references, block pointers, and Objective-C interface,
2113 /// qualified id, and qualified interface types, as well as nullptr_t.
2114 bool hasPointerRepresentation() const;
2116 /// Whether this type can represent an objective pointer type for the
2117 /// purpose of GC'ability
2118 bool hasObjCPointerRepresentation() const;
2120 /// Determine whether this type has an integer representation
2121 /// of some sort, e.g., it is an integer type or a vector.
2122 bool hasIntegerRepresentation() const;
2124 /// Determine whether this type has an signed integer representation
2125 /// of some sort, e.g., it is an signed integer type or a vector.
2126 bool hasSignedIntegerRepresentation() const;
2128 /// Determine whether this type has an unsigned integer representation
2129 /// of some sort, e.g., it is an unsigned integer type or a vector.
2130 bool hasUnsignedIntegerRepresentation() const;
2132 /// Determine whether this type has a floating-point representation
2133 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2134 bool hasFloatingRepresentation() const;
2136 // Type Checking Functions: Check to see if this type is structurally the
2137 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2138 // the best type we can.
2139 const RecordType *getAsStructureType() const;
2140 /// NOTE: getAs*ArrayType are methods on ASTContext.
2141 const RecordType *getAsUnionType() const;
2142 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2143 const ObjCObjectType *getAsObjCInterfaceType() const;
2145 // The following is a convenience method that returns an ObjCObjectPointerType
2146 // for object declared using an interface.
2147 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2148 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2149 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2150 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2152 /// Retrieves the CXXRecordDecl that this type refers to, either
2153 /// because the type is a RecordType or because it is the injected-class-name
2154 /// type of a class template or class template partial specialization.
2155 CXXRecordDecl *getAsCXXRecordDecl() const;
2157 /// Retrieves the RecordDecl this type refers to.
2158 RecordDecl *getAsRecordDecl() const;
2160 /// Retrieves the TagDecl that this type refers to, either
2161 /// because the type is a TagType or because it is the injected-class-name
2162 /// type of a class template or class template partial specialization.
2163 TagDecl *getAsTagDecl() const;
2165 /// If this is a pointer or reference to a RecordType, return the
2166 /// CXXRecordDecl that the type refers to.
2168 /// If this is not a pointer or reference, or the type being pointed to does
2169 /// not refer to a CXXRecordDecl, returns NULL.
2170 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2172 /// Get the DeducedType whose type will be deduced for a variable with
2173 /// an initializer of this type. This looks through declarators like pointer
2174 /// types, but not through decltype or typedefs.
2175 DeducedType *getContainedDeducedType() const;
2177 /// Get the AutoType whose type will be deduced for a variable with
2178 /// an initializer of this type. This looks through declarators like pointer
2179 /// types, but not through decltype or typedefs.
2180 AutoType *getContainedAutoType() const {
2181 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2184 /// Determine whether this type was written with a leading 'auto'
2185 /// corresponding to a trailing return type (possibly for a nested
2186 /// function type within a pointer to function type or similar).
2187 bool hasAutoForTrailingReturnType() const;
2189 /// Member-template getAs<specific type>'. Look through sugar for
2190 /// an instance of \<specific type>. This scheme will eventually
2191 /// replace the specific getAsXXXX methods above.
2193 /// There are some specializations of this member template listed
2194 /// immediately following this class.
2195 template <typename T> const T *getAs() const;
2197 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2198 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2199 /// This is used when you need to walk over sugar nodes that represent some
2200 /// kind of type adjustment from a type that was written as a \<specific type>
2201 /// to another type that is still canonically a \<specific type>.
2202 template <typename T> const T *getAsAdjusted() const;
2204 /// A variant of getAs<> for array types which silently discards
2205 /// qualifiers from the outermost type.
2206 const ArrayType *getAsArrayTypeUnsafe() const;
2208 /// Member-template castAs<specific type>. Look through sugar for
2209 /// the underlying instance of \<specific type>.
2211 /// This method has the same relationship to getAs<T> as cast<T> has
2212 /// to dyn_cast<T>; which is to say, the underlying type *must*
2213 /// have the intended type, and this method will never return null.
2214 template <typename T> const T *castAs() const;
2216 /// A variant of castAs<> for array type which silently discards
2217 /// qualifiers from the outermost type.
2218 const ArrayType *castAsArrayTypeUnsafe() const;
2220 /// Determine whether this type had the specified attribute applied to it
2221 /// (looking through top-level type sugar).
2222 bool hasAttr(attr::Kind AK) const;
2224 /// Get the base element type of this type, potentially discarding type
2225 /// qualifiers. This should never be used when type qualifiers
2227 const Type *getBaseElementTypeUnsafe() const;
2229 /// If this is an array type, return the element type of the array,
2230 /// potentially with type qualifiers missing.
2231 /// This should never be used when type qualifiers are meaningful.
2232 const Type *getArrayElementTypeNoTypeQual() const;
2234 /// If this is a pointer type, return the pointee type.
2235 /// If this is an array type, return the array element type.
2236 /// This should never be used when type qualifiers are meaningful.
2237 const Type *getPointeeOrArrayElementType() const;
2239 /// If this is a pointer, ObjC object pointer, or block
2240 /// pointer, this returns the respective pointee.
2241 QualType getPointeeType() const;
2243 /// Return the specified type with any "sugar" removed from the type,
2244 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2245 const Type *getUnqualifiedDesugaredType() const;
2247 /// More type predicates useful for type checking/promotion
2248 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2250 /// Return true if this is an integer type that is
2251 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2252 /// or an enum decl which has a signed representation.
2253 bool isSignedIntegerType() const;
2255 /// Return true if this is an integer type that is
2256 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2257 /// or an enum decl which has an unsigned representation.
2258 bool isUnsignedIntegerType() const;
2260 /// Determines whether this is an integer type that is signed or an
2261 /// enumeration types whose underlying type is a signed integer type.
2262 bool isSignedIntegerOrEnumerationType() const;
2264 /// Determines whether this is an integer type that is unsigned or an
2265 /// enumeration types whose underlying type is a unsigned integer type.
2266 bool isUnsignedIntegerOrEnumerationType() const;
2268 /// Return true if this is a fixed point type according to
2269 /// ISO/IEC JTC1 SC22 WG14 N1169.
2270 bool isFixedPointType() const;
2272 /// Return true if this is a saturated fixed point type according to
2273 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2274 bool isSaturatedFixedPointType() const;
2276 /// Return true if this is a saturated fixed point type according to
2277 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2278 bool isUnsaturatedFixedPointType() const;
2280 /// Return true if this is a fixed point type that is signed according
2281 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2282 bool isSignedFixedPointType() const;
2284 /// Return true if this is a fixed point type that is unsigned according
2285 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2286 bool isUnsignedFixedPointType() const;
2288 /// Return true if this is not a variable sized type,
2289 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2290 /// incomplete types.
2291 bool isConstantSizeType() const;
2293 /// Returns true if this type can be represented by some
2294 /// set of type specifiers.
2295 bool isSpecifierType() const;
2297 /// Determine the linkage of this type.
2298 Linkage getLinkage() const;
2300 /// Determine the visibility of this type.
2301 Visibility getVisibility() const {
2302 return getLinkageAndVisibility().getVisibility();
2305 /// Return true if the visibility was explicitly set is the code.
2306 bool isVisibilityExplicit() const {
2307 return getLinkageAndVisibility().isVisibilityExplicit();
2310 /// Determine the linkage and visibility of this type.
2311 LinkageInfo getLinkageAndVisibility() const;
2313 /// True if the computed linkage is valid. Used for consistency
2314 /// checking. Should always return true.
2315 bool isLinkageValid() const;
2317 /// Determine the nullability of the given type.
2319 /// Note that nullability is only captured as sugar within the type
2320 /// system, not as part of the canonical type, so nullability will
2321 /// be lost by canonicalization and desugaring.
2322 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2324 /// Determine whether the given type can have a nullability
2325 /// specifier applied to it, i.e., if it is any kind of pointer type.
2327 /// \param ResultIfUnknown The value to return if we don't yet know whether
2328 /// this type can have nullability because it is dependent.
2329 bool canHaveNullability(bool ResultIfUnknown = true) const;
2331 /// Retrieve the set of substitutions required when accessing a member
2332 /// of the Objective-C receiver type that is declared in the given context.
2334 /// \c *this is the type of the object we're operating on, e.g., the
2335 /// receiver for a message send or the base of a property access, and is
2336 /// expected to be of some object or object pointer type.
2338 /// \param dc The declaration context for which we are building up a
2339 /// substitution mapping, which should be an Objective-C class, extension,
2340 /// category, or method within.
2342 /// \returns an array of type arguments that can be substituted for
2343 /// the type parameters of the given declaration context in any type described
2344 /// within that context, or an empty optional to indicate that no
2345 /// substitution is required.
2346 Optional<ArrayRef<QualType>>
2347 getObjCSubstitutions(const DeclContext *dc) const;
2349 /// Determines if this is an ObjC interface type that may accept type
2351 bool acceptsObjCTypeParams() const;
2353 const char *getTypeClassName() const;
2355 QualType getCanonicalTypeInternal() const {
2356 return CanonicalType;
2359 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2361 void dump(llvm::raw_ostream &OS) const;
2364 /// This will check for a TypedefType by removing any existing sugar
2365 /// until it reaches a TypedefType or a non-sugared type.
2366 template <> const TypedefType *Type::getAs() const;
2368 /// This will check for a TemplateSpecializationType by removing any
2369 /// existing sugar until it reaches a TemplateSpecializationType or a
2370 /// non-sugared type.
2371 template <> const TemplateSpecializationType *Type::getAs() const;
2373 /// This will check for an AttributedType by removing any existing sugar
2374 /// until it reaches an AttributedType or a non-sugared type.
2375 template <> const AttributedType *Type::getAs() const;
2377 // We can do canonical leaf types faster, because we don't have to
2378 // worry about preserving child type decoration.
2379 #define TYPE(Class, Base)
2380 #define LEAF_TYPE(Class) \
2381 template <> inline const Class##Type *Type::getAs() const { \
2382 return dyn_cast<Class##Type>(CanonicalType); \
2384 template <> inline const Class##Type *Type::castAs() const { \
2385 return cast<Class##Type>(CanonicalType); \
2387 #include "clang/AST/TypeNodes.def"
2389 /// This class is used for builtin types like 'int'. Builtin
2390 /// types are always canonical and have a literal name field.
2391 class BuiltinType : public Type {
2394 // OpenCL image types
2395 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2396 #include "clang/Basic/OpenCLImageTypes.def"
2397 // OpenCL extension types
2398 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2399 #include "clang/Basic/OpenCLExtensionTypes.def"
2400 // All other builtin types
2401 #define BUILTIN_TYPE(Id, SingletonId) Id,
2402 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2403 #include "clang/AST/BuiltinTypes.def"
2407 friend class ASTContext; // ASTContext creates these.
2410 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2411 /*InstantiationDependent=*/(K == Dependent),
2412 /*VariablyModified=*/false,
2413 /*Unexpanded parameter pack=*/false) {
2414 BuiltinTypeBits.Kind = K;
2418 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2419 StringRef getName(const PrintingPolicy &Policy) const;
2421 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2422 // The StringRef is null-terminated.
2423 StringRef str = getName(Policy);
2424 assert(!str.empty() && str.data()[str.size()] == '\0');
2428 bool isSugared() const { return false; }
2429 QualType desugar() const { return QualType(this, 0); }
2431 bool isInteger() const {
2432 return getKind() >= Bool && getKind() <= Int128;
2435 bool isSignedInteger() const {
2436 return getKind() >= Char_S && getKind() <= Int128;
2439 bool isUnsignedInteger() const {
2440 return getKind() >= Bool && getKind() <= UInt128;
2443 bool isFloatingPoint() const {
2444 return getKind() >= Half && getKind() <= Float128;
2447 /// Determines whether the given kind corresponds to a placeholder type.
2448 static bool isPlaceholderTypeKind(Kind K) {
2449 return K >= Overload;
2452 /// Determines whether this type is a placeholder type, i.e. a type
2453 /// which cannot appear in arbitrary positions in a fully-formed
2455 bool isPlaceholderType() const {
2456 return isPlaceholderTypeKind(getKind());
2459 /// Determines whether this type is a placeholder type other than
2460 /// Overload. Most placeholder types require only syntactic
2461 /// information about their context in order to be resolved (e.g.
2462 /// whether it is a call expression), which means they can (and
2463 /// should) be resolved in an earlier "phase" of analysis.
2464 /// Overload expressions sometimes pick up further information
2465 /// from their context, like whether the context expects a
2466 /// specific function-pointer type, and so frequently need
2467 /// special treatment.
2468 bool isNonOverloadPlaceholderType() const {
2469 return getKind() > Overload;
2472 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2475 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2476 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2477 class ComplexType : public Type, public llvm::FoldingSetNode {
2478 friend class ASTContext; // ASTContext creates these.
2480 QualType ElementType;
2482 ComplexType(QualType Element, QualType CanonicalPtr)
2483 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2484 Element->isInstantiationDependentType(),
2485 Element->isVariablyModifiedType(),
2486 Element->containsUnexpandedParameterPack()),
2487 ElementType(Element) {}
2490 QualType getElementType() const { return ElementType; }
2492 bool isSugared() const { return false; }
2493 QualType desugar() const { return QualType(this, 0); }
2495 void Profile(llvm::FoldingSetNodeID &ID) {
2496 Profile(ID, getElementType());
2499 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2500 ID.AddPointer(Element.getAsOpaquePtr());
2503 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2506 /// Sugar for parentheses used when specifying types.
2507 class ParenType : public Type, public llvm::FoldingSetNode {
2508 friend class ASTContext; // ASTContext creates these.
2512 ParenType(QualType InnerType, QualType CanonType)
2513 : Type(Paren, CanonType, InnerType->isDependentType(),
2514 InnerType->isInstantiationDependentType(),
2515 InnerType->isVariablyModifiedType(),
2516 InnerType->containsUnexpandedParameterPack()),
2520 QualType getInnerType() const { return Inner; }
2522 bool isSugared() const { return true; }
2523 QualType desugar() const { return getInnerType(); }
2525 void Profile(llvm::FoldingSetNodeID &ID) {
2526 Profile(ID, getInnerType());
2529 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2533 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2536 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2537 class PointerType : public Type, public llvm::FoldingSetNode {
2538 friend class ASTContext; // ASTContext creates these.
2540 QualType PointeeType;
2542 PointerType(QualType Pointee, QualType CanonicalPtr)
2543 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2544 Pointee->isInstantiationDependentType(),
2545 Pointee->isVariablyModifiedType(),
2546 Pointee->containsUnexpandedParameterPack()),
2547 PointeeType(Pointee) {}
2550 QualType getPointeeType() const { return PointeeType; }
2552 /// Returns true if address spaces of pointers overlap.
2553 /// OpenCL v2.0 defines conversion rules for pointers to different
2554 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2557 /// address spaces overlap iff they are they same.
2559 /// __generic overlaps with any address space except for __constant.
2560 bool isAddressSpaceOverlapping(const PointerType &other) const {
2561 Qualifiers thisQuals = PointeeType.getQualifiers();
2562 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2563 // Address spaces overlap if at least one of them is a superset of another
2564 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2565 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2568 bool isSugared() const { return false; }
2569 QualType desugar() const { return QualType(this, 0); }
2571 void Profile(llvm::FoldingSetNodeID &ID) {
2572 Profile(ID, getPointeeType());
2575 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2576 ID.AddPointer(Pointee.getAsOpaquePtr());
2579 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2582 /// Represents a type which was implicitly adjusted by the semantic
2583 /// engine for arbitrary reasons. For example, array and function types can
2584 /// decay, and function types can have their calling conventions adjusted.
2585 class AdjustedType : public Type, public llvm::FoldingSetNode {
2586 QualType OriginalTy;
2587 QualType AdjustedTy;
2590 friend class ASTContext; // ASTContext creates these.
2592 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2593 QualType CanonicalPtr)
2594 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2595 OriginalTy->isInstantiationDependentType(),
2596 OriginalTy->isVariablyModifiedType(),
2597 OriginalTy->containsUnexpandedParameterPack()),
2598 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2601 QualType getOriginalType() const { return OriginalTy; }
2602 QualType getAdjustedType() const { return AdjustedTy; }
2604 bool isSugared() const { return true; }
2605 QualType desugar() const { return AdjustedTy; }
2607 void Profile(llvm::FoldingSetNodeID &ID) {
2608 Profile(ID, OriginalTy, AdjustedTy);
2611 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2612 ID.AddPointer(Orig.getAsOpaquePtr());
2613 ID.AddPointer(New.getAsOpaquePtr());
2616 static bool classof(const Type *T) {
2617 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2621 /// Represents a pointer type decayed from an array or function type.
2622 class DecayedType : public AdjustedType {
2623 friend class ASTContext; // ASTContext creates these.
2626 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2629 QualType getDecayedType() const { return getAdjustedType(); }
2631 inline QualType getPointeeType() const;
2633 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2636 /// Pointer to a block type.
2637 /// This type is to represent types syntactically represented as
2638 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2639 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2640 friend class ASTContext; // ASTContext creates these.
2642 // Block is some kind of pointer type
2643 QualType PointeeType;
2645 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2646 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2647 Pointee->isInstantiationDependentType(),
2648 Pointee->isVariablyModifiedType(),
2649 Pointee->containsUnexpandedParameterPack()),
2650 PointeeType(Pointee) {}
2653 // Get the pointee type. Pointee is required to always be a function type.
2654 QualType getPointeeType() const { return PointeeType; }
2656 bool isSugared() const { return false; }
2657 QualType desugar() const { return QualType(this, 0); }
2659 void Profile(llvm::FoldingSetNodeID &ID) {
2660 Profile(ID, getPointeeType());
2663 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2664 ID.AddPointer(Pointee.getAsOpaquePtr());
2667 static bool classof(const Type *T) {
2668 return T->getTypeClass() == BlockPointer;
2672 /// Base for LValueReferenceType and RValueReferenceType
2673 class ReferenceType : public Type, public llvm::FoldingSetNode {
2674 QualType PointeeType;
2677 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2678 bool SpelledAsLValue)
2679 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2680 Referencee->isInstantiationDependentType(),
2681 Referencee->isVariablyModifiedType(),
2682 Referencee->containsUnexpandedParameterPack()),
2683 PointeeType(Referencee) {
2684 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2685 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2689 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2690 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2692 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2694 QualType getPointeeType() const {
2695 // FIXME: this might strip inner qualifiers; okay?
2696 const ReferenceType *T = this;
2697 while (T->isInnerRef())
2698 T = T->PointeeType->castAs<ReferenceType>();
2699 return T->PointeeType;
2702 void Profile(llvm::FoldingSetNodeID &ID) {
2703 Profile(ID, PointeeType, isSpelledAsLValue());
2706 static void Profile(llvm::FoldingSetNodeID &ID,
2707 QualType Referencee,
2708 bool SpelledAsLValue) {
2709 ID.AddPointer(Referencee.getAsOpaquePtr());
2710 ID.AddBoolean(SpelledAsLValue);
2713 static bool classof(const Type *T) {
2714 return T->getTypeClass() == LValueReference ||
2715 T->getTypeClass() == RValueReference;
2719 /// An lvalue reference type, per C++11 [dcl.ref].
2720 class LValueReferenceType : public ReferenceType {
2721 friend class ASTContext; // ASTContext creates these
2723 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2724 bool SpelledAsLValue)
2725 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2729 bool isSugared() const { return false; }
2730 QualType desugar() const { return QualType(this, 0); }
2732 static bool classof(const Type *T) {
2733 return T->getTypeClass() == LValueReference;
2737 /// An rvalue reference type, per C++11 [dcl.ref].
2738 class RValueReferenceType : public ReferenceType {
2739 friend class ASTContext; // ASTContext creates these
2741 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2742 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2745 bool isSugared() const { return false; }
2746 QualType desugar() const { return QualType(this, 0); }
2748 static bool classof(const Type *T) {
2749 return T->getTypeClass() == RValueReference;
2753 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2755 /// This includes both pointers to data members and pointer to member functions.
2756 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2757 friend class ASTContext; // ASTContext creates these.
2759 QualType PointeeType;
2761 /// The class of which the pointee is a member. Must ultimately be a
2762 /// RecordType, but could be a typedef or a template parameter too.
2765 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2766 : Type(MemberPointer, CanonicalPtr,
2767 Cls->isDependentType() || Pointee->isDependentType(),
2768 (Cls->isInstantiationDependentType() ||
2769 Pointee->isInstantiationDependentType()),
2770 Pointee->isVariablyModifiedType(),
2771 (Cls->containsUnexpandedParameterPack() ||
2772 Pointee->containsUnexpandedParameterPack())),
2773 PointeeType(Pointee), Class(Cls) {}
2776 QualType getPointeeType() const { return PointeeType; }
2778 /// Returns true if the member type (i.e. the pointee type) is a
2779 /// function type rather than a data-member type.
2780 bool isMemberFunctionPointer() const {
2781 return PointeeType->isFunctionProtoType();
2784 /// Returns true if the member type (i.e. the pointee type) is a
2785 /// data type rather than a function type.
2786 bool isMemberDataPointer() const {
2787 return !PointeeType->isFunctionProtoType();
2790 const Type *getClass() const { return Class; }
2791 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2793 bool isSugared() const { return false; }
2794 QualType desugar() const { return QualType(this, 0); }
2796 void Profile(llvm::FoldingSetNodeID &ID) {
2797 Profile(ID, getPointeeType(), getClass());
2800 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2801 const Type *Class) {
2802 ID.AddPointer(Pointee.getAsOpaquePtr());
2803 ID.AddPointer(Class);
2806 static bool classof(const Type *T) {
2807 return T->getTypeClass() == MemberPointer;
2811 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2812 class ArrayType : public Type, public llvm::FoldingSetNode {
2814 /// Capture whether this is a normal array (e.g. int X[4])
2815 /// an array with a static size (e.g. int X[static 4]), or an array
2816 /// with a star size (e.g. int X[*]).
2817 /// 'static' is only allowed on function parameters.
2818 enum ArraySizeModifier {
2819 Normal, Static, Star
2823 /// The element type of the array.
2824 QualType ElementType;
2827 friend class ASTContext; // ASTContext creates these.
2829 // C++ [temp.dep.type]p1:
2830 // A type is dependent if it is...
2831 // - an array type constructed from any dependent type or whose
2832 // size is specified by a constant expression that is
2834 ArrayType(TypeClass tc, QualType et, QualType can,
2835 ArraySizeModifier sm, unsigned tq,
2836 bool ContainsUnexpandedParameterPack)
2837 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2838 et->isInstantiationDependentType() || tc == DependentSizedArray,
2839 (tc == VariableArray || et->isVariablyModifiedType()),
2840 ContainsUnexpandedParameterPack),
2842 ArrayTypeBits.IndexTypeQuals = tq;
2843 ArrayTypeBits.SizeModifier = sm;
2847 QualType getElementType() const { return ElementType; }
2849 ArraySizeModifier getSizeModifier() const {
2850 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2853 Qualifiers getIndexTypeQualifiers() const {
2854 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2857 unsigned getIndexTypeCVRQualifiers() const {
2858 return ArrayTypeBits.IndexTypeQuals;
2861 static bool classof(const Type *T) {
2862 return T->getTypeClass() == ConstantArray ||
2863 T->getTypeClass() == VariableArray ||
2864 T->getTypeClass() == IncompleteArray ||
2865 T->getTypeClass() == DependentSizedArray;
2869 /// Represents the canonical version of C arrays with a specified constant size.
2870 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2871 /// ConstantArrayType where the element type is 'int' and the size is 404.
2872 class ConstantArrayType : public ArrayType {
2873 llvm::APInt Size; // Allows us to unique the type.
2875 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2876 ArraySizeModifier sm, unsigned tq)
2877 : ArrayType(ConstantArray, et, can, sm, tq,
2878 et->containsUnexpandedParameterPack()),
2882 friend class ASTContext; // ASTContext creates these.
2884 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2885 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2886 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2890 const llvm::APInt &getSize() const { return Size; }
2891 bool isSugared() const { return false; }
2892 QualType desugar() const { return QualType(this, 0); }
2894 /// Determine the number of bits required to address a member of
2895 // an array with the given element type and number of elements.
2896 static unsigned getNumAddressingBits(const ASTContext &Context,
2897 QualType ElementType,
2898 const llvm::APInt &NumElements);
2900 /// Determine the maximum number of active bits that an array's size
2901 /// can require, which limits the maximum size of the array.
2902 static unsigned getMaxSizeBits(const ASTContext &Context);
2904 void Profile(llvm::FoldingSetNodeID &ID) {
2905 Profile(ID, getElementType(), getSize(),
2906 getSizeModifier(), getIndexTypeCVRQualifiers());
2909 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2910 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2911 unsigned TypeQuals) {
2912 ID.AddPointer(ET.getAsOpaquePtr());
2913 ID.AddInteger(ArraySize.getZExtValue());
2914 ID.AddInteger(SizeMod);
2915 ID.AddInteger(TypeQuals);
2918 static bool classof(const Type *T) {
2919 return T->getTypeClass() == ConstantArray;
2923 /// Represents a C array with an unspecified size. For example 'int A[]' has
2924 /// an IncompleteArrayType where the element type is 'int' and the size is
2926 class IncompleteArrayType : public ArrayType {
2927 friend class ASTContext; // ASTContext creates these.
2929 IncompleteArrayType(QualType et, QualType can,
2930 ArraySizeModifier sm, unsigned tq)
2931 : ArrayType(IncompleteArray, et, can, sm, tq,
2932 et->containsUnexpandedParameterPack()) {}
2935 friend class StmtIteratorBase;
2937 bool isSugared() const { return false; }
2938 QualType desugar() const { return QualType(this, 0); }
2940 static bool classof(const Type *T) {
2941 return T->getTypeClass() == IncompleteArray;
2944 void Profile(llvm::FoldingSetNodeID &ID) {
2945 Profile(ID, getElementType(), getSizeModifier(),
2946 getIndexTypeCVRQualifiers());
2949 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2950 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2951 ID.AddPointer(ET.getAsOpaquePtr());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2957 /// Represents a C array with a specified size that is not an
2958 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2959 /// Since the size expression is an arbitrary expression, we store it as such.
2961 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2962 /// should not be: two lexically equivalent variable array types could mean
2963 /// different things, for example, these variables do not have the same type
2966 /// void foo(int x) {
2971 class VariableArrayType : public ArrayType {
2972 friend class ASTContext; // ASTContext creates these.
2974 /// An assignment-expression. VLA's are only permitted within
2975 /// a function block.
2978 /// The range spanned by the left and right array brackets.
2979 SourceRange Brackets;
2981 VariableArrayType(QualType et, QualType can, Expr *e,
2982 ArraySizeModifier sm, unsigned tq,
2983 SourceRange brackets)
2984 : ArrayType(VariableArray, et, can, sm, tq,
2985 et->containsUnexpandedParameterPack()),
2986 SizeExpr((Stmt*) e), Brackets(brackets) {}
2989 friend class StmtIteratorBase;
2991 Expr *getSizeExpr() const {
2992 // We use C-style casts instead of cast<> here because we do not wish
2993 // to have a dependency of Type.h on Stmt.h/Expr.h.
2994 return (Expr*) SizeExpr;
2997 SourceRange getBracketsRange() const { return Brackets; }
2998 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2999 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3001 bool isSugared() const { return false; }
3002 QualType desugar() const { return QualType(this, 0); }
3004 static bool classof(const Type *T) {
3005 return T->getTypeClass() == VariableArray;
3008 void Profile(llvm::FoldingSetNodeID &ID) {
3009 llvm_unreachable("Cannot unique VariableArrayTypes.");
3013 /// Represents an array type in C++ whose size is a value-dependent expression.
3017 /// template<typename T, int Size>
3023 /// For these types, we won't actually know what the array bound is
3024 /// until template instantiation occurs, at which point this will
3025 /// become either a ConstantArrayType or a VariableArrayType.
3026 class DependentSizedArrayType : public ArrayType {
3027 friend class ASTContext; // ASTContext creates these.
3029 const ASTContext &Context;
3031 /// An assignment expression that will instantiate to the
3032 /// size of the array.
3034 /// The expression itself might be null, in which case the array
3035 /// type will have its size deduced from an initializer.
3038 /// The range spanned by the left and right array brackets.
3039 SourceRange Brackets;
3041 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3042 Expr *e, ArraySizeModifier sm, unsigned tq,
3043 SourceRange brackets);
3046 friend class StmtIteratorBase;
3048 Expr *getSizeExpr() const {
3049 // We use C-style casts instead of cast<> here because we do not wish
3050 // to have a dependency of Type.h on Stmt.h/Expr.h.
3051 return (Expr*) SizeExpr;
3054 SourceRange getBracketsRange() const { return Brackets; }
3055 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3056 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3058 bool isSugared() const { return false; }
3059 QualType desugar() const { return QualType(this, 0); }
3061 static bool classof(const Type *T) {
3062 return T->getTypeClass() == DependentSizedArray;
3065 void Profile(llvm::FoldingSetNodeID &ID) {
3066 Profile(ID, Context, getElementType(),
3067 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3070 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3071 QualType ET, ArraySizeModifier SizeMod,
3072 unsigned TypeQuals, Expr *E);
3075 /// Represents an extended address space qualifier where the input address space
3076 /// value is dependent. Non-dependent address spaces are not represented with a
3077 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3081 /// template<typename T, int AddrSpace>
3082 /// class AddressSpace {
3083 /// typedef T __attribute__((address_space(AddrSpace))) type;
3086 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3087 friend class ASTContext;
3089 const ASTContext &Context;
3090 Expr *AddrSpaceExpr;
3091 QualType PointeeType;
3094 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3095 QualType can, Expr *AddrSpaceExpr,
3096 SourceLocation loc);
3099 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3100 QualType getPointeeType() const { return PointeeType; }
3101 SourceLocation getAttributeLoc() const { return loc; }
3103 bool isSugared() const { return false; }
3104 QualType desugar() const { return QualType(this, 0); }
3106 static bool classof(const Type *T) {
3107 return T->getTypeClass() == DependentAddressSpace;
3110 void Profile(llvm::FoldingSetNodeID &ID) {
3111 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3114 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3115 QualType PointeeType, Expr *AddrSpaceExpr);
3118 /// Represents an extended vector type where either the type or size is
3123 /// template<typename T, int Size>
3125 /// typedef T __attribute__((ext_vector_type(Size))) type;
3128 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3129 friend class ASTContext;
3131 const ASTContext &Context;
3134 /// The element type of the array.
3135 QualType ElementType;
3139 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3140 QualType can, Expr *SizeExpr, SourceLocation loc);
3143 Expr *getSizeExpr() const { return SizeExpr; }
3144 QualType getElementType() const { return ElementType; }
3145 SourceLocation getAttributeLoc() const { return loc; }
3147 bool isSugared() const { return false; }
3148 QualType desugar() const { return QualType(this, 0); }
3150 static bool classof(const Type *T) {
3151 return T->getTypeClass() == DependentSizedExtVector;
3154 void Profile(llvm::FoldingSetNodeID &ID) {
3155 Profile(ID, Context, getElementType(), getSizeExpr());
3158 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3159 QualType ElementType, Expr *SizeExpr);
3163 /// Represents a GCC generic vector type. This type is created using
3164 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3165 /// bytes; or from an Altivec __vector or vector declaration.
3166 /// Since the constructor takes the number of vector elements, the
3167 /// client is responsible for converting the size into the number of elements.
3168 class VectorType : public Type, public llvm::FoldingSetNode {
3171 /// not a target-specific vector type
3174 /// is AltiVec vector
3177 /// is AltiVec 'vector Pixel'
3180 /// is AltiVec 'vector bool ...'
3183 /// is ARM Neon vector
3186 /// is ARM Neon polynomial vector
3191 friend class ASTContext; // ASTContext creates these.
3193 /// The element type of the vector.
3194 QualType ElementType;
3196 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3197 VectorKind vecKind);
3199 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3200 QualType canonType, VectorKind vecKind);
3203 QualType getElementType() const { return ElementType; }
3204 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3206 static bool isVectorSizeTooLarge(unsigned NumElements) {
3207 return NumElements > VectorTypeBitfields::MaxNumElements;
3210 bool isSugared() const { return false; }
3211 QualType desugar() const { return QualType(this, 0); }
3213 VectorKind getVectorKind() const {
3214 return VectorKind(VectorTypeBits.VecKind);
3217 void Profile(llvm::FoldingSetNodeID &ID) {
3218 Profile(ID, getElementType(), getNumElements(),
3219 getTypeClass(), getVectorKind());
3222 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3223 unsigned NumElements, TypeClass TypeClass,
3224 VectorKind VecKind) {
3225 ID.AddPointer(ElementType.getAsOpaquePtr());
3226 ID.AddInteger(NumElements);
3227 ID.AddInteger(TypeClass);
3228 ID.AddInteger(VecKind);
3231 static bool classof(const Type *T) {
3232 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3236 /// Represents a vector type where either the type or size is dependent.
3240 /// template<typename T, int Size>
3242 /// typedef T __attribute__((vector_size(Size))) type;
3245 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3246 friend class ASTContext;
3248 const ASTContext &Context;
3249 QualType ElementType;
3253 DependentVectorType(const ASTContext &Context, QualType ElementType,
3254 QualType CanonType, Expr *SizeExpr,
3255 SourceLocation Loc, VectorType::VectorKind vecKind);
3258 Expr *getSizeExpr() const { return SizeExpr; }
3259 QualType getElementType() const { return ElementType; }
3260 SourceLocation getAttributeLoc() const { return Loc; }
3261 VectorType::VectorKind getVectorKind() const {
3262 return VectorType::VectorKind(VectorTypeBits.VecKind);
3265 bool isSugared() const { return false; }
3266 QualType desugar() const { return QualType(this, 0); }
3268 static bool classof(const Type *T) {
3269 return T->getTypeClass() == DependentVector;
3272 void Profile(llvm::FoldingSetNodeID &ID) {
3273 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3276 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3277 QualType ElementType, const Expr *SizeExpr,
3278 VectorType::VectorKind VecKind);
3281 /// ExtVectorType - Extended vector type. This type is created using
3282 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3283 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3284 /// class enables syntactic extensions, like Vector Components for accessing
3285 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3286 /// Shading Language).
3287 class ExtVectorType : public VectorType {
3288 friend class ASTContext; // ASTContext creates these.
3290 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3291 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3294 static int getPointAccessorIdx(char c) {
3297 case 'x': case 'r': return 0;
3298 case 'y': case 'g': return 1;
3299 case 'z': case 'b': return 2;
3300 case 'w': case 'a': return 3;
3304 static int getNumericAccessorIdx(char c) {
3318 case 'a': return 10;
3320 case 'b': return 11;
3322 case 'c': return 12;
3324 case 'd': return 13;
3326 case 'e': return 14;
3328 case 'f': return 15;
3332 static int getAccessorIdx(char c, bool isNumericAccessor) {
3333 if (isNumericAccessor)
3334 return getNumericAccessorIdx(c);
3336 return getPointAccessorIdx(c);
3339 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3340 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3341 return unsigned(idx-1) < getNumElements();
3345 bool isSugared() const { return false; }
3346 QualType desugar() const { return QualType(this, 0); }
3348 static bool classof(const Type *T) {
3349 return T->getTypeClass() == ExtVector;
3353 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3354 /// class of FunctionNoProtoType and FunctionProtoType.
3355 class FunctionType : public Type {
3356 // The type returned by the function.
3357 QualType ResultType;
3360 /// Interesting information about a specific parameter that can't simply
3361 /// be reflected in parameter's type. This is only used by FunctionProtoType
3362 /// but is in FunctionType to make this class available during the
3363 /// specification of the bases of FunctionProtoType.
3365 /// It makes sense to model language features this way when there's some
3366 /// sort of parameter-specific override (such as an attribute) that
3367 /// affects how the function is called. For example, the ARC ns_consumed
3368 /// attribute changes whether a parameter is passed at +0 (the default)
3369 /// or +1 (ns_consumed). This must be reflected in the function type,
3370 /// but isn't really a change to the parameter type.
3372 /// One serious disadvantage of modelling language features this way is
3373 /// that they generally do not work with language features that attempt
3374 /// to destructure types. For example, template argument deduction will
3375 /// not be able to match a parameter declared as
3377 /// against an argument of type
3378 /// void (*)(__attribute__((ns_consumed)) id)
3379 /// because the substitution of T=void, U=id into the former will
3380 /// not produce the latter.
3381 class ExtParameterInfo {
3385 HasPassObjSize = 0x20,
3388 unsigned char Data = 0;
3391 ExtParameterInfo() = default;
3393 /// Return the ABI treatment of this parameter.
3394 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3395 ExtParameterInfo withABI(ParameterABI kind) const {
3396 ExtParameterInfo copy = *this;
3397 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3401 /// Is this parameter considered "consumed" by Objective-C ARC?
3402 /// Consumed parameters must have retainable object type.
3403 bool isConsumed() const { return (Data & IsConsumed); }
3404 ExtParameterInfo withIsConsumed(bool consumed) const {
3405 ExtParameterInfo copy = *this;
3407 copy.Data |= IsConsumed;
3409 copy.Data &= ~IsConsumed;
3413 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3414 ExtParameterInfo withHasPassObjectSize() const {
3415 ExtParameterInfo Copy = *this;
3416 Copy.Data |= HasPassObjSize;
3420 bool isNoEscape() const { return Data & IsNoEscape; }
3421 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3422 ExtParameterInfo Copy = *this;
3424 Copy.Data |= IsNoEscape;
3426 Copy.Data &= ~IsNoEscape;
3430 unsigned char getOpaqueValue() const { return Data; }
3431 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3432 ExtParameterInfo result;
3437 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3438 return lhs.Data == rhs.Data;
3441 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3442 return lhs.Data != rhs.Data;
3446 /// A class which abstracts out some details necessary for
3449 /// It is not actually used directly for storing this information in
3450 /// a FunctionType, although FunctionType does currently use the
3451 /// same bit-pattern.
3453 // If you add a field (say Foo), other than the obvious places (both,
3454 // constructors, compile failures), what you need to update is
3458 // * functionType. Add Foo, getFoo.
3459 // * ASTContext::getFooType
3460 // * ASTContext::mergeFunctionTypes
3461 // * FunctionNoProtoType::Profile
3462 // * FunctionProtoType::Profile
3463 // * TypePrinter::PrintFunctionProto
3464 // * AST read and write
3467 friend class FunctionType;
3469 // Feel free to rearrange or add bits, but if you go over 12,
3470 // you'll need to adjust both the Bits field below and
3471 // Type::FunctionTypeBitfields.
3473 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3474 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3476 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3477 enum { CallConvMask = 0x1F };
3478 enum { NoReturnMask = 0x20 };
3479 enum { ProducesResultMask = 0x40 };
3480 enum { NoCallerSavedRegsMask = 0x80 };
3481 enum { NoCfCheckMask = 0x800 };
3483 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3484 NoCallerSavedRegsMask | NoCfCheckMask),
3486 }; // Assumed to be the last field
3487 uint16_t Bits = CC_C;
3489 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3492 // Constructor with no defaults. Use this when you know that you
3493 // have all the elements (when reading an AST file for example).
3494 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3495 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3496 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3497 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3498 (producesResult ? ProducesResultMask : 0) |
3499 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3500 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3501 (NoCfCheck ? NoCfCheckMask : 0);
3504 // Constructor with all defaults. Use when for example creating a
3505 // function known to use defaults.
3506 ExtInfo() = default;
3508 // Constructor with just the calling convention, which is an important part
3509 // of the canonical type.
3510 ExtInfo(CallingConv CC) : Bits(CC) {}
3512 bool getNoReturn() const { return Bits & NoReturnMask; }
3513 bool getProducesResult() const { return Bits & ProducesResultMask; }
3514 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3515 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3516 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3518 unsigned getRegParm() const {
3519 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3525 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3527 bool operator==(ExtInfo Other) const {
3528 return Bits == Other.Bits;
3530 bool operator!=(ExtInfo Other) const {
3531 return Bits != Other.Bits;
3534 // Note that we don't have setters. That is by design, use
3535 // the following with methods instead of mutating these objects.
3537 ExtInfo withNoReturn(bool noReturn) const {
3539 return ExtInfo(Bits | NoReturnMask);
3541 return ExtInfo(Bits & ~NoReturnMask);
3544 ExtInfo withProducesResult(bool producesResult) const {
3546 return ExtInfo(Bits | ProducesResultMask);
3548 return ExtInfo(Bits & ~ProducesResultMask);
3551 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3552 if (noCallerSavedRegs)
3553 return ExtInfo(Bits | NoCallerSavedRegsMask);
3555 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3558 ExtInfo withNoCfCheck(bool noCfCheck) const {
3560 return ExtInfo(Bits | NoCfCheckMask);
3562 return ExtInfo(Bits & ~NoCfCheckMask);
3565 ExtInfo withRegParm(unsigned RegParm) const {
3566 assert(RegParm < 7 && "Invalid regparm value");
3567 return ExtInfo((Bits & ~RegParmMask) |
3568 ((RegParm + 1) << RegParmOffset));
3571 ExtInfo withCallingConv(CallingConv cc) const {
3572 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3575 void Profile(llvm::FoldingSetNodeID &ID) const {
3576 ID.AddInteger(Bits);
3580 /// A simple holder for a QualType representing a type in an
3581 /// exception specification. Unfortunately needed by FunctionProtoType
3582 /// because TrailingObjects cannot handle repeated types.
3583 struct ExceptionType { QualType Type; };
3585 /// A simple holder for various uncommon bits which do not fit in
3586 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3587 /// alignment of subsequent objects in TrailingObjects. You must update
3588 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3589 struct alignas(void *) FunctionTypeExtraBitfields {
3590 /// The number of types in the exception specification.
3591 /// A whole unsigned is not needed here and according to
3592 /// [implimits] 8 bits would be enough here.
3593 unsigned NumExceptionType;
3597 FunctionType(TypeClass tc, QualType res,
3598 QualType Canonical, bool Dependent,
3599 bool InstantiationDependent,
3600 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3602 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3603 ContainsUnexpandedParameterPack),
3605 FunctionTypeBits.ExtInfo = Info.Bits;
3608 Qualifiers getFastTypeQuals() const {
3609 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3613 QualType getReturnType() const { return ResultType; }
3615 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3616 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3618 /// Determine whether this function type includes the GNU noreturn
3619 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3621 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3623 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3624 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3626 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3627 "Const, volatile and restrict are assumed to be a subset of "
3628 "the fast qualifiers.");
3630 bool isConst() const { return getFastTypeQuals().hasConst(); }
3631 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3632 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3634 /// Determine the type of an expression that calls a function of
3636 QualType getCallResultType(const ASTContext &Context) const {
3637 return getReturnType().getNonLValueExprType(Context);
3640 static StringRef getNameForCallConv(CallingConv CC);
3642 static bool classof(const Type *T) {
3643 return T->getTypeClass() == FunctionNoProto ||
3644 T->getTypeClass() == FunctionProto;
3648 /// Represents a K&R-style 'int foo()' function, which has
3649 /// no information available about its arguments.
3650 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3651 friend class ASTContext; // ASTContext creates these.
3653 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3654 : FunctionType(FunctionNoProto, Result, Canonical,
3655 /*Dependent=*/false, /*InstantiationDependent=*/false,
3656 Result->isVariablyModifiedType(),
3657 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3660 // No additional state past what FunctionType provides.
3662 bool isSugared() const { return false; }
3663 QualType desugar() const { return QualType(this, 0); }
3665 void Profile(llvm::FoldingSetNodeID &ID) {
3666 Profile(ID, getReturnType(), getExtInfo());
3669 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3672 ID.AddPointer(ResultType.getAsOpaquePtr());
3675 static bool classof(const Type *T) {
3676 return T->getTypeClass() == FunctionNoProto;
3680 /// Represents a prototype with parameter type info, e.g.
3681 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3682 /// parameters, not as having a single void parameter. Such a type can have
3683 /// an exception specification, but this specification is not part of the
3684 /// canonical type. FunctionProtoType has several trailing objects, some of
3685 /// which optional. For more information about the trailing objects see
3686 /// the first comment inside FunctionProtoType.
3687 class FunctionProtoType final
3688 : public FunctionType,
3689 public llvm::FoldingSetNode,
3690 private llvm::TrailingObjects<
3691 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3692 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3693 FunctionType::ExtParameterInfo, Qualifiers> {
3694 friend class ASTContext; // ASTContext creates these.
3695 friend TrailingObjects;
3697 // FunctionProtoType is followed by several trailing objects, some of
3698 // which optional. They are in order:
3700 // * An array of getNumParams() QualType holding the parameter types.
3701 // Always present. Note that for the vast majority of FunctionProtoType,
3702 // these will be the only trailing objects.
3704 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3705 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3706 // a single FunctionTypeExtraBitfields. Present if and only if
3707 // hasExtraBitfields() is true.
3709 // * Optionally exactly one of:
3710 // * an array of getNumExceptions() ExceptionType,
3711 // * a single Expr *,
3712 // * a pair of FunctionDecl *,
3713 // * a single FunctionDecl *
3714 // used to store information about the various types of exception
3715 // specification. See getExceptionSpecSize for the details.
3717 // * Optionally an array of getNumParams() ExtParameterInfo holding
3718 // an ExtParameterInfo for each of the parameters. Present if and
3719 // only if hasExtParameterInfos() is true.
3721 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3722 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3723 // if hasExtQualifiers() is true.
3725 // The optional FunctionTypeExtraBitfields has to be before the data
3726 // related to the exception specification since it contains the number
3727 // of exception types.
3729 // We put the ExtParameterInfos last. If all were equal, it would make
3730 // more sense to put these before the exception specification, because
3731 // it's much easier to skip past them compared to the elaborate switch
3732 // required to skip the exception specification. However, all is not
3733 // equal; ExtParameterInfos are used to model very uncommon features,
3734 // and it's better not to burden the more common paths.
3737 /// Holds information about the various types of exception specification.
3738 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3739 /// used to group together the various bits of information about the
3740 /// exception specification.
3741 struct ExceptionSpecInfo {
3742 /// The kind of exception specification this is.
3743 ExceptionSpecificationType Type = EST_None;
3745 /// Explicitly-specified list of exception types.
3746 ArrayRef<QualType> Exceptions;
3748 /// Noexcept expression, if this is a computed noexcept specification.
3749 Expr *NoexceptExpr = nullptr;
3751 /// The function whose exception specification this is, for
3752 /// EST_Unevaluated and EST_Uninstantiated.
3753 FunctionDecl *SourceDecl = nullptr;
3755 /// The function template whose exception specification this is instantiated
3756 /// from, for EST_Uninstantiated.
3757 FunctionDecl *SourceTemplate = nullptr;
3759 ExceptionSpecInfo() = default;
3761 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3764 /// Extra information about a function prototype. ExtProtoInfo is not
3765 /// stored as such in FunctionProtoType but is used to group together
3766 /// the various bits of extra information about a function prototype.
3767 struct ExtProtoInfo {
3768 FunctionType::ExtInfo ExtInfo;
3770 bool HasTrailingReturn : 1;
3771 Qualifiers TypeQuals;
3772 RefQualifierKind RefQualifier = RQ_None;
3773 ExceptionSpecInfo ExceptionSpec;
3774 const ExtParameterInfo *ExtParameterInfos = nullptr;
3776 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3778 ExtProtoInfo(CallingConv CC)
3779 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3781 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3782 ExtProtoInfo Result(*this);
3783 Result.ExceptionSpec = ESI;
3789 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3790 return getNumParams();
3793 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3794 return hasExtraBitfields();
3797 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3798 return getExceptionSpecSize().NumExceptionType;
3801 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3802 return getExceptionSpecSize().NumExprPtr;
3805 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3806 return getExceptionSpecSize().NumFunctionDeclPtr;
3809 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3810 return hasExtParameterInfos() ? getNumParams() : 0;
3813 /// Determine whether there are any argument types that
3814 /// contain an unexpanded parameter pack.
3815 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3817 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3818 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3824 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3825 QualType canonical, const ExtProtoInfo &epi);
3827 /// This struct is returned by getExceptionSpecSize and is used to
3828 /// translate an ExceptionSpecificationType to the number and kind
3829 /// of trailing objects related to the exception specification.
3830 struct ExceptionSpecSizeHolder {
3831 unsigned NumExceptionType;
3832 unsigned NumExprPtr;
3833 unsigned NumFunctionDeclPtr;
3836 /// Return the number and kind of trailing objects
3837 /// related to the exception specification.
3838 static ExceptionSpecSizeHolder
3839 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3842 case EST_DynamicNone:
3844 case EST_BasicNoexcept:
3849 return {NumExceptions, 0, 0};
3851 case EST_DependentNoexcept:
3852 case EST_NoexceptFalse:
3853 case EST_NoexceptTrue:
3856 case EST_Uninstantiated:
3859 case EST_Unevaluated:
3862 llvm_unreachable("bad exception specification kind");
3865 /// Return the number and kind of trailing objects
3866 /// related to the exception specification.
3867 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3868 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3871 /// Whether the trailing FunctionTypeExtraBitfields is present.
3872 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3873 // If the exception spec type is EST_Dynamic then we have > 0 exception
3874 // types and the exact number is stored in FunctionTypeExtraBitfields.
3875 return EST == EST_Dynamic;
3878 /// Whether the trailing FunctionTypeExtraBitfields is present.
3879 bool hasExtraBitfields() const {
3880 return hasExtraBitfields(getExceptionSpecType());
3883 bool hasExtQualifiers() const {
3884 return FunctionTypeBits.HasExtQuals;
3888 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3890 QualType getParamType(unsigned i) const {
3891 assert(i < getNumParams() && "invalid parameter index");
3892 return param_type_begin()[i];
3895 ArrayRef<QualType> getParamTypes() const {
3896 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3899 ExtProtoInfo getExtProtoInfo() const {
3901 EPI.ExtInfo = getExtInfo();
3902 EPI.Variadic = isVariadic();
3903 EPI.HasTrailingReturn = hasTrailingReturn();
3904 EPI.ExceptionSpec.Type = getExceptionSpecType();
3905 EPI.TypeQuals = getTypeQuals();
3906 EPI.RefQualifier = getRefQualifier();
3907 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3908 EPI.ExceptionSpec.Exceptions = exceptions();
3909 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3910 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3911 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3912 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3913 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3914 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3915 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3917 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3921 /// Get the kind of exception specification on this function.
3922 ExceptionSpecificationType getExceptionSpecType() const {
3923 return static_cast<ExceptionSpecificationType>(
3924 FunctionTypeBits.ExceptionSpecType);
3927 /// Return whether this function has any kind of exception spec.
3928 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3930 /// Return whether this function has a dynamic (throw) exception spec.
3931 bool hasDynamicExceptionSpec() const {
3932 return isDynamicExceptionSpec(getExceptionSpecType());
3935 /// Return whether this function has a noexcept exception spec.
3936 bool hasNoexceptExceptionSpec() const {
3937 return isNoexceptExceptionSpec(getExceptionSpecType());
3940 /// Return whether this function has a dependent exception spec.
3941 bool hasDependentExceptionSpec() const;
3943 /// Return whether this function has an instantiation-dependent exception
3945 bool hasInstantiationDependentExceptionSpec() const;
3947 /// Return the number of types in the exception specification.
3948 unsigned getNumExceptions() const {
3949 return getExceptionSpecType() == EST_Dynamic
3950 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3955 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3956 QualType getExceptionType(unsigned i) const {
3957 assert(i < getNumExceptions() && "Invalid exception number!");
3958 return exception_begin()[i];
3961 /// Return the expression inside noexcept(expression), or a null pointer
3962 /// if there is none (because the exception spec is not of this form).
3963 Expr *getNoexceptExpr() const {
3964 if (!isComputedNoexcept(getExceptionSpecType()))
3966 return *getTrailingObjects<Expr *>();
3969 /// If this function type has an exception specification which hasn't
3970 /// been determined yet (either because it has not been evaluated or because
3971 /// it has not been instantiated), this is the function whose exception
3972 /// specification is represented by this type.
3973 FunctionDecl *getExceptionSpecDecl() const {
3974 if (getExceptionSpecType() != EST_Uninstantiated &&
3975 getExceptionSpecType() != EST_Unevaluated)
3977 return getTrailingObjects<FunctionDecl *>()[0];
3980 /// If this function type has an uninstantiated exception
3981 /// specification, this is the function whose exception specification
3982 /// should be instantiated to find the exception specification for
3984 FunctionDecl *getExceptionSpecTemplate() const {
3985 if (getExceptionSpecType() != EST_Uninstantiated)
3987 return getTrailingObjects<FunctionDecl *>()[1];
3990 /// Determine whether this function type has a non-throwing exception
3992 CanThrowResult canThrow() const;
3994 /// Determine whether this function type has a non-throwing exception
3995 /// specification. If this depends on template arguments, returns
3996 /// \c ResultIfDependent.
3997 bool isNothrow(bool ResultIfDependent = false) const {
3998 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4001 /// Whether this function prototype is variadic.
4002 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4004 /// Determines whether this function prototype contains a
4005 /// parameter pack at the end.
4007 /// A function template whose last parameter is a parameter pack can be
4008 /// called with an arbitrary number of arguments, much like a variadic
4010 bool isTemplateVariadic() const;
4012 /// Whether this function prototype has a trailing return type.
4013 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4015 Qualifiers getTypeQuals() const {
4016 if (hasExtQualifiers())
4017 return *getTrailingObjects<Qualifiers>();
4019 return getFastTypeQuals();
4022 /// Retrieve the ref-qualifier associated with this function type.
4023 RefQualifierKind getRefQualifier() const {
4024 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4027 using param_type_iterator = const QualType *;
4028 using param_type_range = llvm::iterator_range<param_type_iterator>;
4030 param_type_range param_types() const {
4031 return param_type_range(param_type_begin(), param_type_end());
4034 param_type_iterator param_type_begin() const {
4035 return getTrailingObjects<QualType>();
4038 param_type_iterator param_type_end() const {
4039 return param_type_begin() + getNumParams();
4042 using exception_iterator = const QualType *;
4044 ArrayRef<QualType> exceptions() const {
4045 return llvm::makeArrayRef(exception_begin(), exception_end());
4048 exception_iterator exception_begin() const {
4049 return reinterpret_cast<exception_iterator>(
4050 getTrailingObjects<ExceptionType>());
4053 exception_iterator exception_end() const {
4054 return exception_begin() + getNumExceptions();
4057 /// Is there any interesting extra information for any of the parameters
4058 /// of this function type?
4059 bool hasExtParameterInfos() const {
4060 return FunctionTypeBits.HasExtParameterInfos;
4063 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4064 assert(hasExtParameterInfos());
4065 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4069 /// Return a pointer to the beginning of the array of extra parameter
4070 /// information, if present, or else null if none of the parameters
4071 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4072 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4073 if (!hasExtParameterInfos())
4075 return getTrailingObjects<ExtParameterInfo>();
4078 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4079 assert(I < getNumParams() && "parameter index out of range");
4080 if (hasExtParameterInfos())
4081 return getTrailingObjects<ExtParameterInfo>()[I];
4082 return ExtParameterInfo();
4085 ParameterABI getParameterABI(unsigned I) const {
4086 assert(I < getNumParams() && "parameter index out of range");
4087 if (hasExtParameterInfos())
4088 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4089 return ParameterABI::Ordinary;
4092 bool isParamConsumed(unsigned I) const {
4093 assert(I < getNumParams() && "parameter index out of range");
4094 if (hasExtParameterInfos())
4095 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4099 bool isSugared() const { return false; }
4100 QualType desugar() const { return QualType(this, 0); }
4102 void printExceptionSpecification(raw_ostream &OS,
4103 const PrintingPolicy &Policy) const;
4105 static bool classof(const Type *T) {
4106 return T->getTypeClass() == FunctionProto;
4109 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4110 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4111 param_type_iterator ArgTys, unsigned NumArgs,
4112 const ExtProtoInfo &EPI, const ASTContext &Context,
4116 /// Represents the dependent type named by a dependently-scoped
4117 /// typename using declaration, e.g.
4118 /// using typename Base<T>::foo;
4120 /// Template instantiation turns these into the underlying type.
4121 class UnresolvedUsingType : public Type {
4122 friend class ASTContext; // ASTContext creates these.
4124 UnresolvedUsingTypenameDecl *Decl;
4126 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4127 : Type(UnresolvedUsing, QualType(), true, true, false,
4128 /*ContainsUnexpandedParameterPack=*/false),
4129 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4132 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4134 bool isSugared() const { return false; }
4135 QualType desugar() const { return QualType(this, 0); }
4137 static bool classof(const Type *T) {
4138 return T->getTypeClass() == UnresolvedUsing;
4141 void Profile(llvm::FoldingSetNodeID &ID) {
4142 return Profile(ID, Decl);
4145 static void Profile(llvm::FoldingSetNodeID &ID,
4146 UnresolvedUsingTypenameDecl *D) {
4151 class TypedefType : public Type {
4152 TypedefNameDecl *Decl;
4155 friend class ASTContext; // ASTContext creates these.
4157 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4158 : Type(tc, can, can->isDependentType(),
4159 can->isInstantiationDependentType(),
4160 can->isVariablyModifiedType(),
4161 /*ContainsUnexpandedParameterPack=*/false),
4162 Decl(const_cast<TypedefNameDecl*>(D)) {
4163 assert(!isa<TypedefType>(can) && "Invalid canonical type");
4167 TypedefNameDecl *getDecl() const { return Decl; }
4169 bool isSugared() const { return true; }
4170 QualType desugar() const;
4172 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4175 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4176 class TypeOfExprType : public Type {
4180 friend class ASTContext; // ASTContext creates these.
4182 TypeOfExprType(Expr *E, QualType can = QualType());
4185 Expr *getUnderlyingExpr() const { return TOExpr; }
4187 /// Remove a single level of sugar.
4188 QualType desugar() const;
4190 /// Returns whether this type directly provides sugar.
4191 bool isSugared() const;
4193 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4196 /// Internal representation of canonical, dependent
4197 /// `typeof(expr)` types.
4199 /// This class is used internally by the ASTContext to manage
4200 /// canonical, dependent types, only. Clients will only see instances
4201 /// of this class via TypeOfExprType nodes.
4202 class DependentTypeOfExprType
4203 : public TypeOfExprType, public llvm::FoldingSetNode {
4204 const ASTContext &Context;
4207 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4208 : TypeOfExprType(E), Context(Context) {}
4210 void Profile(llvm::FoldingSetNodeID &ID) {
4211 Profile(ID, Context, getUnderlyingExpr());
4214 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4218 /// Represents `typeof(type)`, a GCC extension.
4219 class TypeOfType : public Type {
4220 friend class ASTContext; // ASTContext creates these.
4224 TypeOfType(QualType T, QualType can)
4225 : Type(TypeOf, can, T->isDependentType(),
4226 T->isInstantiationDependentType(),
4227 T->isVariablyModifiedType(),
4228 T->containsUnexpandedParameterPack()),
4230 assert(!isa<TypedefType>(can) && "Invalid canonical type");
4234 QualType getUnderlyingType() const { return TOType; }
4236 /// Remove a single level of sugar.
4237 QualType desugar() const { return getUnderlyingType(); }
4239 /// Returns whether this type directly provides sugar.
4240 bool isSugared() const { return true; }
4242 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4245 /// Represents the type `decltype(expr)` (C++11).
4246 class DecltypeType : public Type {
4248 QualType UnderlyingType;
4251 friend class ASTContext; // ASTContext creates these.
4253 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4256 Expr *getUnderlyingExpr() const { return E; }
4257 QualType getUnderlyingType() const { return UnderlyingType; }
4259 /// Remove a single level of sugar.
4260 QualType desugar() const;
4262 /// Returns whether this type directly provides sugar.
4263 bool isSugared() const;
4265 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4268 /// Internal representation of canonical, dependent
4269 /// decltype(expr) types.
4271 /// This class is used internally by the ASTContext to manage
4272 /// canonical, dependent types, only. Clients will only see instances
4273 /// of this class via DecltypeType nodes.
4274 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4275 const ASTContext &Context;
4278 DependentDecltypeType(const ASTContext &Context, Expr *E);
4280 void Profile(llvm::FoldingSetNodeID &ID) {
4281 Profile(ID, Context, getUnderlyingExpr());
4284 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4288 /// A unary type transform, which is a type constructed from another.
4289 class UnaryTransformType : public Type {
4296 /// The untransformed type.
4299 /// The transformed type if not dependent, otherwise the same as BaseType.
4300 QualType UnderlyingType;
4305 friend class ASTContext;
4307 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4308 QualType CanonicalTy);
4311 bool isSugared() const { return !isDependentType(); }
4312 QualType desugar() const { return UnderlyingType; }
4314 QualType getUnderlyingType() const { return UnderlyingType; }
4315 QualType getBaseType() const { return BaseType; }
4317 UTTKind getUTTKind() const { return UKind; }
4319 static bool classof(const Type *T) {
4320 return T->getTypeClass() == UnaryTransform;
4324 /// Internal representation of canonical, dependent
4325 /// __underlying_type(type) types.
4327 /// This class is used internally by the ASTContext to manage
4328 /// canonical, dependent types, only. Clients will only see instances
4329 /// of this class via UnaryTransformType nodes.
4330 class DependentUnaryTransformType : public UnaryTransformType,
4331 public llvm::FoldingSetNode {
4333 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4336 void Profile(llvm::FoldingSetNodeID &ID) {
4337 Profile(ID, getBaseType(), getUTTKind());
4340 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4342 ID.AddPointer(BaseType.getAsOpaquePtr());
4343 ID.AddInteger((unsigned)UKind);
4347 class TagType : public Type {
4348 friend class ASTReader;
4350 /// Stores the TagDecl associated with this type. The decl may point to any
4351 /// TagDecl that declares the entity.
4355 TagType(TypeClass TC, const TagDecl *D, QualType can);
4358 TagDecl *getDecl() const;
4360 /// Determines whether this type is in the process of being defined.
4361 bool isBeingDefined() const;
4363 static bool classof(const Type *T) {
4364 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
4368 /// A helper class that allows the use of isa/cast/dyncast
4369 /// to detect TagType objects of structs/unions/classes.
4370 class RecordType : public TagType {
4372 friend class ASTContext; // ASTContext creates these.
4374 explicit RecordType(const RecordDecl *D)
4375 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4376 explicit RecordType(TypeClass TC, RecordDecl *D)
4377 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4380 RecordDecl *getDecl() const {
4381 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4384 /// Recursively check all fields in the record for const-ness. If any field
4385 /// is declared const, return true. Otherwise, return false.
4386 bool hasConstFields() const;
4388 bool isSugared() const { return false; }
4389 QualType desugar() const { return QualType(this, 0); }
4391 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4394 /// A helper class that allows the use of isa/cast/dyncast
4395 /// to detect TagType objects of enums.
4396 class EnumType : public TagType {
4397 friend class ASTContext; // ASTContext creates these.
4399 explicit EnumType(const EnumDecl *D)
4400 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4403 EnumDecl *getDecl() const {
4404 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4407 bool isSugared() const { return false; }
4408 QualType desugar() const { return QualType(this, 0); }
4410 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4413 /// An attributed type is a type to which a type attribute has been applied.
4415 /// The "modified type" is the fully-sugared type to which the attributed
4416 /// type was applied; generally it is not canonically equivalent to the
4417 /// attributed type. The "equivalent type" is the minimally-desugared type
4418 /// which the type is canonically equivalent to.
4420 /// For example, in the following attributed type:
4421 /// int32_t __attribute__((vector_size(16)))
4422 /// - the modified type is the TypedefType for int32_t
4423 /// - the equivalent type is VectorType(16, int32_t)
4424 /// - the canonical type is VectorType(16, int)
4425 class AttributedType : public Type, public llvm::FoldingSetNode {
4427 using Kind = attr::Kind;
4430 friend class ASTContext; // ASTContext creates these
4432 QualType ModifiedType;
4433 QualType EquivalentType;
4435 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4436 QualType equivalent)
4437 : Type(Attributed, canon, equivalent->isDependentType(),
4438 equivalent->isInstantiationDependentType(),
4439 equivalent->isVariablyModifiedType(),
4440 equivalent->containsUnexpandedParameterPack()),
4441 ModifiedType(modified), EquivalentType(equivalent) {
4442 AttributedTypeBits.AttrKind = attrKind;
4446 Kind getAttrKind() const {
4447 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4450 QualType getModifiedType() const { return ModifiedType; }
4451 QualType getEquivalentType() const { return EquivalentType; }
4453 bool isSugared() const { return true; }
4454 QualType desugar() const { return getEquivalentType(); }
4456 /// Does this attribute behave like a type qualifier?
4458 /// A type qualifier adjusts a type to provide specialized rules for
4459 /// a specific object, like the standard const and volatile qualifiers.
4460 /// This includes attributes controlling things like nullability,
4461 /// address spaces, and ARC ownership. The value of the object is still
4462 /// largely described by the modified type.
4464 /// In contrast, many type attributes "rewrite" their modified type to
4465 /// produce a fundamentally different type, not necessarily related in any
4466 /// formalizable way to the original type. For example, calling convention
4467 /// and vector attributes are not simple type qualifiers.
4469 /// Type qualifiers are often, but not always, reflected in the canonical
4471 bool isQualifier() const;
4473 bool isMSTypeSpec() const;
4475 bool isCallingConv() const;
4477 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4479 /// Retrieve the attribute kind corresponding to the given
4480 /// nullability kind.
4481 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4483 case NullabilityKind::NonNull:
4484 return attr::TypeNonNull;
4486 case NullabilityKind::Nullable:
4487 return attr::TypeNullable;
4489 case NullabilityKind::Unspecified:
4490 return attr::TypeNullUnspecified;
4492 llvm_unreachable("Unknown nullability kind.");
4495 /// Strip off the top-level nullability annotation on the given
4496 /// type, if it's there.
4498 /// \param T The type to strip. If the type is exactly an
4499 /// AttributedType specifying nullability (without looking through
4500 /// type sugar), the nullability is returned and this type changed
4501 /// to the underlying modified type.
4503 /// \returns the top-level nullability, if present.
4504 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4506 void Profile(llvm::FoldingSetNodeID &ID) {
4507 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4510 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4511 QualType modified, QualType equivalent) {
4512 ID.AddInteger(attrKind);
4513 ID.AddPointer(modified.getAsOpaquePtr());
4514 ID.AddPointer(equivalent.getAsOpaquePtr());
4517 static bool classof(const Type *T) {
4518 return T->getTypeClass() == Attributed;
4522 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4523 friend class ASTContext; // ASTContext creates these
4525 // Helper data collector for canonical types.
4526 struct CanonicalTTPTInfo {
4527 unsigned Depth : 15;
4528 unsigned ParameterPack : 1;
4529 unsigned Index : 16;
4533 // Info for the canonical type.
4534 CanonicalTTPTInfo CanTTPTInfo;
4536 // Info for the non-canonical type.
4537 TemplateTypeParmDecl *TTPDecl;
4540 /// Build a non-canonical type.
4541 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4542 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4543 /*InstantiationDependent=*/true,
4544 /*VariablyModified=*/false,
4545 Canon->containsUnexpandedParameterPack()),
4548 /// Build the canonical type.
4549 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4550 : Type(TemplateTypeParm, QualType(this, 0),
4552 /*InstantiationDependent=*/true,
4553 /*VariablyModified=*/false, PP) {
4554 CanTTPTInfo.Depth = D;
4555 CanTTPTInfo.Index = I;
4556 CanTTPTInfo.ParameterPack = PP;
4559 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4560 QualType Can = getCanonicalTypeInternal();
4561 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4565 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4566 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4567 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4569 TemplateTypeParmDecl *getDecl() const {
4570 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4573 IdentifierInfo *getIdentifier() const;
4575 bool isSugared() const { return false; }
4576 QualType desugar() const { return QualType(this, 0); }
4578 void Profile(llvm::FoldingSetNodeID &ID) {
4579 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4582 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4583 unsigned Index, bool ParameterPack,
4584 TemplateTypeParmDecl *TTPDecl) {
4585 ID.AddInteger(Depth);
4586 ID.AddInteger(Index);
4587 ID.AddBoolean(ParameterPack);
4588 ID.AddPointer(TTPDecl);
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == TemplateTypeParm;
4596 /// Represents the result of substituting a type for a template
4599 /// Within an instantiated template, all template type parameters have
4600 /// been replaced with these. They are used solely to record that a
4601 /// type was originally written as a template type parameter;
4602 /// therefore they are never canonical.
4603 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4604 friend class ASTContext;
4606 // The original type parameter.
4607 const TemplateTypeParmType *Replaced;
4609 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4610 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4611 Canon->isInstantiationDependentType(),
4612 Canon->isVariablyModifiedType(),
4613 Canon->containsUnexpandedParameterPack()),
4617 /// Gets the template parameter that was substituted for.
4618 const TemplateTypeParmType *getReplacedParameter() const {
4622 /// Gets the type that was substituted for the template
4624 QualType getReplacementType() const {
4625 return getCanonicalTypeInternal();
4628 bool isSugared() const { return true; }
4629 QualType desugar() const { return getReplacementType(); }
4631 void Profile(llvm::FoldingSetNodeID &ID) {
4632 Profile(ID, getReplacedParameter(), getReplacementType());
4635 static void Profile(llvm::FoldingSetNodeID &ID,
4636 const TemplateTypeParmType *Replaced,
4637 QualType Replacement) {
4638 ID.AddPointer(Replaced);
4639 ID.AddPointer(Replacement.getAsOpaquePtr());
4642 static bool classof(const Type *T) {
4643 return T->getTypeClass() == SubstTemplateTypeParm;
4647 /// Represents the result of substituting a set of types for a template
4648 /// type parameter pack.
4650 /// When a pack expansion in the source code contains multiple parameter packs
4651 /// and those parameter packs correspond to different levels of template
4652 /// parameter lists, this type node is used to represent a template type
4653 /// parameter pack from an outer level, which has already had its argument pack
4654 /// substituted but that still lives within a pack expansion that itself
4655 /// could not be instantiated. When actually performing a substitution into
4656 /// that pack expansion (e.g., when all template parameters have corresponding
4657 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4658 /// at the current pack substitution index.
4659 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4660 friend class ASTContext;
4662 /// The original type parameter.
4663 const TemplateTypeParmType *Replaced;
4665 /// A pointer to the set of template arguments that this
4666 /// parameter pack is instantiated with.
4667 const TemplateArgument *Arguments;
4669 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4671 const TemplateArgument &ArgPack);
4674 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4676 /// Gets the template parameter that was substituted for.
4677 const TemplateTypeParmType *getReplacedParameter() const {
4681 unsigned getNumArgs() const {
4682 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4685 bool isSugared() const { return false; }
4686 QualType desugar() const { return QualType(this, 0); }
4688 TemplateArgument getArgumentPack() const;
4690 void Profile(llvm::FoldingSetNodeID &ID);
4691 static void Profile(llvm::FoldingSetNodeID &ID,
4692 const TemplateTypeParmType *Replaced,
4693 const TemplateArgument &ArgPack);
4695 static bool classof(const Type *T) {
4696 return T->getTypeClass() == SubstTemplateTypeParmPack;
4700 /// Common base class for placeholders for types that get replaced by
4701 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4702 /// class template types, and (eventually) constrained type names from the C++
4705 /// These types are usually a placeholder for a deduced type. However, before
4706 /// the initializer is attached, or (usually) if the initializer is
4707 /// type-dependent, there is no deduced type and the type is canonical. In
4708 /// the latter case, it is also a dependent type.
4709 class DeducedType : public Type {
4711 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4712 bool IsInstantiationDependent, bool ContainsParameterPack)
4714 // FIXME: Retain the sugared deduced type?
4715 DeducedAsType.isNull() ? QualType(this, 0)
4716 : DeducedAsType.getCanonicalType(),
4717 IsDependent, IsInstantiationDependent,
4718 /*VariablyModified=*/false, ContainsParameterPack) {
4719 if (!DeducedAsType.isNull()) {
4720 if (DeducedAsType->isDependentType())
4722 if (DeducedAsType->isInstantiationDependentType())
4723 setInstantiationDependent();
4724 if (DeducedAsType->containsUnexpandedParameterPack())
4725 setContainsUnexpandedParameterPack();
4730 bool isSugared() const { return !isCanonicalUnqualified(); }
4731 QualType desugar() const { return getCanonicalTypeInternal(); }
4733 /// Get the type deduced for this placeholder type, or null if it's
4734 /// either not been deduced or was deduced to a dependent type.
4735 QualType getDeducedType() const {
4736 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4738 bool isDeduced() const {
4739 return !isCanonicalUnqualified() || isDependentType();
4742 static bool classof(const Type *T) {
4743 return T->getTypeClass() == Auto ||
4744 T->getTypeClass() == DeducedTemplateSpecialization;
4748 /// Represents a C++11 auto or C++14 decltype(auto) type.
4749 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4750 friend class ASTContext; // ASTContext creates these
4752 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4753 bool IsDeducedAsDependent)
4754 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4755 IsDeducedAsDependent, /*ContainsPack=*/false) {
4756 AutoTypeBits.Keyword = (unsigned)Keyword;
4760 bool isDecltypeAuto() const {
4761 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4764 AutoTypeKeyword getKeyword() const {
4765 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4768 void Profile(llvm::FoldingSetNodeID &ID) {
4769 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4772 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4773 AutoTypeKeyword Keyword, bool IsDependent) {
4774 ID.AddPointer(Deduced.getAsOpaquePtr());
4775 ID.AddInteger((unsigned)Keyword);
4776 ID.AddBoolean(IsDependent);
4779 static bool classof(const Type *T) {
4780 return T->getTypeClass() == Auto;
4784 /// Represents a C++17 deduced template specialization type.
4785 class DeducedTemplateSpecializationType : public DeducedType,
4786 public llvm::FoldingSetNode {
4787 friend class ASTContext; // ASTContext creates these
4789 /// The name of the template whose arguments will be deduced.
4790 TemplateName Template;
4792 DeducedTemplateSpecializationType(TemplateName Template,
4793 QualType DeducedAsType,
4794 bool IsDeducedAsDependent)
4795 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4796 IsDeducedAsDependent || Template.isDependent(),
4797 IsDeducedAsDependent || Template.isInstantiationDependent(),
4798 Template.containsUnexpandedParameterPack()),
4799 Template(Template) {}
4802 /// Retrieve the name of the template that we are deducing.
4803 TemplateName getTemplateName() const { return Template;}
4805 void Profile(llvm::FoldingSetNodeID &ID) {
4806 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4809 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4810 QualType Deduced, bool IsDependent) {
4811 Template.Profile(ID);
4812 ID.AddPointer(Deduced.getAsOpaquePtr());
4813 ID.AddBoolean(IsDependent);
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == DeducedTemplateSpecialization;
4821 /// Represents a type template specialization; the template
4822 /// must be a class template, a type alias template, or a template
4823 /// template parameter. A template which cannot be resolved to one of
4824 /// these, e.g. because it is written with a dependent scope
4825 /// specifier, is instead represented as a
4826 /// @c DependentTemplateSpecializationType.
4828 /// A non-dependent template specialization type is always "sugar",
4829 /// typically for a \c RecordType. For example, a class template
4830 /// specialization type of \c vector<int> will refer to a tag type for
4831 /// the instantiation \c std::vector<int, std::allocator<int>>
4833 /// Template specializations are dependent if either the template or
4834 /// any of the template arguments are dependent, in which case the
4835 /// type may also be canonical.
4837 /// Instances of this type are allocated with a trailing array of
4838 /// TemplateArguments, followed by a QualType representing the
4839 /// non-canonical aliased type when the template is a type alias
4841 class alignas(8) TemplateSpecializationType
4843 public llvm::FoldingSetNode {
4844 friend class ASTContext; // ASTContext creates these
4846 /// The name of the template being specialized. This is
4847 /// either a TemplateName::Template (in which case it is a
4848 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4849 /// TypeAliasTemplateDecl*), a
4850 /// TemplateName::SubstTemplateTemplateParmPack, or a
4851 /// TemplateName::SubstTemplateTemplateParm (in which case the
4852 /// replacement must, recursively, be one of these).
4853 TemplateName Template;
4855 TemplateSpecializationType(TemplateName T,
4856 ArrayRef<TemplateArgument> Args,
4861 /// Determine whether any of the given template arguments are dependent.
4862 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4863 bool &InstantiationDependent);
4865 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4866 bool &InstantiationDependent);
4868 /// True if this template specialization type matches a current
4869 /// instantiation in the context in which it is found.
4870 bool isCurrentInstantiation() const {
4871 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4874 /// Determine if this template specialization type is for a type alias
4875 /// template that has been substituted.
4877 /// Nearly every template specialization type whose template is an alias
4878 /// template will be substituted. However, this is not the case when
4879 /// the specialization contains a pack expansion but the template alias
4880 /// does not have a corresponding parameter pack, e.g.,
4883 /// template<typename T, typename U, typename V> struct S;
4884 /// template<typename T, typename U> using A = S<T, int, U>;
4885 /// template<typename... Ts> struct X {
4886 /// typedef A<Ts...> type; // not a type alias
4889 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4891 /// Get the aliased type, if this is a specialization of a type alias
4893 QualType getAliasedType() const {
4894 assert(isTypeAlias() && "not a type alias template specialization");
4895 return *reinterpret_cast<const QualType*>(end());
4898 using iterator = const TemplateArgument *;
4900 iterator begin() const { return getArgs(); }
4901 iterator end() const; // defined inline in TemplateBase.h
4903 /// Retrieve the name of the template that we are specializing.
4904 TemplateName getTemplateName() const { return Template; }
4906 /// Retrieve the template arguments.
4907 const TemplateArgument *getArgs() const {
4908 return reinterpret_cast<const TemplateArgument *>(this + 1);
4911 /// Retrieve the number of template arguments.
4912 unsigned getNumArgs() const {
4913 return TemplateSpecializationTypeBits.NumArgs;
4916 /// Retrieve a specific template argument as a type.
4917 /// \pre \c isArgType(Arg)
4918 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4920 ArrayRef<TemplateArgument> template_arguments() const {
4921 return {getArgs(), getNumArgs()};
4924 bool isSugared() const {
4925 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4928 QualType desugar() const {
4929 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
4932 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4933 Profile(ID, Template, template_arguments(), Ctx);
4935 getAliasedType().Profile(ID);
4938 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4939 ArrayRef<TemplateArgument> Args,
4940 const ASTContext &Context);
4942 static bool classof(const Type *T) {
4943 return T->getTypeClass() == TemplateSpecialization;
4947 /// Print a template argument list, including the '<' and '>'
4948 /// enclosing the template arguments.
4949 void printTemplateArgumentList(raw_ostream &OS,
4950 ArrayRef<TemplateArgument> Args,
4951 const PrintingPolicy &Policy);
4953 void printTemplateArgumentList(raw_ostream &OS,
4954 ArrayRef<TemplateArgumentLoc> Args,
4955 const PrintingPolicy &Policy);
4957 void printTemplateArgumentList(raw_ostream &OS,
4958 const TemplateArgumentListInfo &Args,
4959 const PrintingPolicy &Policy);
4961 /// The injected class name of a C++ class template or class
4962 /// template partial specialization. Used to record that a type was
4963 /// spelled with a bare identifier rather than as a template-id; the
4964 /// equivalent for non-templated classes is just RecordType.
4966 /// Injected class name types are always dependent. Template
4967 /// instantiation turns these into RecordTypes.
4969 /// Injected class name types are always canonical. This works
4970 /// because it is impossible to compare an injected class name type
4971 /// with the corresponding non-injected template type, for the same
4972 /// reason that it is impossible to directly compare template
4973 /// parameters from different dependent contexts: injected class name
4974 /// types can only occur within the scope of a particular templated
4975 /// declaration, and within that scope every template specialization
4976 /// will canonicalize to the injected class name (when appropriate
4977 /// according to the rules of the language).
4978 class InjectedClassNameType : public Type {
4979 friend class ASTContext; // ASTContext creates these.
4980 friend class ASTNodeImporter;
4981 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4982 // currently suitable for AST reading, too much
4983 // interdependencies.
4985 CXXRecordDecl *Decl;
4987 /// The template specialization which this type represents.
4989 /// template <class T> class A { ... };
4990 /// this is A<T>, whereas in
4991 /// template <class X, class Y> class A<B<X,Y> > { ... };
4992 /// this is A<B<X,Y> >.
4994 /// It is always unqualified, always a template specialization type,
4995 /// and always dependent.
4996 QualType InjectedType;
4998 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4999 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5000 /*InstantiationDependent=*/true,
5001 /*VariablyModified=*/false,
5002 /*ContainsUnexpandedParameterPack=*/false),
5003 Decl(D), InjectedType(TST) {
5004 assert(isa<TemplateSpecializationType>(TST));
5005 assert(!TST.hasQualifiers());
5006 assert(TST->isDependentType());
5010 QualType getInjectedSpecializationType() const { return InjectedType; }
5012 const TemplateSpecializationType *getInjectedTST() const {
5013 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5016 TemplateName getTemplateName() const {
5017 return getInjectedTST()->getTemplateName();
5020 CXXRecordDecl *getDecl() const;
5022 bool isSugared() const { return false; }
5023 QualType desugar() const { return QualType(this, 0); }
5025 static bool classof(const Type *T) {
5026 return T->getTypeClass() == InjectedClassName;
5030 /// The kind of a tag type.
5032 /// The "struct" keyword.
5035 /// The "__interface" keyword.
5038 /// The "union" keyword.
5041 /// The "class" keyword.
5044 /// The "enum" keyword.
5048 /// The elaboration keyword that precedes a qualified type name or
5049 /// introduces an elaborated-type-specifier.
5050 enum ElaboratedTypeKeyword {
5051 /// The "struct" keyword introduces the elaborated-type-specifier.
5054 /// The "__interface" keyword introduces the elaborated-type-specifier.
5057 /// The "union" keyword introduces the elaborated-type-specifier.
5060 /// The "class" keyword introduces the elaborated-type-specifier.
5063 /// The "enum" keyword introduces the elaborated-type-specifier.
5066 /// The "typename" keyword precedes the qualified type name, e.g.,
5067 /// \c typename T::type.
5070 /// No keyword precedes the qualified type name.
5074 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
5075 /// The keyword in stored in the free bits of the base class.
5076 /// Also provides a few static helpers for converting and printing
5077 /// elaborated type keyword and tag type kind enumerations.
5078 class TypeWithKeyword : public Type {
5080 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5081 QualType Canonical, bool Dependent,
5082 bool InstantiationDependent, bool VariablyModified,
5083 bool ContainsUnexpandedParameterPack)
5084 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5085 ContainsUnexpandedParameterPack) {
5086 TypeWithKeywordBits.Keyword = Keyword;
5090 ElaboratedTypeKeyword getKeyword() const {
5091 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5094 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5095 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5097 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5098 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5099 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5101 /// Converts a TagTypeKind into an elaborated type keyword.
5102 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5104 /// Converts an elaborated type keyword into a TagTypeKind.
5105 /// It is an error to provide an elaborated type keyword
5106 /// which *isn't* a tag kind here.
5107 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5109 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5111 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5113 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5114 return getKeywordName(getKeywordForTagTypeKind(Kind));
5117 class CannotCastToThisType {};
5118 static CannotCastToThisType classof(const Type *);
5121 /// Represents a type that was referred to using an elaborated type
5122 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5125 /// This type is used to keep track of a type name as written in the
5126 /// source code, including tag keywords and any nested-name-specifiers.
5127 /// The type itself is always "sugar", used to express what was written
5128 /// in the source code but containing no additional semantic information.
5129 class ElaboratedType final
5130 : public TypeWithKeyword,
5131 public llvm::FoldingSetNode,
5132 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5133 friend class ASTContext; // ASTContext creates these
5134 friend TrailingObjects;
5136 /// The nested name specifier containing the qualifier.
5137 NestedNameSpecifier *NNS;
5139 /// The type that this qualified name refers to.
5142 /// The (re)declaration of this tag type owned by this occurrence is stored
5143 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5144 /// it, or obtain a null pointer if there is none.
5146 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5147 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5148 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5149 NamedType->isDependentType(),
5150 NamedType->isInstantiationDependentType(),
5151 NamedType->isVariablyModifiedType(),
5152 NamedType->containsUnexpandedParameterPack()),
5153 NNS(NNS), NamedType(NamedType) {
5154 ElaboratedTypeBits.HasOwnedTagDecl = false;
5156 ElaboratedTypeBits.HasOwnedTagDecl = true;
5157 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5159 assert(!(Keyword == ETK_None && NNS == nullptr) &&
5160 "ElaboratedType cannot have elaborated type keyword "
5161 "and name qualifier both null.");
5165 /// Retrieve the qualification on this type.
5166 NestedNameSpecifier *getQualifier() const { return NNS; }
5168 /// Retrieve the type named by the qualified-id.
5169 QualType getNamedType() const { return NamedType; }
5171 /// Remove a single level of sugar.
5172 QualType desugar() const { return getNamedType(); }
5174 /// Returns whether this type directly provides sugar.
5175 bool isSugared() const { return true; }
5177 /// Return the (re)declaration of this type owned by this occurrence of this
5178 /// type, or nullptr if there is none.
5179 TagDecl *getOwnedTagDecl() const {
5180 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5184 void Profile(llvm::FoldingSetNodeID &ID) {
5185 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5188 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5189 NestedNameSpecifier *NNS, QualType NamedType,
5190 TagDecl *OwnedTagDecl) {
5191 ID.AddInteger(Keyword);
5193 NamedType.Profile(ID);
5194 ID.AddPointer(OwnedTagDecl);
5197 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5200 /// Represents a qualified type name for which the type name is
5203 /// DependentNameType represents a class of dependent types that involve a
5204 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5205 /// name of a type. The DependentNameType may start with a "typename" (for a
5206 /// typename-specifier), "class", "struct", "union", or "enum" (for a
5207 /// dependent elaborated-type-specifier), or nothing (in contexts where we
5208 /// know that we must be referring to a type, e.g., in a base class specifier).
5209 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5210 /// mode, this type is used with non-dependent names to delay name lookup until
5212 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5213 friend class ASTContext; // ASTContext creates these
5215 /// The nested name specifier containing the qualifier.
5216 NestedNameSpecifier *NNS;
5218 /// The type that this typename specifier refers to.
5219 const IdentifierInfo *Name;
5221 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5222 const IdentifierInfo *Name, QualType CanonType)
5223 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5224 /*InstantiationDependent=*/true,
5225 /*VariablyModified=*/false,
5226 NNS->containsUnexpandedParameterPack()),
5227 NNS(NNS), Name(Name) {}
5230 /// Retrieve the qualification on this type.
5231 NestedNameSpecifier *getQualifier() const { return NNS; }
5233 /// Retrieve the type named by the typename specifier as an identifier.
5235 /// This routine will return a non-NULL identifier pointer when the
5236 /// form of the original typename was terminated by an identifier,
5237 /// e.g., "typename T::type".
5238 const IdentifierInfo *getIdentifier() const {
5242 bool isSugared() const { return false; }
5243 QualType desugar() const { return QualType(this, 0); }
5245 void Profile(llvm::FoldingSetNodeID &ID) {
5246 Profile(ID, getKeyword(), NNS, Name);
5249 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5250 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5251 ID.AddInteger(Keyword);
5253 ID.AddPointer(Name);
5256 static bool classof(const Type *T) {
5257 return T->getTypeClass() == DependentName;
5261 /// Represents a template specialization type whose template cannot be
5263 /// A<T>::template B<T>
5264 class alignas(8) DependentTemplateSpecializationType
5265 : public TypeWithKeyword,
5266 public llvm::FoldingSetNode {
5267 friend class ASTContext; // ASTContext creates these
5269 /// The nested name specifier containing the qualifier.
5270 NestedNameSpecifier *NNS;
5272 /// The identifier of the template.
5273 const IdentifierInfo *Name;
5275 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5276 NestedNameSpecifier *NNS,
5277 const IdentifierInfo *Name,
5278 ArrayRef<TemplateArgument> Args,
5281 const TemplateArgument *getArgBuffer() const {
5282 return reinterpret_cast<const TemplateArgument*>(this+1);
5285 TemplateArgument *getArgBuffer() {
5286 return reinterpret_cast<TemplateArgument*>(this+1);
5290 NestedNameSpecifier *getQualifier() const { return NNS; }
5291 const IdentifierInfo *getIdentifier() const { return Name; }
5293 /// Retrieve the template arguments.
5294 const TemplateArgument *getArgs() const {
5295 return getArgBuffer();
5298 /// Retrieve the number of template arguments.
5299 unsigned getNumArgs() const {
5300 return DependentTemplateSpecializationTypeBits.NumArgs;
5303 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5305 ArrayRef<TemplateArgument> template_arguments() const {
5306 return {getArgs(), getNumArgs()};
5309 using iterator = const TemplateArgument *;
5311 iterator begin() const { return getArgs(); }
5312 iterator end() const; // inline in TemplateBase.h
5314 bool isSugared() const { return false; }
5315 QualType desugar() const { return QualType(this, 0); }
5317 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5318 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5321 static void Profile(llvm::FoldingSetNodeID &ID,
5322 const ASTContext &Context,
5323 ElaboratedTypeKeyword Keyword,
5324 NestedNameSpecifier *Qualifier,
5325 const IdentifierInfo *Name,
5326 ArrayRef<TemplateArgument> Args);
5328 static bool classof(const Type *T) {
5329 return T->getTypeClass() == DependentTemplateSpecialization;
5333 /// Represents a pack expansion of types.
5335 /// Pack expansions are part of C++11 variadic templates. A pack
5336 /// expansion contains a pattern, which itself contains one or more
5337 /// "unexpanded" parameter packs. When instantiated, a pack expansion
5338 /// produces a series of types, each instantiated from the pattern of
5339 /// the expansion, where the Ith instantiation of the pattern uses the
5340 /// Ith arguments bound to each of the unexpanded parameter packs. The
5341 /// pack expansion is considered to "expand" these unexpanded
5342 /// parameter packs.
5345 /// template<typename ...Types> struct tuple;
5347 /// template<typename ...Types>
5348 /// struct tuple_of_references {
5349 /// typedef tuple<Types&...> type;
5353 /// Here, the pack expansion \c Types&... is represented via a
5354 /// PackExpansionType whose pattern is Types&.
5355 class PackExpansionType : public Type, public llvm::FoldingSetNode {
5356 friend class ASTContext; // ASTContext creates these
5358 /// The pattern of the pack expansion.
5361 PackExpansionType(QualType Pattern, QualType Canon,
5362 Optional<unsigned> NumExpansions)
5363 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5364 /*InstantiationDependent=*/true,
5365 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5366 /*ContainsUnexpandedParameterPack=*/false),
5368 PackExpansionTypeBits.NumExpansions =
5369 NumExpansions ? *NumExpansions + 1 : 0;
5373 /// Retrieve the pattern of this pack expansion, which is the
5374 /// type that will be repeatedly instantiated when instantiating the
5375 /// pack expansion itself.
5376 QualType getPattern() const { return Pattern; }
5378 /// Retrieve the number of expansions that this pack expansion will
5379 /// generate, if known.
5380 Optional<unsigned> getNumExpansions() const {
5381 if (PackExpansionTypeBits.NumExpansions)
5382 return PackExpansionTypeBits.NumExpansions - 1;
5386 bool isSugared() const { return !Pattern->isDependentType(); }
5387 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5389 void Profile(llvm::FoldingSetNodeID &ID) {
5390 Profile(ID, getPattern(), getNumExpansions());
5393 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5394 Optional<unsigned> NumExpansions) {
5395 ID.AddPointer(Pattern.getAsOpaquePtr());
5396 ID.AddBoolean(NumExpansions.hasValue());
5398 ID.AddInteger(*NumExpansions);
5401 static bool classof(const Type *T) {
5402 return T->getTypeClass() == PackExpansion;
5406 /// This class wraps the list of protocol qualifiers. For types that can
5407 /// take ObjC protocol qualifers, they can subclass this class.
5409 class ObjCProtocolQualifiers {
5411 ObjCProtocolQualifiers() = default;
5413 ObjCProtocolDecl * const *getProtocolStorage() const {
5414 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5417 ObjCProtocolDecl **getProtocolStorage() {
5418 return static_cast<T*>(this)->getProtocolStorageImpl();
5421 void setNumProtocols(unsigned N) {
5422 static_cast<T*>(this)->setNumProtocolsImpl(N);
5425 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5426 setNumProtocols(protocols.size());
5427 assert(getNumProtocols() == protocols.size() &&
5428 "bitfield overflow in protocol count");
5429 if (!protocols.empty())
5430 memcpy(getProtocolStorage(), protocols.data(),
5431 protocols.size() * sizeof(ObjCProtocolDecl*));
5435 using qual_iterator = ObjCProtocolDecl * const *;
5436 using qual_range = llvm::iterator_range<qual_iterator>;
5438 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5439 qual_iterator qual_begin() const { return getProtocolStorage(); }
5440 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5442 bool qual_empty() const { return getNumProtocols() == 0; }
5444 /// Return the number of qualifying protocols in this type, or 0 if
5446 unsigned getNumProtocols() const {
5447 return static_cast<const T*>(this)->getNumProtocolsImpl();
5450 /// Fetch a protocol by index.
5451 ObjCProtocolDecl *getProtocol(unsigned I) const {
5452 assert(I < getNumProtocols() && "Out-of-range protocol access");
5453 return qual_begin()[I];
5456 /// Retrieve all of the protocol qualifiers.
5457 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5458 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5462 /// Represents a type parameter type in Objective C. It can take
5463 /// a list of protocols.
5464 class ObjCTypeParamType : public Type,
5465 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5466 public llvm::FoldingSetNode {
5467 friend class ASTContext;
5468 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5470 /// The number of protocols stored on this type.
5471 unsigned NumProtocols : 6;
5473 ObjCTypeParamDecl *OTPDecl;
5475 /// The protocols are stored after the ObjCTypeParamType node. In the
5476 /// canonical type, the list of protocols are sorted alphabetically
5478 ObjCProtocolDecl **getProtocolStorageImpl();
5480 /// Return the number of qualifying protocols in this interface type,
5481 /// or 0 if there are none.
5482 unsigned getNumProtocolsImpl() const {
5483 return NumProtocols;
5486 void setNumProtocolsImpl(unsigned N) {
5490 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5492 ArrayRef<ObjCProtocolDecl *> protocols);
5495 bool isSugared() const { return true; }
5496 QualType desugar() const { return getCanonicalTypeInternal(); }
5498 static bool classof(const Type *T) {
5499 return T->getTypeClass() == ObjCTypeParam;
5502 void Profile(llvm::FoldingSetNodeID &ID);
5503 static void Profile(llvm::FoldingSetNodeID &ID,
5504 const ObjCTypeParamDecl *OTPDecl,
5505 ArrayRef<ObjCProtocolDecl *> protocols);
5507 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5510 /// Represents a class type in Objective C.
5512 /// Every Objective C type is a combination of a base type, a set of
5513 /// type arguments (optional, for parameterized classes) and a list of
5516 /// Given the following declarations:
5522 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5523 /// with base C and no protocols.
5525 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5526 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5528 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5529 /// and protocol list [P].
5531 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5532 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5533 /// and no protocols.
5535 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5536 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5537 /// this should get its own sugar class to better represent the source.
5538 class ObjCObjectType : public Type,
5539 public ObjCProtocolQualifiers<ObjCObjectType> {
5540 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5542 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5543 // after the ObjCObjectPointerType node.
5544 // ObjCObjectType.NumProtocols - the number of protocols stored
5545 // after the type arguments of ObjCObjectPointerType node.
5547 // These protocols are those written directly on the type. If
5548 // protocol qualifiers ever become additive, the iterators will need
5549 // to get kindof complicated.
5551 // In the canonical object type, these are sorted alphabetically
5554 /// Either a BuiltinType or an InterfaceType or sugar for either.
5557 /// Cached superclass type.
5558 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5559 CachedSuperClassType;
5561 QualType *getTypeArgStorage();
5562 const QualType *getTypeArgStorage() const {
5563 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5566 ObjCProtocolDecl **getProtocolStorageImpl();
5567 /// Return the number of qualifying protocols in this interface type,
5568 /// or 0 if there are none.
5569 unsigned getNumProtocolsImpl() const {
5570 return ObjCObjectTypeBits.NumProtocols;
5572 void setNumProtocolsImpl(unsigned N) {
5573 ObjCObjectTypeBits.NumProtocols = N;
5577 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5579 ObjCObjectType(QualType Canonical, QualType Base,
5580 ArrayRef<QualType> typeArgs,
5581 ArrayRef<ObjCProtocolDecl *> protocols,
5584 ObjCObjectType(enum Nonce_ObjCInterface)
5585 : Type(ObjCInterface, QualType(), false, false, false, false),
5586 BaseType(QualType(this_(), 0)) {
5587 ObjCObjectTypeBits.NumProtocols = 0;
5588 ObjCObjectTypeBits.NumTypeArgs = 0;
5589 ObjCObjectTypeBits.IsKindOf = 0;
5592 void computeSuperClassTypeSlow() const;
5595 /// Gets the base type of this object type. This is always (possibly
5596 /// sugar for) one of:
5597 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5598 /// user, which is a typedef for an ObjCObjectPointerType)
5599 /// - the 'Class' builtin type (same caveat)
5600 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5601 QualType getBaseType() const { return BaseType; }
5603 bool isObjCId() const {
5604 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5607 bool isObjCClass() const {
5608 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5611 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5612 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5613 bool isObjCUnqualifiedIdOrClass() const {
5614 if (!qual_empty()) return false;
5615 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5616 return T->getKind() == BuiltinType::ObjCId ||
5617 T->getKind() == BuiltinType::ObjCClass;
5620 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5621 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5623 /// Gets the interface declaration for this object type, if the base type
5624 /// really is an interface.
5625 ObjCInterfaceDecl *getInterface() const;
5627 /// Determine whether this object type is "specialized", meaning
5628 /// that it has type arguments.
5629 bool isSpecialized() const;
5631 /// Determine whether this object type was written with type arguments.
5632 bool isSpecializedAsWritten() const {
5633 return ObjCObjectTypeBits.NumTypeArgs > 0;
5636 /// Determine whether this object type is "unspecialized", meaning
5637 /// that it has no type arguments.
5638 bool isUnspecialized() const { return !isSpecialized(); }
5640 /// Determine whether this object type is "unspecialized" as
5641 /// written, meaning that it has no type arguments.
5642 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5644 /// Retrieve the type arguments of this object type (semantically).
5645 ArrayRef<QualType> getTypeArgs() const;
5647 /// Retrieve the type arguments of this object type as they were
5649 ArrayRef<QualType> getTypeArgsAsWritten() const {
5650 return llvm::makeArrayRef(getTypeArgStorage(),
5651 ObjCObjectTypeBits.NumTypeArgs);
5654 /// Whether this is a "__kindof" type as written.
5655 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5657 /// Whether this ia a "__kindof" type (semantically).
5658 bool isKindOfType() const;
5660 /// Retrieve the type of the superclass of this object type.
5662 /// This operation substitutes any type arguments into the
5663 /// superclass of the current class type, potentially producing a
5664 /// specialization of the superclass type. Produces a null type if
5665 /// there is no superclass.
5666 QualType getSuperClassType() const {
5667 if (!CachedSuperClassType.getInt())
5668 computeSuperClassTypeSlow();
5670 assert(CachedSuperClassType.getInt() && "Superclass not set?");
5671 return QualType(CachedSuperClassType.getPointer(), 0);
5674 /// Strip off the Objective-C "kindof" type and (with it) any
5675 /// protocol qualifiers.
5676 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5678 bool isSugared() const { return false; }
5679 QualType desugar() const { return QualType(this, 0); }
5681 static bool classof(const Type *T) {
5682 return T->getTypeClass() == ObjCObject ||
5683 T->getTypeClass() == ObjCInterface;
5687 /// A class providing a concrete implementation
5688 /// of ObjCObjectType, so as to not increase the footprint of
5689 /// ObjCInterfaceType. Code outside of ASTContext and the core type
5690 /// system should not reference this type.
5691 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5692 friend class ASTContext;
5694 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5695 // will need to be modified.
5697 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5698 ArrayRef<QualType> typeArgs,
5699 ArrayRef<ObjCProtocolDecl *> protocols,
5701 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5704 void Profile(llvm::FoldingSetNodeID &ID);
5705 static void Profile(llvm::FoldingSetNodeID &ID,
5707 ArrayRef<QualType> typeArgs,
5708 ArrayRef<ObjCProtocolDecl *> protocols,
5712 inline QualType *ObjCObjectType::getTypeArgStorage() {
5713 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5716 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5717 return reinterpret_cast<ObjCProtocolDecl**>(
5718 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5721 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5722 return reinterpret_cast<ObjCProtocolDecl**>(
5723 static_cast<ObjCTypeParamType*>(this)+1);
5726 /// Interfaces are the core concept in Objective-C for object oriented design.
5727 /// They basically correspond to C++ classes. There are two kinds of interface
5728 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5729 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5731 /// ObjCInterfaceType guarantees the following properties when considered
5732 /// as a subtype of its superclass, ObjCObjectType:
5733 /// - There are no protocol qualifiers. To reinforce this, code which
5734 /// tries to invoke the protocol methods via an ObjCInterfaceType will
5735 /// fail to compile.
5736 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5737 /// T->getBaseType() == QualType(T, 0).
5738 class ObjCInterfaceType : public ObjCObjectType {
5739 friend class ASTContext; // ASTContext creates these.
5740 friend class ASTReader;
5741 friend class ObjCInterfaceDecl;
5743 mutable ObjCInterfaceDecl *Decl;
5745 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5746 : ObjCObjectType(Nonce_ObjCInterface),
5747 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5750 /// Get the declaration of this interface.
5751 ObjCInterfaceDecl *getDecl() const { return Decl; }
5753 bool isSugared() const { return false; }
5754 QualType desugar() const { return QualType(this, 0); }
5756 static bool classof(const Type *T) {
5757 return T->getTypeClass() == ObjCInterface;
5760 // Nonsense to "hide" certain members of ObjCObjectType within this
5761 // class. People asking for protocols on an ObjCInterfaceType are
5762 // not going to get what they want: ObjCInterfaceTypes are
5763 // guaranteed to have no protocols.
5773 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5774 QualType baseType = getBaseType();
5775 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5776 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5777 return T->getDecl();
5779 baseType = ObjT->getBaseType();
5785 /// Represents a pointer to an Objective C object.
5787 /// These are constructed from pointer declarators when the pointee type is
5788 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5789 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5790 /// and 'Class<P>' are translated into these.
5792 /// Pointers to pointers to Objective C objects are still PointerTypes;
5793 /// only the first level of pointer gets it own type implementation.
5794 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5795 friend class ASTContext; // ASTContext creates these.
5797 QualType PointeeType;
5799 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5800 : Type(ObjCObjectPointer, Canonical,
5801 Pointee->isDependentType(),
5802 Pointee->isInstantiationDependentType(),
5803 Pointee->isVariablyModifiedType(),
5804 Pointee->containsUnexpandedParameterPack()),
5805 PointeeType(Pointee) {}
5808 /// Gets the type pointed to by this ObjC pointer.
5809 /// The result will always be an ObjCObjectType or sugar thereof.
5810 QualType getPointeeType() const { return PointeeType; }
5812 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5814 /// This method is equivalent to getPointeeType() except that
5815 /// it discards any typedefs (or other sugar) between this
5816 /// type and the "outermost" object type. So for:
5818 /// \@class A; \@protocol P; \@protocol Q;
5819 /// typedef A<P> AP;
5821 /// typedef A1<P> A1P;
5822 /// typedef A1P<Q> A1PQ;
5824 /// For 'A*', getObjectType() will return 'A'.
5825 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5826 /// For 'AP*', getObjectType() will return 'A<P>'.
5827 /// For 'A1*', getObjectType() will return 'A'.
5828 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5829 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5830 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5831 /// adding protocols to a protocol-qualified base discards the
5832 /// old qualifiers (for now). But if it didn't, getObjectType()
5833 /// would return 'A1P<Q>' (and we'd have to make iterating over
5834 /// qualifiers more complicated).
5835 const ObjCObjectType *getObjectType() const {
5836 return PointeeType->castAs<ObjCObjectType>();
5839 /// If this pointer points to an Objective C
5840 /// \@interface type, gets the type for that interface. Any protocol
5841 /// qualifiers on the interface are ignored.
5843 /// \return null if the base type for this pointer is 'id' or 'Class'
5844 const ObjCInterfaceType *getInterfaceType() const;
5846 /// If this pointer points to an Objective \@interface
5847 /// type, gets the declaration for that interface.
5849 /// \return null if the base type for this pointer is 'id' or 'Class'
5850 ObjCInterfaceDecl *getInterfaceDecl() const {
5851 return getObjectType()->getInterface();
5854 /// True if this is equivalent to the 'id' type, i.e. if
5855 /// its object type is the primitive 'id' type with no protocols.
5856 bool isObjCIdType() const {
5857 return getObjectType()->isObjCUnqualifiedId();
5860 /// True if this is equivalent to the 'Class' type,
5861 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5862 bool isObjCClassType() const {
5863 return getObjectType()->isObjCUnqualifiedClass();
5866 /// True if this is equivalent to the 'id' or 'Class' type,
5867 bool isObjCIdOrClassType() const {
5868 return getObjectType()->isObjCUnqualifiedIdOrClass();
5871 /// True if this is equivalent to 'id<P>' for some non-empty set of
5873 bool isObjCQualifiedIdType() const {
5874 return getObjectType()->isObjCQualifiedId();
5877 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5879 bool isObjCQualifiedClassType() const {
5880 return getObjectType()->isObjCQualifiedClass();
5883 /// Whether this is a "__kindof" type.
5884 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5886 /// Whether this type is specialized, meaning that it has type arguments.
5887 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5889 /// Whether this type is specialized, meaning that it has type arguments.
5890 bool isSpecializedAsWritten() const {
5891 return getObjectType()->isSpecializedAsWritten();
5894 /// Whether this type is unspecialized, meaning that is has no type arguments.
5895 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5897 /// Determine whether this object type is "unspecialized" as
5898 /// written, meaning that it has no type arguments.
5899 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5901 /// Retrieve the type arguments for this type.
5902 ArrayRef<QualType> getTypeArgs() const {
5903 return getObjectType()->getTypeArgs();
5906 /// Retrieve the type arguments for this type.
5907 ArrayRef<QualType> getTypeArgsAsWritten() const {
5908 return getObjectType()->getTypeArgsAsWritten();
5911 /// An iterator over the qualifiers on the object type. Provided
5912 /// for convenience. This will always iterate over the full set of
5913 /// protocols on a type, not just those provided directly.
5914 using qual_iterator = ObjCObjectType::qual_iterator;
5915 using qual_range = llvm::iterator_range<qual_iterator>;
5917 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5919 qual_iterator qual_begin() const {
5920 return getObjectType()->qual_begin();
5923 qual_iterator qual_end() const {
5924 return getObjectType()->qual_end();
5927 bool qual_empty() const { return getObjectType()->qual_empty(); }
5929 /// Return the number of qualifying protocols on the object type.
5930 unsigned getNumProtocols() const {
5931 return getObjectType()->getNumProtocols();
5934 /// Retrieve a qualifying protocol by index on the object type.
5935 ObjCProtocolDecl *getProtocol(unsigned I) const {
5936 return getObjectType()->getProtocol(I);
5939 bool isSugared() const { return false; }
5940 QualType desugar() const { return QualType(this, 0); }
5942 /// Retrieve the type of the superclass of this object pointer type.
5944 /// This operation substitutes any type arguments into the
5945 /// superclass of the current class type, potentially producing a
5946 /// pointer to a specialization of the superclass type. Produces a
5947 /// null type if there is no superclass.
5948 QualType getSuperClassType() const;
5950 /// Strip off the Objective-C "kindof" type and (with it) any
5951 /// protocol qualifiers.
5952 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5953 const ASTContext &ctx) const;
5955 void Profile(llvm::FoldingSetNodeID &ID) {
5956 Profile(ID, getPointeeType());
5959 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5960 ID.AddPointer(T.getAsOpaquePtr());
5963 static bool classof(const Type *T) {
5964 return T->getTypeClass() == ObjCObjectPointer;
5968 class AtomicType : public Type, public llvm::FoldingSetNode {
5969 friend class ASTContext; // ASTContext creates these.
5973 AtomicType(QualType ValTy, QualType Canonical)
5974 : Type(Atomic, Canonical, ValTy->isDependentType(),
5975 ValTy->isInstantiationDependentType(),
5976 ValTy->isVariablyModifiedType(),
5977 ValTy->containsUnexpandedParameterPack()),
5981 /// Gets the type contained by this atomic type, i.e.
5982 /// the type returned by performing an atomic load of this atomic type.
5983 QualType getValueType() const { return ValueType; }
5985 bool isSugared() const { return false; }
5986 QualType desugar() const { return QualType(this, 0); }
5988 void Profile(llvm::FoldingSetNodeID &ID) {
5989 Profile(ID, getValueType());
5992 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5993 ID.AddPointer(T.getAsOpaquePtr());
5996 static bool classof(const Type *T) {
5997 return T->getTypeClass() == Atomic;
6001 /// PipeType - OpenCL20.
6002 class PipeType : public Type, public llvm::FoldingSetNode {
6003 friend class ASTContext; // ASTContext creates these.
6005 QualType ElementType;
6008 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6009 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6010 elemType->isInstantiationDependentType(),
6011 elemType->isVariablyModifiedType(),
6012 elemType->containsUnexpandedParameterPack()),
6013 ElementType(elemType), isRead(isRead) {}
6016 QualType getElementType() const { return ElementType; }
6018 bool isSugared() const { return false; }
6020 QualType desugar() const { return QualType(this, 0); }
6022 void Profile(llvm::FoldingSetNodeID &ID) {
6023 Profile(ID, getElementType(), isReadOnly());
6026 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6027 ID.AddPointer(T.getAsOpaquePtr());
6028 ID.AddBoolean(isRead);
6031 static bool classof(const Type *T) {
6032 return T->getTypeClass() == Pipe;
6035 bool isReadOnly() const { return isRead; }
6038 /// A qualifier set is used to build a set of qualifiers.
6039 class QualifierCollector : public Qualifiers {
6041 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6043 /// Collect any qualifiers on the given type and return an
6044 /// unqualified type. The qualifiers are assumed to be consistent
6045 /// with those already in the type.
6046 const Type *strip(QualType type) {
6047 addFastQualifiers(type.getLocalFastQualifiers());
6048 if (!type.hasLocalNonFastQualifiers())
6049 return type.getTypePtrUnsafe();
6051 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6052 addConsistentQualifiers(extQuals->getQualifiers());
6053 return extQuals->getBaseType();
6056 /// Apply the collected qualifiers to the given type.
6057 QualType apply(const ASTContext &Context, QualType QT) const;
6059 /// Apply the collected qualifiers to the given type.
6060 QualType apply(const ASTContext &Context, const Type* T) const;
6063 // Inline function definitions.
6065 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6066 SplitQualType desugar =
6067 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6068 desugar.Quals.addConsistentQualifiers(Quals);
6072 inline const Type *QualType::getTypePtr() const {
6073 return getCommonPtr()->BaseType;
6076 inline const Type *QualType::getTypePtrOrNull() const {
6077 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6080 inline SplitQualType QualType::split() const {
6081 if (!hasLocalNonFastQualifiers())
6082 return SplitQualType(getTypePtrUnsafe(),
6083 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6085 const ExtQuals *eq = getExtQualsUnsafe();
6086 Qualifiers qs = eq->getQualifiers();
6087 qs.addFastQualifiers(getLocalFastQualifiers());
6088 return SplitQualType(eq->getBaseType(), qs);
6091 inline Qualifiers QualType::getLocalQualifiers() const {
6093 if (hasLocalNonFastQualifiers())
6094 Quals = getExtQualsUnsafe()->getQualifiers();
6095 Quals.addFastQualifiers(getLocalFastQualifiers());
6099 inline Qualifiers QualType::getQualifiers() const {
6100 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6101 quals.addFastQualifiers(getLocalFastQualifiers());
6105 inline unsigned QualType::getCVRQualifiers() const {
6106 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6107 cvr |= getLocalCVRQualifiers();
6111 inline QualType QualType::getCanonicalType() const {
6112 QualType canon = getCommonPtr()->CanonicalType;
6113 return canon.withFastQualifiers(getLocalFastQualifiers());
6116 inline bool QualType::isCanonical() const {
6117 return getTypePtr()->isCanonicalUnqualified();
6120 inline bool QualType::isCanonicalAsParam() const {
6121 if (!isCanonical()) return false;
6122 if (hasLocalQualifiers()) return false;
6124 const Type *T = getTypePtr();
6125 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6128 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6131 inline bool QualType::isConstQualified() const {
6132 return isLocalConstQualified() ||
6133 getCommonPtr()->CanonicalType.isLocalConstQualified();
6136 inline bool QualType::isRestrictQualified() const {
6137 return isLocalRestrictQualified() ||
6138 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6142 inline bool QualType::isVolatileQualified() const {
6143 return isLocalVolatileQualified() ||
6144 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6147 inline bool QualType::hasQualifiers() const {
6148 return hasLocalQualifiers() ||
6149 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6152 inline QualType QualType::getUnqualifiedType() const {
6153 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6154 return QualType(getTypePtr(), 0);
6156 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6159 inline SplitQualType QualType::getSplitUnqualifiedType() const {
6160 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6163 return getSplitUnqualifiedTypeImpl(*this);
6166 inline void QualType::removeLocalConst() {
6167 removeLocalFastQualifiers(Qualifiers::Const);
6170 inline void QualType::removeLocalRestrict() {
6171 removeLocalFastQualifiers(Qualifiers::Restrict);
6174 inline void QualType::removeLocalVolatile() {
6175 removeLocalFastQualifiers(Qualifiers::Volatile);
6178 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6179 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
6180 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6181 "Fast bits differ from CVR bits!");
6183 // Fast path: we don't need to touch the slow qualifiers.
6184 removeLocalFastQualifiers(Mask);
6187 /// Return the address space of this type.
6188 inline LangAS QualType::getAddressSpace() const {
6189 return getQualifiers().getAddressSpace();
6192 /// Return the gc attribute of this type.
6193 inline Qualifiers::GC QualType::getObjCGCAttr() const {
6194 return getQualifiers().getObjCGCAttr();
6197 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6198 if (const auto *PT = t.getAs<PointerType>()) {
6199 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6200 return FT->getExtInfo();
6201 } else if (const auto *FT = t.getAs<FunctionType>())
6202 return FT->getExtInfo();
6204 return FunctionType::ExtInfo();
6207 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6208 return getFunctionExtInfo(*t);
6211 /// Determine whether this type is more
6212 /// qualified than the Other type. For example, "const volatile int"
6213 /// is more qualified than "const int", "volatile int", and
6214 /// "int". However, it is not more qualified than "const volatile
6216 inline bool QualType::isMoreQualifiedThan(QualType other) const {
6217 Qualifiers MyQuals = getQualifiers();
6218 Qualifiers OtherQuals = other.getQualifiers();
6219 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6222 /// Determine whether this type is at last
6223 /// as qualified as the Other type. For example, "const volatile
6224 /// int" is at least as qualified as "const int", "volatile int",
6225 /// "int", and "const volatile int".
6226 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6227 Qualifiers OtherQuals = other.getQualifiers();
6229 // Ignore __unaligned qualifier if this type is a void.
6230 if (getUnqualifiedType()->isVoidType())
6231 OtherQuals.removeUnaligned();
6233 return getQualifiers().compatiblyIncludes(OtherQuals);
6236 /// If Type is a reference type (e.g., const
6237 /// int&), returns the type that the reference refers to ("const
6238 /// int"). Otherwise, returns the type itself. This routine is used
6239 /// throughout Sema to implement C++ 5p6:
6241 /// If an expression initially has the type "reference to T" (8.3.2,
6242 /// 8.5.3), the type is adjusted to "T" prior to any further
6243 /// analysis, the expression designates the object or function
6244 /// denoted by the reference, and the expression is an lvalue.
6245 inline QualType QualType::getNonReferenceType() const {
6246 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6247 return RefType->getPointeeType();
6252 inline bool QualType::isCForbiddenLValueType() const {
6253 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6254 getTypePtr()->isFunctionType());
6257 /// Tests whether the type is categorized as a fundamental type.
6259 /// \returns True for types specified in C++0x [basic.fundamental].
6260 inline bool Type::isFundamentalType() const {
6261 return isVoidType() ||
6262 // FIXME: It's really annoying that we don't have an
6263 // 'isArithmeticType()' which agrees with the standard definition.
6264 (isArithmeticType() && !isEnumeralType());
6267 /// Tests whether the type is categorized as a compound type.
6269 /// \returns True for types specified in C++0x [basic.compound].
6270 inline bool Type::isCompoundType() const {
6271 // C++0x [basic.compound]p1:
6272 // Compound types can be constructed in the following ways:
6273 // -- arrays of objects of a given type [...];
6274 return isArrayType() ||
6275 // -- functions, which have parameters of given types [...];
6277 // -- pointers to void or objects or functions [...];
6279 // -- references to objects or functions of a given type. [...]
6280 isReferenceType() ||
6281 // -- classes containing a sequence of objects of various types, [...];
6283 // -- unions, which are classes capable of containing objects of different
6284 // types at different times;
6286 // -- enumerations, which comprise a set of named constant values. [...];
6288 // -- pointers to non-static class members, [...].
6289 isMemberPointerType();
6292 inline bool Type::isFunctionType() const {
6293 return isa<FunctionType>(CanonicalType);
6296 inline bool Type::isPointerType() const {
6297 return isa<PointerType>(CanonicalType);
6300 inline bool Type::isAnyPointerType() const {
6301 return isPointerType() || isObjCObjectPointerType();
6304 inline bool Type::isBlockPointerType() const {
6305 return isa<BlockPointerType>(CanonicalType);
6308 inline bool Type::isReferenceType() const {
6309 return isa<ReferenceType>(CanonicalType);
6312 inline bool Type::isLValueReferenceType() const {
6313 return isa<LValueReferenceType>(CanonicalType);
6316 inline bool Type::isRValueReferenceType() const {
6317 return isa<RValueReferenceType>(CanonicalType);
6320 inline bool Type::isFunctionPointerType() const {
6321 if (const auto *T = getAs<PointerType>())
6322 return T->getPointeeType()->isFunctionType();
6327 inline bool Type::isMemberPointerType() const {
6328 return isa<MemberPointerType>(CanonicalType);
6331 inline bool Type::isMemberFunctionPointerType() const {
6332 if (const auto *T = getAs<MemberPointerType>())
6333 return T->isMemberFunctionPointer();
6338 inline bool Type::isMemberDataPointerType() const {
6339 if (const auto *T = getAs<MemberPointerType>())
6340 return T->isMemberDataPointer();
6345 inline bool Type::isArrayType() const {
6346 return isa<ArrayType>(CanonicalType);
6349 inline bool Type::isConstantArrayType() const {
6350 return isa<ConstantArrayType>(CanonicalType);
6353 inline bool Type::isIncompleteArrayType() const {
6354 return isa<IncompleteArrayType>(CanonicalType);
6357 inline bool Type::isVariableArrayType() const {
6358 return isa<VariableArrayType>(CanonicalType);
6361 inline bool Type::isDependentSizedArrayType() const {
6362 return isa<DependentSizedArrayType>(CanonicalType);
6365 inline bool Type::isBuiltinType() const {
6366 return isa<BuiltinType>(CanonicalType);
6369 inline bool Type::isRecordType() const {
6370 return isa<RecordType>(CanonicalType);
6373 inline bool Type::isEnumeralType() const {
6374 return isa<EnumType>(CanonicalType);
6377 inline bool Type::isAnyComplexType() const {
6378 return isa<ComplexType>(CanonicalType);
6381 inline bool Type::isVectorType() const {
6382 return isa<VectorType>(CanonicalType);
6385 inline bool Type::isExtVectorType() const {
6386 return isa<ExtVectorType>(CanonicalType);
6389 inline bool Type::isDependentAddressSpaceType() const {
6390 return isa<DependentAddressSpaceType>(CanonicalType);
6393 inline bool Type::isObjCObjectPointerType() const {
6394 return isa<ObjCObjectPointerType>(CanonicalType);
6397 inline bool Type::isObjCObjectType() const {
6398 return isa<ObjCObjectType>(CanonicalType);
6401 inline bool Type::isObjCObjectOrInterfaceType() const {
6402 return isa<ObjCInterfaceType>(CanonicalType) ||
6403 isa<ObjCObjectType>(CanonicalType);
6406 inline bool Type::isAtomicType() const {
6407 return isa<AtomicType>(CanonicalType);
6410 inline bool Type::isObjCQualifiedIdType() const {
6411 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6412 return OPT->isObjCQualifiedIdType();
6416 inline bool Type::isObjCQualifiedClassType() const {
6417 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6418 return OPT->isObjCQualifiedClassType();
6422 inline bool Type::isObjCIdType() const {
6423 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6424 return OPT->isObjCIdType();
6428 inline bool Type::isObjCClassType() const {
6429 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6430 return OPT->isObjCClassType();
6434 inline bool Type::isObjCSelType() const {
6435 if (const auto *OPT = getAs<PointerType>())
6436 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6440 inline bool Type::isObjCBuiltinType() const {
6441 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6444 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6445 inline bool Type::is##Id##Type() const { \
6446 return isSpecificBuiltinType(BuiltinType::Id); \
6448 #include "clang/Basic/OpenCLImageTypes.def"
6450 inline bool Type::isSamplerT() const {
6451 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6454 inline bool Type::isEventT() const {
6455 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6458 inline bool Type::isClkEventT() const {
6459 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6462 inline bool Type::isQueueT() const {
6463 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6466 inline bool Type::isReserveIDT() const {
6467 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6470 inline bool Type::isImageType() const {
6471 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6473 #include "clang/Basic/OpenCLImageTypes.def"
6474 false; // end boolean or operation
6477 inline bool Type::isPipeType() const {
6478 return isa<PipeType>(CanonicalType);
6481 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6482 inline bool Type::is##Id##Type() const { \
6483 return isSpecificBuiltinType(BuiltinType::Id); \
6485 #include "clang/Basic/OpenCLExtensionTypes.def"
6487 inline bool Type::isOCLIntelSubgroupAVCType() const {
6488 #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6489 isOCLIntelSubgroupAVC##Id##Type() ||
6491 #include "clang/Basic/OpenCLExtensionTypes.def"
6492 false; // end of boolean or operation
6495 inline bool Type::isOCLExtOpaqueType() const {
6496 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6498 #include "clang/Basic/OpenCLExtensionTypes.def"
6499 false; // end of boolean or operation
6502 inline bool Type::isOpenCLSpecificType() const {
6503 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6504 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6507 inline bool Type::isTemplateTypeParmType() const {
6508 return isa<TemplateTypeParmType>(CanonicalType);
6511 inline bool Type::isSpecificBuiltinType(unsigned K) const {
6512 if (const BuiltinType *BT = getAs<BuiltinType>())
6513 if (BT->getKind() == (BuiltinType::Kind) K)
6518 inline bool Type::isPlaceholderType() const {
6519 if (const auto *BT = dyn_cast<BuiltinType>(this))
6520 return BT->isPlaceholderType();
6524 inline const BuiltinType *Type::getAsPlaceholderType() const {
6525 if (const auto *BT = dyn_cast<BuiltinType>(this))
6526 if (BT->isPlaceholderType())
6531 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6532 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
6533 if (const auto *BT = dyn_cast<BuiltinType>(this))
6534 return (BT->getKind() == (BuiltinType::Kind) K);
6538 inline bool Type::isNonOverloadPlaceholderType() const {
6539 if (const auto *BT = dyn_cast<BuiltinType>(this))
6540 return BT->isNonOverloadPlaceholderType();
6544 inline bool Type::isVoidType() const {
6545 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6546 return BT->getKind() == BuiltinType::Void;
6550 inline bool Type::isHalfType() const {
6551 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6552 return BT->getKind() == BuiltinType::Half;
6553 // FIXME: Should we allow complex __fp16? Probably not.
6557 inline bool Type::isFloat16Type() const {
6558 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6559 return BT->getKind() == BuiltinType::Float16;
6563 inline bool Type::isFloat128Type() const {
6564 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6565 return BT->getKind() == BuiltinType::Float128;
6569 inline bool Type::isNullPtrType() const {
6570 if (const auto *BT = getAs<BuiltinType>())
6571 return BT->getKind() == BuiltinType::NullPtr;
6575 bool IsEnumDeclComplete(EnumDecl *);
6576 bool IsEnumDeclScoped(EnumDecl *);
6578 inline bool Type::isIntegerType() const {
6579 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6580 return BT->getKind() >= BuiltinType::Bool &&
6581 BT->getKind() <= BuiltinType::Int128;
6582 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6583 // Incomplete enum types are not treated as integer types.
6584 // FIXME: In C++, enum types are never integer types.
6585 return IsEnumDeclComplete(ET->getDecl()) &&
6586 !IsEnumDeclScoped(ET->getDecl());
6591 inline bool Type::isFixedPointType() const {
6592 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6593 return BT->getKind() >= BuiltinType::ShortAccum &&
6594 BT->getKind() <= BuiltinType::SatULongFract;
6599 inline bool Type::isSaturatedFixedPointType() const {
6600 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6601 return BT->getKind() >= BuiltinType::SatShortAccum &&
6602 BT->getKind() <= BuiltinType::SatULongFract;
6607 inline bool Type::isUnsaturatedFixedPointType() const {
6608 return isFixedPointType() && !isSaturatedFixedPointType();
6611 inline bool Type::isSignedFixedPointType() const {
6612 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6613 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6614 BT->getKind() <= BuiltinType::LongAccum) ||
6615 (BT->getKind() >= BuiltinType::ShortFract &&
6616 BT->getKind() <= BuiltinType::LongFract) ||
6617 (BT->getKind() >= BuiltinType::SatShortAccum &&
6618 BT->getKind() <= BuiltinType::SatLongAccum) ||
6619 (BT->getKind() >= BuiltinType::SatShortFract &&
6620 BT->getKind() <= BuiltinType::SatLongFract));
6625 inline bool Type::isUnsignedFixedPointType() const {
6626 return isFixedPointType() && !isSignedFixedPointType();
6629 inline bool Type::isScalarType() const {
6630 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6631 return BT->getKind() > BuiltinType::Void &&
6632 BT->getKind() <= BuiltinType::NullPtr;
6633 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6634 // Enums are scalar types, but only if they are defined. Incomplete enums
6635 // are not treated as scalar types.
6636 return IsEnumDeclComplete(ET->getDecl());
6637 return isa<PointerType>(CanonicalType) ||
6638 isa<BlockPointerType>(CanonicalType) ||
6639 isa<MemberPointerType>(CanonicalType) ||
6640 isa<ComplexType>(CanonicalType) ||
6641 isa<ObjCObjectPointerType>(CanonicalType);
6644 inline bool Type::isIntegralOrEnumerationType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6646 return BT->getKind() >= BuiltinType::Bool &&
6647 BT->getKind() <= BuiltinType::Int128;
6649 // Check for a complete enum type; incomplete enum types are not properly an
6650 // enumeration type in the sense required here.
6651 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6652 return IsEnumDeclComplete(ET->getDecl());
6657 inline bool Type::isBooleanType() const {
6658 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6659 return BT->getKind() == BuiltinType::Bool;
6663 inline bool Type::isUndeducedType() const {
6664 auto *DT = getContainedDeducedType();
6665 return DT && !DT->isDeduced();
6668 /// Determines whether this is a type for which one can define
6669 /// an overloaded operator.
6670 inline bool Type::isOverloadableType() const {
6671 return isDependentType() || isRecordType() || isEnumeralType();
6674 /// Determines whether this type can decay to a pointer type.
6675 inline bool Type::canDecayToPointerType() const {
6676 return isFunctionType() || isArrayType();
6679 inline bool Type::hasPointerRepresentation() const {
6680 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6681 isObjCObjectPointerType() || isNullPtrType());
6684 inline bool Type::hasObjCPointerRepresentation() const {
6685 return isObjCObjectPointerType();
6688 inline const Type *Type::getBaseElementTypeUnsafe() const {
6689 const Type *type = this;
6690 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6691 type = arrayType->getElementType().getTypePtr();
6695 inline const Type *Type::getPointeeOrArrayElementType() const {
6696 const Type *type = this;
6697 if (type->isAnyPointerType())
6698 return type->getPointeeType().getTypePtr();
6699 else if (type->isArrayType())
6700 return type->getBaseElementTypeUnsafe();
6704 /// Insertion operator for diagnostics. This allows sending Qualifiers into a
6705 /// diagnostic with <<.
6706 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6708 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6709 DiagnosticsEngine::ArgumentKind::ak_qual);
6713 /// Insertion operator for partial diagnostics. This allows sending Qualifiers
6714 /// into a diagnostic with <<.
6715 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6717 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6718 DiagnosticsEngine::ArgumentKind::ak_qual);
6722 /// Insertion operator for diagnostics. This allows sending QualType's into a
6723 /// diagnostic with <<.
6724 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6726 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6727 DiagnosticsEngine::ak_qualtype);
6731 /// Insertion operator for partial diagnostics. This allows sending QualType's
6732 /// into a diagnostic with <<.
6733 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6735 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6736 DiagnosticsEngine::ak_qualtype);
6740 // Helper class template that is used by Type::getAs to ensure that one does
6741 // not try to look through a qualified type to get to an array type.
6742 template <typename T>
6743 using TypeIsArrayType =
6744 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6745 std::is_base_of<ArrayType, T>::value>;
6747 // Member-template getAs<specific type>'.
6748 template <typename T> const T *Type::getAs() const {
6749 static_assert(!TypeIsArrayType<T>::value,
6750 "ArrayType cannot be used with getAs!");
6752 // If this is directly a T type, return it.
6753 if (const auto *Ty = dyn_cast<T>(this))
6756 // If the canonical form of this type isn't the right kind, reject it.
6757 if (!isa<T>(CanonicalType))
6760 // If this is a typedef for the type, strip the typedef off without
6761 // losing all typedef information.
6762 return cast<T>(getUnqualifiedDesugaredType());
6765 template <typename T> const T *Type::getAsAdjusted() const {
6766 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6768 // If this is directly a T type, return it.
6769 if (const auto *Ty = dyn_cast<T>(this))
6772 // If the canonical form of this type isn't the right kind, reject it.
6773 if (!isa<T>(CanonicalType))
6776 // Strip off type adjustments that do not modify the underlying nature of the
6778 const Type *Ty = this;
6780 if (const auto *A = dyn_cast<AttributedType>(Ty))
6781 Ty = A->getModifiedType().getTypePtr();
6782 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6783 Ty = E->desugar().getTypePtr();
6784 else if (const auto *P = dyn_cast<ParenType>(Ty))
6785 Ty = P->desugar().getTypePtr();
6786 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6787 Ty = A->desugar().getTypePtr();
6792 // Just because the canonical type is correct does not mean we can use cast<>,
6793 // since we may not have stripped off all the sugar down to the base type.
6794 return dyn_cast<T>(Ty);
6797 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6798 // If this is directly an array type, return it.
6799 if (const auto *arr = dyn_cast<ArrayType>(this))
6802 // If the canonical form of this type isn't the right kind, reject it.
6803 if (!isa<ArrayType>(CanonicalType))
6806 // If this is a typedef for the type, strip the typedef off without
6807 // losing all typedef information.
6808 return cast<ArrayType>(getUnqualifiedDesugaredType());
6811 template <typename T> const T *Type::castAs() const {
6812 static_assert(!TypeIsArrayType<T>::value,
6813 "ArrayType cannot be used with castAs!");
6815 if (const auto *ty = dyn_cast<T>(this)) return ty;
6816 assert(isa<T>(CanonicalType));
6817 return cast<T>(getUnqualifiedDesugaredType());
6820 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6821 assert(isa<ArrayType>(CanonicalType));
6822 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6823 return cast<ArrayType>(getUnqualifiedDesugaredType());
6826 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6827 QualType CanonicalPtr)
6828 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6830 QualType Adjusted = getAdjustedType();
6831 (void)AttributedType::stripOuterNullability(Adjusted);
6832 assert(isa<PointerType>(Adjusted));
6836 QualType DecayedType::getPointeeType() const {
6837 QualType Decayed = getDecayedType();
6838 (void)AttributedType::stripOuterNullability(Decayed);
6839 return cast<PointerType>(Decayed)->getPointeeType();
6842 // Get the decimal string representation of a fixed point type, represented
6843 // as a scaled integer.
6844 void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6847 } // namespace clang
6849 #endif // LLVM_CLANG_AST_TYPE_H