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 //===----------------------------------------------------------------------===//
10 /// \brief C Language Family Type Representation
12 /// This file defines the clang::Type interface and subclasses, used to
13 /// represent types for languages in the C family.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_CLANG_AST_TYPE_H
18 #define LLVM_CLANG_AST_TYPE_H
20 #include "clang/AST/NestedNameSpecifier.h"
21 #include "clang/AST/TemplateName.h"
22 #include "clang/Basic/AddressSpaces.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/ExceptionSpecificationType.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/Basic/Linkage.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/Visibility.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/FoldingSet.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/PointerIntPair.h"
34 #include "llvm/ADT/PointerUnion.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/ADT/iterator_range.h"
37 #include "llvm/Support/ErrorHandling.h"
41 TypeAlignmentInBits = 4,
42 TypeAlignment = 1 << TypeAlignmentInBits
51 class PointerLikeTypeTraits;
53 class PointerLikeTypeTraits< ::clang::Type*> {
55 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
56 static inline ::clang::Type *getFromVoidPointer(void *P) {
57 return static_cast< ::clang::Type*>(P);
59 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
62 class PointerLikeTypeTraits< ::clang::ExtQuals*> {
64 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
65 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
66 return static_cast< ::clang::ExtQuals*>(P);
68 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
72 struct isPodLike<clang::QualType> { static const bool value = true; };
77 class TypedefNameDecl;
79 class TemplateTypeParmDecl;
80 class NonTypeTemplateParmDecl;
81 class TemplateTemplateParmDecl;
88 class ObjCInterfaceDecl;
89 class ObjCProtocolDecl;
91 class UnresolvedUsingTypenameDecl;
95 class StmtIteratorBase;
96 class TemplateArgument;
97 class TemplateArgumentLoc;
98 class TemplateArgumentListInfo;
101 class ExtQualsTypeCommonBase;
102 struct PrintingPolicy;
104 template <typename> class CanQual;
105 typedef CanQual<Type> CanQualType;
107 // Provide forward declarations for all of the *Type classes
108 #define TYPE(Class, Base) class Class##Type;
109 #include "clang/AST/TypeNodes.def"
111 /// The collection of all-type qualifiers we support.
112 /// Clang supports five independent qualifiers:
113 /// * C99: const, volatile, and restrict
114 /// * MS: __unaligned
115 /// * Embedded C (TR18037): address spaces
116 /// * Objective C: the GC attributes (none, weak, or strong)
119 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
123 CVRMask = Const | Volatile | Restrict
133 /// There is no lifetime qualification on this type.
136 /// This object can be modified without requiring retains or
140 /// Assigning into this object requires the old value to be
141 /// released and the new value to be retained. The timing of the
142 /// release of the old value is inexact: it may be moved to
143 /// immediately after the last known point where the value is
147 /// Reading or writing from this object requires a barrier call.
150 /// Assigning into this object requires a lifetime extension.
155 /// The maximum supported address space number.
156 /// 23 bits should be enough for anyone.
157 MaxAddressSpace = 0x7fffffu,
159 /// The width of the "fast" qualifier mask.
162 /// The fast qualifier mask.
163 FastMask = (1 << FastWidth) - 1
166 Qualifiers() : Mask(0) {}
168 /// Returns the common set of qualifiers while removing them from
170 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
171 // If both are only CVR-qualified, bit operations are sufficient.
172 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
174 Q.Mask = L.Mask & R.Mask;
181 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
182 Q.addCVRQualifiers(CommonCRV);
183 L.removeCVRQualifiers(CommonCRV);
184 R.removeCVRQualifiers(CommonCRV);
186 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
187 Q.setObjCGCAttr(L.getObjCGCAttr());
188 L.removeObjCGCAttr();
189 R.removeObjCGCAttr();
192 if (L.getObjCLifetime() == R.getObjCLifetime()) {
193 Q.setObjCLifetime(L.getObjCLifetime());
194 L.removeObjCLifetime();
195 R.removeObjCLifetime();
198 if (L.getAddressSpace() == R.getAddressSpace()) {
199 Q.setAddressSpace(L.getAddressSpace());
200 L.removeAddressSpace();
201 R.removeAddressSpace();
206 static Qualifiers fromFastMask(unsigned Mask) {
208 Qs.addFastQualifiers(Mask);
212 static Qualifiers fromCVRMask(unsigned CVR) {
214 Qs.addCVRQualifiers(CVR);
218 static Qualifiers fromCVRUMask(unsigned CVRU) {
220 Qs.addCVRUQualifiers(CVRU);
224 // Deserialize qualifiers from an opaque representation.
225 static Qualifiers fromOpaqueValue(unsigned opaque) {
231 // Serialize these qualifiers into an opaque representation.
232 unsigned getAsOpaqueValue() const {
236 bool hasConst() const { return Mask & Const; }
237 void setConst(bool flag) {
238 Mask = (Mask & ~Const) | (flag ? Const : 0);
240 void removeConst() { Mask &= ~Const; }
241 void addConst() { Mask |= Const; }
243 bool hasVolatile() const { return Mask & Volatile; }
244 void setVolatile(bool flag) {
245 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
247 void removeVolatile() { Mask &= ~Volatile; }
248 void addVolatile() { Mask |= Volatile; }
250 bool hasRestrict() const { return Mask & Restrict; }
251 void setRestrict(bool flag) {
252 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
254 void removeRestrict() { Mask &= ~Restrict; }
255 void addRestrict() { Mask |= Restrict; }
257 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
258 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
259 void setCVRQualifiers(unsigned mask) {
260 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
261 Mask = (Mask & ~CVRMask) | mask;
263 void removeCVRQualifiers(unsigned mask) {
264 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
267 void removeCVRQualifiers() {
268 removeCVRQualifiers(CVRMask);
270 void addCVRQualifiers(unsigned mask) {
271 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
274 void addCVRUQualifiers(unsigned mask) {
275 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
279 bool hasUnaligned() const { return Mask & UMask; }
280 void setUnaligned(bool flag) {
281 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
283 void removeUnaligned() { Mask &= ~UMask; }
284 void addUnaligned() { Mask |= UMask; }
286 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
287 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
288 void setObjCGCAttr(GC type) {
289 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
291 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
292 void addObjCGCAttr(GC type) {
296 Qualifiers withoutObjCGCAttr() const {
297 Qualifiers qs = *this;
298 qs.removeObjCGCAttr();
301 Qualifiers withoutObjCLifetime() const {
302 Qualifiers qs = *this;
303 qs.removeObjCLifetime();
307 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
308 ObjCLifetime getObjCLifetime() const {
309 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
311 void setObjCLifetime(ObjCLifetime type) {
312 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
314 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
315 void addObjCLifetime(ObjCLifetime type) {
317 assert(!hasObjCLifetime());
318 Mask |= (type << LifetimeShift);
321 /// True if the lifetime is neither None or ExplicitNone.
322 bool hasNonTrivialObjCLifetime() const {
323 ObjCLifetime lifetime = getObjCLifetime();
324 return (lifetime > OCL_ExplicitNone);
327 /// True if the lifetime is either strong or weak.
328 bool hasStrongOrWeakObjCLifetime() const {
329 ObjCLifetime lifetime = getObjCLifetime();
330 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
333 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
334 unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
335 void setAddressSpace(unsigned space) {
336 assert(space <= MaxAddressSpace);
337 Mask = (Mask & ~AddressSpaceMask)
338 | (((uint32_t) space) << AddressSpaceShift);
340 void removeAddressSpace() { setAddressSpace(0); }
341 void addAddressSpace(unsigned space) {
343 setAddressSpace(space);
346 // Fast qualifiers are those that can be allocated directly
347 // on a QualType object.
348 bool hasFastQualifiers() const { return getFastQualifiers(); }
349 unsigned getFastQualifiers() const { return Mask & FastMask; }
350 void setFastQualifiers(unsigned mask) {
351 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
352 Mask = (Mask & ~FastMask) | mask;
354 void removeFastQualifiers(unsigned mask) {
355 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
358 void removeFastQualifiers() {
359 removeFastQualifiers(FastMask);
361 void addFastQualifiers(unsigned mask) {
362 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
366 /// Return true if the set contains any qualifiers which require an ExtQuals
367 /// node to be allocated.
368 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
369 Qualifiers getNonFastQualifiers() const {
370 Qualifiers Quals = *this;
371 Quals.setFastQualifiers(0);
375 /// Return true if the set contains any qualifiers.
376 bool hasQualifiers() const { return Mask; }
377 bool empty() const { return !Mask; }
379 /// Add the qualifiers from the given set to this set.
380 void addQualifiers(Qualifiers Q) {
381 // If the other set doesn't have any non-boolean qualifiers, just
383 if (!(Q.Mask & ~CVRMask))
386 Mask |= (Q.Mask & CVRMask);
387 if (Q.hasAddressSpace())
388 addAddressSpace(Q.getAddressSpace());
389 if (Q.hasObjCGCAttr())
390 addObjCGCAttr(Q.getObjCGCAttr());
391 if (Q.hasObjCLifetime())
392 addObjCLifetime(Q.getObjCLifetime());
396 /// \brief Remove the qualifiers from the given set from this set.
397 void removeQualifiers(Qualifiers Q) {
398 // If the other set doesn't have any non-boolean qualifiers, just
399 // bit-and the inverse in.
400 if (!(Q.Mask & ~CVRMask))
403 Mask &= ~(Q.Mask & CVRMask);
404 if (getObjCGCAttr() == Q.getObjCGCAttr())
406 if (getObjCLifetime() == Q.getObjCLifetime())
407 removeObjCLifetime();
408 if (getAddressSpace() == Q.getAddressSpace())
409 removeAddressSpace();
413 /// Add the qualifiers from the given set to this set, given that
414 /// they don't conflict.
415 void addConsistentQualifiers(Qualifiers qs) {
416 assert(getAddressSpace() == qs.getAddressSpace() ||
417 !hasAddressSpace() || !qs.hasAddressSpace());
418 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
419 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
420 assert(getObjCLifetime() == qs.getObjCLifetime() ||
421 !hasObjCLifetime() || !qs.hasObjCLifetime());
425 /// Returns true if this address space is a superset of the other one.
426 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
427 /// overlapping address spaces.
429 /// every address space is a superset of itself.
431 /// __generic is a superset of any address space except for __constant.
432 bool isAddressSpaceSupersetOf(Qualifiers other) const {
434 // Address spaces must match exactly.
435 getAddressSpace() == other.getAddressSpace() ||
436 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
437 // for __constant can be used as __generic.
438 (getAddressSpace() == LangAS::opencl_generic &&
439 other.getAddressSpace() != LangAS::opencl_constant);
442 /// Determines if these qualifiers compatibly include another set.
443 /// Generally this answers the question of whether an object with the other
444 /// qualifiers can be safely used as an object with these qualifiers.
445 bool compatiblyIncludes(Qualifiers other) const {
446 return isAddressSpaceSupersetOf(other) &&
447 // ObjC GC qualifiers can match, be added, or be removed, but can't
449 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
450 !other.hasObjCGCAttr()) &&
451 // ObjC lifetime qualifiers must match exactly.
452 getObjCLifetime() == other.getObjCLifetime() &&
453 // CVR qualifiers may subset.
454 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
455 // U qualifier may superset.
456 (!other.hasUnaligned() || hasUnaligned());
459 /// \brief Determines if these qualifiers compatibly include another set of
460 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
462 /// One set of Objective-C lifetime qualifiers compatibly includes the other
463 /// if the lifetime qualifiers match, or if both are non-__weak and the
464 /// including set also contains the 'const' qualifier, or both are non-__weak
465 /// and one is None (which can only happen in non-ARC modes).
466 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
467 if (getObjCLifetime() == other.getObjCLifetime())
470 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
473 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
479 /// \brief Determine whether this set of qualifiers is a strict superset of
480 /// another set of qualifiers, not considering qualifier compatibility.
481 bool isStrictSupersetOf(Qualifiers Other) const;
483 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
484 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
486 explicit operator bool() const { return hasQualifiers(); }
488 Qualifiers &operator+=(Qualifiers R) {
493 // Union two qualifier sets. If an enumerated qualifier appears
494 // in both sets, use the one from the right.
495 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
500 Qualifiers &operator-=(Qualifiers R) {
505 /// \brief Compute the difference between two qualifier sets.
506 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
511 std::string getAsString() const;
512 std::string getAsString(const PrintingPolicy &Policy) const;
514 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
515 void print(raw_ostream &OS, const PrintingPolicy &Policy,
516 bool appendSpaceIfNonEmpty = false) const;
518 void Profile(llvm::FoldingSetNodeID &ID) const {
524 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
525 // |C R V|U|GCAttr|Lifetime|AddressSpace|
528 static const uint32_t UMask = 0x8;
529 static const uint32_t UShift = 3;
530 static const uint32_t GCAttrMask = 0x30;
531 static const uint32_t GCAttrShift = 4;
532 static const uint32_t LifetimeMask = 0x1C0;
533 static const uint32_t LifetimeShift = 6;
534 static const uint32_t AddressSpaceMask =
535 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
536 static const uint32_t AddressSpaceShift = 9;
539 /// A std::pair-like structure for storing a qualified type split
540 /// into its local qualifiers and its locally-unqualified type.
541 struct SplitQualType {
542 /// The locally-unqualified type.
545 /// The local qualifiers.
548 SplitQualType() : Ty(nullptr), Quals() {}
549 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
551 SplitQualType getSingleStepDesugaredType() const; // end of this file
553 // Make std::tie work.
554 std::pair<const Type *,Qualifiers> asPair() const {
555 return std::pair<const Type *, Qualifiers>(Ty, Quals);
558 friend bool operator==(SplitQualType a, SplitQualType b) {
559 return a.Ty == b.Ty && a.Quals == b.Quals;
561 friend bool operator!=(SplitQualType a, SplitQualType b) {
562 return a.Ty != b.Ty || a.Quals != b.Quals;
566 /// The kind of type we are substituting Objective-C type arguments into.
568 /// The kind of substitution affects the replacement of type parameters when
569 /// no concrete type information is provided, e.g., when dealing with an
570 /// unspecialized type.
571 enum class ObjCSubstitutionContext {
572 /// An ordinary type.
574 /// The result type of a method or function.
576 /// The parameter type of a method or function.
578 /// The type of a property.
580 /// The superclass of a type.
584 /// A (possibly-)qualified type.
586 /// For efficiency, we don't store CV-qualified types as nodes on their
587 /// own: instead each reference to a type stores the qualifiers. This
588 /// greatly reduces the number of nodes we need to allocate for types (for
589 /// example we only need one for 'int', 'const int', 'volatile int',
590 /// 'const volatile int', etc).
592 /// As an added efficiency bonus, instead of making this a pair, we
593 /// just store the two bits we care about in the low bits of the
594 /// pointer. To handle the packing/unpacking, we make QualType be a
595 /// simple wrapper class that acts like a smart pointer. A third bit
596 /// indicates whether there are extended qualifiers present, in which
597 /// case the pointer points to a special structure.
599 // Thankfully, these are efficiently composable.
600 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
601 Qualifiers::FastWidth> Value;
603 const ExtQuals *getExtQualsUnsafe() const {
604 return Value.getPointer().get<const ExtQuals*>();
607 const Type *getTypePtrUnsafe() const {
608 return Value.getPointer().get<const Type*>();
611 const ExtQualsTypeCommonBase *getCommonPtr() const {
612 assert(!isNull() && "Cannot retrieve a NULL type pointer");
613 uintptr_t CommonPtrVal
614 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
615 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
616 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
619 friend class QualifierCollector;
623 QualType(const Type *Ptr, unsigned Quals)
624 : Value(Ptr, Quals) {}
625 QualType(const ExtQuals *Ptr, unsigned Quals)
626 : Value(Ptr, Quals) {}
628 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
629 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
631 /// Retrieves a pointer to the underlying (unqualified) type.
633 /// This function requires that the type not be NULL. If the type might be
634 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
635 const Type *getTypePtr() const;
637 const Type *getTypePtrOrNull() const;
639 /// Retrieves a pointer to the name of the base type.
640 const IdentifierInfo *getBaseTypeIdentifier() const;
642 /// Divides a QualType into its unqualified type and a set of local
644 SplitQualType split() const;
646 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
647 static QualType getFromOpaquePtr(const void *Ptr) {
649 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
653 const Type &operator*() const {
654 return *getTypePtr();
657 const Type *operator->() const {
661 bool isCanonical() const;
662 bool isCanonicalAsParam() const;
664 /// Return true if this QualType doesn't point to a type yet.
665 bool isNull() const {
666 return Value.getPointer().isNull();
669 /// \brief Determine whether this particular QualType instance has the
670 /// "const" qualifier set, without looking through typedefs that may have
671 /// added "const" at a different level.
672 bool isLocalConstQualified() const {
673 return (getLocalFastQualifiers() & Qualifiers::Const);
676 /// \brief Determine whether this type is const-qualified.
677 bool isConstQualified() const;
679 /// \brief Determine whether this particular QualType instance has the
680 /// "restrict" qualifier set, without looking through typedefs that may have
681 /// added "restrict" at a different level.
682 bool isLocalRestrictQualified() const {
683 return (getLocalFastQualifiers() & Qualifiers::Restrict);
686 /// \brief Determine whether this type is restrict-qualified.
687 bool isRestrictQualified() const;
689 /// \brief Determine whether this particular QualType instance has the
690 /// "volatile" qualifier set, without looking through typedefs that may have
691 /// added "volatile" at a different level.
692 bool isLocalVolatileQualified() const {
693 return (getLocalFastQualifiers() & Qualifiers::Volatile);
696 /// \brief Determine whether this type is volatile-qualified.
697 bool isVolatileQualified() const;
699 /// \brief Determine whether this particular QualType instance has any
700 /// qualifiers, without looking through any typedefs that might add
701 /// qualifiers at a different level.
702 bool hasLocalQualifiers() const {
703 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
706 /// \brief Determine whether this type has any qualifiers.
707 bool hasQualifiers() const;
709 /// \brief Determine whether this particular QualType instance has any
710 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
712 bool hasLocalNonFastQualifiers() const {
713 return Value.getPointer().is<const ExtQuals*>();
716 /// \brief Retrieve the set of qualifiers local to this particular QualType
717 /// instance, not including any qualifiers acquired through typedefs or
719 Qualifiers getLocalQualifiers() const;
721 /// \brief Retrieve the set of qualifiers applied to this type.
722 Qualifiers getQualifiers() const;
724 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
725 /// local to this particular QualType instance, not including any qualifiers
726 /// acquired through typedefs or other sugar.
727 unsigned getLocalCVRQualifiers() const {
728 return getLocalFastQualifiers();
731 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
732 /// applied to this type.
733 unsigned getCVRQualifiers() const;
735 bool isConstant(const ASTContext& Ctx) const {
736 return QualType::isConstant(*this, Ctx);
739 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
740 bool isPODType(const ASTContext &Context) const;
742 /// Return true if this is a POD type according to the rules of the C++98
743 /// standard, regardless of the current compilation's language.
744 bool isCXX98PODType(const ASTContext &Context) const;
746 /// Return true if this is a POD type according to the more relaxed rules
747 /// of the C++11 standard, regardless of the current compilation's language.
748 /// (C++0x [basic.types]p9)
749 bool isCXX11PODType(const ASTContext &Context) const;
751 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
752 bool isTrivialType(const ASTContext &Context) const;
754 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
755 bool isTriviallyCopyableType(const ASTContext &Context) const;
757 // Don't promise in the API that anything besides 'const' can be
760 /// Add the `const` type qualifier to this QualType.
762 addFastQualifiers(Qualifiers::Const);
764 QualType withConst() const {
765 return withFastQualifiers(Qualifiers::Const);
768 /// Add the `volatile` type qualifier to this QualType.
770 addFastQualifiers(Qualifiers::Volatile);
772 QualType withVolatile() const {
773 return withFastQualifiers(Qualifiers::Volatile);
776 /// Add the `restrict` qualifier to this QualType.
778 addFastQualifiers(Qualifiers::Restrict);
780 QualType withRestrict() const {
781 return withFastQualifiers(Qualifiers::Restrict);
784 QualType withCVRQualifiers(unsigned CVR) const {
785 return withFastQualifiers(CVR);
788 void addFastQualifiers(unsigned TQs) {
789 assert(!(TQs & ~Qualifiers::FastMask)
790 && "non-fast qualifier bits set in mask!");
791 Value.setInt(Value.getInt() | TQs);
794 void removeLocalConst();
795 void removeLocalVolatile();
796 void removeLocalRestrict();
797 void removeLocalCVRQualifiers(unsigned Mask);
799 void removeLocalFastQualifiers() { Value.setInt(0); }
800 void removeLocalFastQualifiers(unsigned Mask) {
801 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
802 Value.setInt(Value.getInt() & ~Mask);
805 // Creates a type with the given qualifiers in addition to any
806 // qualifiers already on this type.
807 QualType withFastQualifiers(unsigned TQs) const {
809 T.addFastQualifiers(TQs);
813 // Creates a type with exactly the given fast qualifiers, removing
814 // any existing fast qualifiers.
815 QualType withExactLocalFastQualifiers(unsigned TQs) const {
816 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
819 // Removes fast qualifiers, but leaves any extended qualifiers in place.
820 QualType withoutLocalFastQualifiers() const {
822 T.removeLocalFastQualifiers();
826 QualType getCanonicalType() const;
828 /// \brief Return this type with all of the instance-specific qualifiers
829 /// removed, but without removing any qualifiers that may have been applied
830 /// through typedefs.
831 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
833 /// \brief Retrieve the unqualified variant of the given type,
834 /// removing as little sugar as possible.
836 /// This routine looks through various kinds of sugar to find the
837 /// least-desugared type that is unqualified. For example, given:
840 /// typedef int Integer;
841 /// typedef const Integer CInteger;
842 /// typedef CInteger DifferenceType;
845 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
846 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
848 /// The resulting type might still be qualified if it's sugar for an array
849 /// type. To strip qualifiers even from within a sugared array type, use
850 /// ASTContext::getUnqualifiedArrayType.
851 inline QualType getUnqualifiedType() const;
853 /// Retrieve the unqualified variant of the given type, removing as little
854 /// sugar as possible.
856 /// Like getUnqualifiedType(), but also returns the set of
857 /// qualifiers that were built up.
859 /// The resulting type might still be qualified if it's sugar for an array
860 /// type. To strip qualifiers even from within a sugared array type, use
861 /// ASTContext::getUnqualifiedArrayType.
862 inline SplitQualType getSplitUnqualifiedType() const;
864 /// \brief Determine whether this type is more qualified than the other
865 /// given type, requiring exact equality for non-CVR qualifiers.
866 bool isMoreQualifiedThan(QualType Other) const;
868 /// \brief Determine whether this type is at least as qualified as the other
869 /// given type, requiring exact equality for non-CVR qualifiers.
870 bool isAtLeastAsQualifiedAs(QualType Other) const;
872 QualType getNonReferenceType() const;
874 /// \brief Determine the type of a (typically non-lvalue) expression with the
875 /// specified result type.
877 /// This routine should be used for expressions for which the return type is
878 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
879 /// an lvalue. It removes a top-level reference (since there are no
880 /// expressions of reference type) and deletes top-level cvr-qualifiers
881 /// from non-class types (in C++) or all types (in C).
882 QualType getNonLValueExprType(const ASTContext &Context) const;
884 /// Return the specified type with any "sugar" removed from
885 /// the type. This takes off typedefs, typeof's etc. If the outer level of
886 /// the type is already concrete, it returns it unmodified. This is similar
887 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
888 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
891 /// Qualifiers are left in place.
892 QualType getDesugaredType(const ASTContext &Context) const {
893 return getDesugaredType(*this, Context);
896 SplitQualType getSplitDesugaredType() const {
897 return getSplitDesugaredType(*this);
900 /// \brief Return the specified type with one level of "sugar" removed from
903 /// This routine takes off the first typedef, typeof, etc. If the outer level
904 /// of the type is already concrete, it returns it unmodified.
905 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
906 return getSingleStepDesugaredTypeImpl(*this, Context);
909 /// Returns the specified type after dropping any
910 /// outer-level parentheses.
911 QualType IgnoreParens() const {
912 if (isa<ParenType>(*this))
913 return QualType::IgnoreParens(*this);
917 /// Indicate whether the specified types and qualifiers are identical.
918 friend bool operator==(const QualType &LHS, const QualType &RHS) {
919 return LHS.Value == RHS.Value;
921 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
922 return LHS.Value != RHS.Value;
924 std::string getAsString() const {
925 return getAsString(split());
927 static std::string getAsString(SplitQualType split) {
928 return getAsString(split.Ty, split.Quals);
930 static std::string getAsString(const Type *ty, Qualifiers qs);
932 std::string getAsString(const PrintingPolicy &Policy) const;
934 void print(raw_ostream &OS, const PrintingPolicy &Policy,
935 const Twine &PlaceHolder = Twine(),
936 unsigned Indentation = 0) const {
937 print(split(), OS, Policy, PlaceHolder, Indentation);
939 static void print(SplitQualType split, raw_ostream &OS,
940 const PrintingPolicy &policy, const Twine &PlaceHolder,
941 unsigned Indentation = 0) {
942 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
944 static void print(const Type *ty, Qualifiers qs,
945 raw_ostream &OS, const PrintingPolicy &policy,
946 const Twine &PlaceHolder,
947 unsigned Indentation = 0);
949 void getAsStringInternal(std::string &Str,
950 const PrintingPolicy &Policy) const {
951 return getAsStringInternal(split(), Str, Policy);
953 static void getAsStringInternal(SplitQualType split, std::string &out,
954 const PrintingPolicy &policy) {
955 return getAsStringInternal(split.Ty, split.Quals, out, policy);
957 static void getAsStringInternal(const Type *ty, Qualifiers qs,
959 const PrintingPolicy &policy);
961 class StreamedQualTypeHelper {
963 const PrintingPolicy &Policy;
964 const Twine &PlaceHolder;
965 unsigned Indentation;
967 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
968 const Twine &PlaceHolder, unsigned Indentation)
969 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
970 Indentation(Indentation) { }
972 friend raw_ostream &operator<<(raw_ostream &OS,
973 const StreamedQualTypeHelper &SQT) {
974 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
979 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
980 const Twine &PlaceHolder = Twine(),
981 unsigned Indentation = 0) const {
982 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
985 void dump(const char *s) const;
988 void Profile(llvm::FoldingSetNodeID &ID) const {
989 ID.AddPointer(getAsOpaquePtr());
992 /// Return the address space of this type.
993 inline unsigned getAddressSpace() const;
995 /// Returns gc attribute of this type.
996 inline Qualifiers::GC getObjCGCAttr() const;
998 /// true when Type is objc's weak.
999 bool isObjCGCWeak() const {
1000 return getObjCGCAttr() == Qualifiers::Weak;
1003 /// true when Type is objc's strong.
1004 bool isObjCGCStrong() const {
1005 return getObjCGCAttr() == Qualifiers::Strong;
1008 /// Returns lifetime attribute of this type.
1009 Qualifiers::ObjCLifetime getObjCLifetime() const {
1010 return getQualifiers().getObjCLifetime();
1013 bool hasNonTrivialObjCLifetime() const {
1014 return getQualifiers().hasNonTrivialObjCLifetime();
1017 bool hasStrongOrWeakObjCLifetime() const {
1018 return getQualifiers().hasStrongOrWeakObjCLifetime();
1021 enum DestructionKind {
1024 DK_objc_strong_lifetime,
1025 DK_objc_weak_lifetime
1028 /// Returns a nonzero value if objects of this type require
1029 /// non-trivial work to clean up after. Non-zero because it's
1030 /// conceivable that qualifiers (objc_gc(weak)?) could make
1031 /// something require destruction.
1032 DestructionKind isDestructedType() const {
1033 return isDestructedTypeImpl(*this);
1036 /// Determine whether expressions of the given type are forbidden
1037 /// from being lvalues in C.
1039 /// The expression types that are forbidden to be lvalues are:
1040 /// - 'void', but not qualified void
1041 /// - function types
1043 /// The exact rule here is C99 6.3.2.1:
1044 /// An lvalue is an expression with an object type or an incomplete
1045 /// type other than void.
1046 bool isCForbiddenLValueType() const;
1048 /// Substitute type arguments for the Objective-C type parameters used in the
1051 /// \param ctx ASTContext in which the type exists.
1053 /// \param typeArgs The type arguments that will be substituted for the
1054 /// Objective-C type parameters in the subject type, which are generally
1055 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1056 /// parameters will be replaced with their bounds or id/Class, as appropriate
1057 /// for the context.
1059 /// \param context The context in which the subject type was written.
1061 /// \returns the resulting type.
1062 QualType substObjCTypeArgs(ASTContext &ctx,
1063 ArrayRef<QualType> typeArgs,
1064 ObjCSubstitutionContext context) const;
1066 /// Substitute type arguments from an object type for the Objective-C type
1067 /// parameters used in the subject type.
1069 /// This operation combines the computation of type arguments for
1070 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1071 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1072 /// callers that need to perform a single substitution in isolation.
1074 /// \param objectType The type of the object whose member type we're
1075 /// substituting into. For example, this might be the receiver of a message
1076 /// or the base of a property access.
1078 /// \param dc The declaration context from which the subject type was
1079 /// retrieved, which indicates (for example) which type parameters should
1082 /// \param context The context in which the subject type was written.
1084 /// \returns the subject type after replacing all of the Objective-C type
1085 /// parameters with their corresponding arguments.
1086 QualType substObjCMemberType(QualType objectType,
1087 const DeclContext *dc,
1088 ObjCSubstitutionContext context) const;
1090 /// Strip Objective-C "__kindof" types from the given type.
1091 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1093 /// Remove all qualifiers including _Atomic.
1094 QualType getAtomicUnqualifiedType() const;
1097 // These methods are implemented in a separate translation unit;
1098 // "static"-ize them to avoid creating temporary QualTypes in the
1100 static bool isConstant(QualType T, const ASTContext& Ctx);
1101 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1102 static SplitQualType getSplitDesugaredType(QualType T);
1103 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1104 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1105 const ASTContext &C);
1106 static QualType IgnoreParens(QualType T);
1107 static DestructionKind isDestructedTypeImpl(QualType type);
1113 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1114 /// to a specific Type class.
1115 template<> struct simplify_type< ::clang::QualType> {
1116 typedef const ::clang::Type *SimpleType;
1117 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1118 return Val.getTypePtr();
1122 // Teach SmallPtrSet that QualType is "basically a pointer".
1124 class PointerLikeTypeTraits<clang::QualType> {
1126 static inline void *getAsVoidPointer(clang::QualType P) {
1127 return P.getAsOpaquePtr();
1129 static inline clang::QualType getFromVoidPointer(void *P) {
1130 return clang::QualType::getFromOpaquePtr(P);
1132 // Various qualifiers go in low bits.
1133 enum { NumLowBitsAvailable = 0 };
1136 } // end namespace llvm
1140 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1141 /// classes, which allows \c QualType to access the common fields between the
1144 class ExtQualsTypeCommonBase {
1145 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1146 : BaseType(baseType), CanonicalType(canon) {}
1148 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1149 /// a self-referential pointer (for \c Type).
1151 /// This pointer allows an efficient mapping from a QualType to its
1152 /// underlying type pointer.
1153 const Type *const BaseType;
1155 /// \brief The canonical type of this type. A QualType.
1156 QualType CanonicalType;
1158 friend class QualType;
1160 friend class ExtQuals;
1163 /// We can encode up to four bits in the low bits of a
1164 /// type pointer, but there are many more type qualifiers that we want
1165 /// to be able to apply to an arbitrary type. Therefore we have this
1166 /// struct, intended to be heap-allocated and used by QualType to
1167 /// store qualifiers.
1169 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1170 /// in three low bits on the QualType pointer; a fourth bit records whether
1171 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1172 /// Objective-C GC attributes) are much more rare.
1173 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1174 // NOTE: changing the fast qualifiers should be straightforward as
1175 // long as you don't make 'const' non-fast.
1177 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1178 // Fast qualifiers must occupy the low-order bits.
1179 // b) Update Qualifiers::FastWidth and FastMask.
1181 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1182 // b) Update remove{Volatile,Restrict}, defined near the end of
1185 // a) Update get{Volatile,Restrict}Type.
1187 /// The immutable set of qualifiers applied by this node. Always contains
1188 /// extended qualifiers.
1191 ExtQuals *this_() { return this; }
1194 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1195 : ExtQualsTypeCommonBase(baseType,
1196 canon.isNull() ? QualType(this_(), 0) : canon),
1199 assert(Quals.hasNonFastQualifiers()
1200 && "ExtQuals created with no fast qualifiers");
1201 assert(!Quals.hasFastQualifiers()
1202 && "ExtQuals created with fast qualifiers");
1205 Qualifiers getQualifiers() const { return Quals; }
1207 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1208 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1210 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1211 Qualifiers::ObjCLifetime getObjCLifetime() const {
1212 return Quals.getObjCLifetime();
1215 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1216 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1218 const Type *getBaseType() const { return BaseType; }
1221 void Profile(llvm::FoldingSetNodeID &ID) const {
1222 Profile(ID, getBaseType(), Quals);
1224 static void Profile(llvm::FoldingSetNodeID &ID,
1225 const Type *BaseType,
1227 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1228 ID.AddPointer(BaseType);
1233 /// The kind of C++11 ref-qualifier associated with a function type.
1234 /// This determines whether a member function's "this" object can be an
1235 /// lvalue, rvalue, or neither.
1236 enum RefQualifierKind {
1237 /// \brief No ref-qualifier was provided.
1239 /// \brief An lvalue ref-qualifier was provided (\c &).
1241 /// \brief An rvalue ref-qualifier was provided (\c &&).
1245 /// Which keyword(s) were used to create an AutoType.
1246 enum class AutoTypeKeyword {
1249 /// \brief decltype(auto)
1251 /// \brief __auto_type (GNU extension)
1255 /// The base class of the type hierarchy.
1257 /// A central concept with types is that each type always has a canonical
1258 /// type. A canonical type is the type with any typedef names stripped out
1259 /// of it or the types it references. For example, consider:
1261 /// typedef int foo;
1262 /// typedef foo* bar;
1263 /// 'int *' 'foo *' 'bar'
1265 /// There will be a Type object created for 'int'. Since int is canonical, its
1266 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1267 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1268 /// there is a PointerType that represents 'int*', which, like 'int', is
1269 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1270 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1273 /// Non-canonical types are useful for emitting diagnostics, without losing
1274 /// information about typedefs being used. Canonical types are useful for type
1275 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1276 /// about whether something has a particular form (e.g. is a function type),
1277 /// because they implicitly, recursively, strip all typedefs out of a type.
1279 /// Types, once created, are immutable.
1281 class Type : public ExtQualsTypeCommonBase {
1284 #define TYPE(Class, Base) Class,
1285 #define LAST_TYPE(Class) TypeLast = Class,
1286 #define ABSTRACT_TYPE(Class, Base)
1287 #include "clang/AST/TypeNodes.def"
1288 TagFirst = Record, TagLast = Enum
1292 Type(const Type &) = delete;
1293 void operator=(const Type &) = delete;
1295 /// Bitfields required by the Type class.
1296 class TypeBitfields {
1298 template <class T> friend class TypePropertyCache;
1300 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1303 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1304 unsigned Dependent : 1;
1306 /// Whether this type somehow involves a template parameter, even
1307 /// if the resolution of the type does not depend on a template parameter.
1308 unsigned InstantiationDependent : 1;
1310 /// Whether this type is a variably-modified type (C99 6.7.5).
1311 unsigned VariablyModified : 1;
1313 /// \brief Whether this type contains an unexpanded parameter pack
1314 /// (for C++11 variadic templates).
1315 unsigned ContainsUnexpandedParameterPack : 1;
1317 /// \brief True if the cache (i.e. the bitfields here starting with
1318 /// 'Cache') is valid.
1319 mutable unsigned CacheValid : 1;
1321 /// \brief Linkage of this type.
1322 mutable unsigned CachedLinkage : 3;
1324 /// \brief Whether this type involves and local or unnamed types.
1325 mutable unsigned CachedLocalOrUnnamed : 1;
1327 /// \brief Whether this type comes from an AST file.
1328 mutable unsigned FromAST : 1;
1330 bool isCacheValid() const {
1333 Linkage getLinkage() const {
1334 assert(isCacheValid() && "getting linkage from invalid cache");
1335 return static_cast<Linkage>(CachedLinkage);
1337 bool hasLocalOrUnnamedType() const {
1338 assert(isCacheValid() && "getting linkage from invalid cache");
1339 return CachedLocalOrUnnamed;
1342 enum { NumTypeBits = 18 };
1345 // These classes allow subclasses to somewhat cleanly pack bitfields
1348 class ArrayTypeBitfields {
1349 friend class ArrayType;
1351 unsigned : NumTypeBits;
1353 /// CVR qualifiers from declarations like
1354 /// 'int X[static restrict 4]'. For function parameters only.
1355 unsigned IndexTypeQuals : 3;
1357 /// Storage class qualifiers from declarations like
1358 /// 'int X[static restrict 4]'. For function parameters only.
1359 /// Actually an ArrayType::ArraySizeModifier.
1360 unsigned SizeModifier : 3;
1363 class BuiltinTypeBitfields {
1364 friend class BuiltinType;
1366 unsigned : NumTypeBits;
1368 /// The kind (BuiltinType::Kind) of builtin type this is.
1372 class FunctionTypeBitfields {
1373 friend class FunctionType;
1374 friend class FunctionProtoType;
1376 unsigned : NumTypeBits;
1378 /// Extra information which affects how the function is called, like
1379 /// regparm and the calling convention.
1380 unsigned ExtInfo : 9;
1382 /// Used only by FunctionProtoType, put here to pack with the
1383 /// other bitfields.
1384 /// The qualifiers are part of FunctionProtoType because...
1386 /// C++ 8.3.5p4: The return type, the parameter type list and the
1387 /// cv-qualifier-seq, [...], are part of the function type.
1388 unsigned TypeQuals : 4;
1390 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1392 /// This is a value of type \c RefQualifierKind.
1393 unsigned RefQualifier : 2;
1396 class ObjCObjectTypeBitfields {
1397 friend class ObjCObjectType;
1399 unsigned : NumTypeBits;
1401 /// The number of type arguments stored directly on this object type.
1402 unsigned NumTypeArgs : 7;
1404 /// The number of protocols stored directly on this object type.
1405 unsigned NumProtocols : 6;
1407 /// Whether this is a "kindof" type.
1408 unsigned IsKindOf : 1;
1410 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1412 class ReferenceTypeBitfields {
1413 friend class ReferenceType;
1415 unsigned : NumTypeBits;
1417 /// True if the type was originally spelled with an lvalue sigil.
1418 /// This is never true of rvalue references but can also be false
1419 /// on lvalue references because of C++0x [dcl.typedef]p9,
1422 /// typedef int &ref; // lvalue, spelled lvalue
1423 /// typedef int &&rvref; // rvalue
1424 /// ref &a; // lvalue, inner ref, spelled lvalue
1425 /// ref &&a; // lvalue, inner ref
1426 /// rvref &a; // lvalue, inner ref, spelled lvalue
1427 /// rvref &&a; // rvalue, inner ref
1428 unsigned SpelledAsLValue : 1;
1430 /// True if the inner type is a reference type. This only happens
1431 /// in non-canonical forms.
1432 unsigned InnerRef : 1;
1435 class TypeWithKeywordBitfields {
1436 friend class TypeWithKeyword;
1438 unsigned : NumTypeBits;
1440 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1441 unsigned Keyword : 8;
1444 class VectorTypeBitfields {
1445 friend class VectorType;
1447 unsigned : NumTypeBits;
1449 /// The kind of vector, either a generic vector type or some
1450 /// target-specific vector type such as for AltiVec or Neon.
1451 unsigned VecKind : 3;
1453 /// The number of elements in the vector.
1454 unsigned NumElements : 29 - NumTypeBits;
1456 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1459 class AttributedTypeBitfields {
1460 friend class AttributedType;
1462 unsigned : NumTypeBits;
1464 /// An AttributedType::Kind
1465 unsigned AttrKind : 32 - NumTypeBits;
1468 class AutoTypeBitfields {
1469 friend class AutoType;
1471 unsigned : NumTypeBits;
1473 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1474 /// or '__auto_type'? AutoTypeKeyword value.
1475 unsigned Keyword : 2;
1479 TypeBitfields TypeBits;
1480 ArrayTypeBitfields ArrayTypeBits;
1481 AttributedTypeBitfields AttributedTypeBits;
1482 AutoTypeBitfields AutoTypeBits;
1483 BuiltinTypeBitfields BuiltinTypeBits;
1484 FunctionTypeBitfields FunctionTypeBits;
1485 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1486 ReferenceTypeBitfields ReferenceTypeBits;
1487 TypeWithKeywordBitfields TypeWithKeywordBits;
1488 VectorTypeBitfields VectorTypeBits;
1492 /// \brief Set whether this type comes from an AST file.
1493 void setFromAST(bool V = true) const {
1494 TypeBits.FromAST = V;
1497 template <class T> friend class TypePropertyCache;
1500 // silence VC++ warning C4355: 'this' : used in base member initializer list
1501 Type *this_() { return this; }
1502 Type(TypeClass tc, QualType canon, bool Dependent,
1503 bool InstantiationDependent, bool VariablyModified,
1504 bool ContainsUnexpandedParameterPack)
1505 : ExtQualsTypeCommonBase(this,
1506 canon.isNull() ? QualType(this_(), 0) : canon) {
1508 TypeBits.Dependent = Dependent;
1509 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1510 TypeBits.VariablyModified = VariablyModified;
1511 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1512 TypeBits.CacheValid = false;
1513 TypeBits.CachedLocalOrUnnamed = false;
1514 TypeBits.CachedLinkage = NoLinkage;
1515 TypeBits.FromAST = false;
1517 friend class ASTContext;
1519 void setDependent(bool D = true) {
1520 TypeBits.Dependent = D;
1522 TypeBits.InstantiationDependent = true;
1524 void setInstantiationDependent(bool D = true) {
1525 TypeBits.InstantiationDependent = D; }
1526 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1528 void setContainsUnexpandedParameterPack(bool PP = true) {
1529 TypeBits.ContainsUnexpandedParameterPack = PP;
1533 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1535 /// \brief Whether this type comes from an AST file.
1536 bool isFromAST() const { return TypeBits.FromAST; }
1538 /// \brief Whether this type is or contains an unexpanded parameter
1539 /// pack, used to support C++0x variadic templates.
1541 /// A type that contains a parameter pack shall be expanded by the
1542 /// ellipsis operator at some point. For example, the typedef in the
1543 /// following example contains an unexpanded parameter pack 'T':
1546 /// template<typename ...T>
1548 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1552 /// Note that this routine does not specify which
1553 bool containsUnexpandedParameterPack() const {
1554 return TypeBits.ContainsUnexpandedParameterPack;
1557 /// Determines if this type would be canonical if it had no further
1559 bool isCanonicalUnqualified() const {
1560 return CanonicalType == QualType(this, 0);
1563 /// Pull a single level of sugar off of this locally-unqualified type.
1564 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1565 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1566 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1568 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1569 /// object types, function types, and incomplete types.
1571 /// Return true if this is an incomplete type.
1572 /// A type that can describe objects, but which lacks information needed to
1573 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1574 /// routine will need to determine if the size is actually required.
1576 /// \brief Def If non-null, and the type refers to some kind of declaration
1577 /// that can be completed (such as a C struct, C++ class, or Objective-C
1578 /// class), will be set to the declaration.
1579 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1581 /// Return true if this is an incomplete or object
1582 /// type, in other words, not a function type.
1583 bool isIncompleteOrObjectType() const {
1584 return !isFunctionType();
1587 /// \brief Determine whether this type is an object type.
1588 bool isObjectType() const {
1589 // C++ [basic.types]p8:
1590 // An object type is a (possibly cv-qualified) type that is not a
1591 // function type, not a reference type, and not a void type.
1592 return !isReferenceType() && !isFunctionType() && !isVoidType();
1595 /// Return true if this is a literal type
1596 /// (C++11 [basic.types]p10)
1597 bool isLiteralType(const ASTContext &Ctx) const;
1599 /// Test if this type is a standard-layout type.
1600 /// (C++0x [basic.type]p9)
1601 bool isStandardLayoutType() const;
1603 /// Helper methods to distinguish type categories. All type predicates
1604 /// operate on the canonical type, ignoring typedefs and qualifiers.
1606 /// Returns true if the type is a builtin type.
1607 bool isBuiltinType() const;
1609 /// Test for a particular builtin type.
1610 bool isSpecificBuiltinType(unsigned K) const;
1612 /// Test for a type which does not represent an actual type-system type but
1613 /// is instead used as a placeholder for various convenient purposes within
1614 /// Clang. All such types are BuiltinTypes.
1615 bool isPlaceholderType() const;
1616 const BuiltinType *getAsPlaceholderType() const;
1618 /// Test for a specific placeholder type.
1619 bool isSpecificPlaceholderType(unsigned K) const;
1621 /// Test for a placeholder type other than Overload; see
1622 /// BuiltinType::isNonOverloadPlaceholderType.
1623 bool isNonOverloadPlaceholderType() const;
1625 /// isIntegerType() does *not* include complex integers (a GCC extension).
1626 /// isComplexIntegerType() can be used to test for complex integers.
1627 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1628 bool isEnumeralType() const;
1629 bool isBooleanType() const;
1630 bool isCharType() const;
1631 bool isWideCharType() const;
1632 bool isChar16Type() const;
1633 bool isChar32Type() const;
1634 bool isAnyCharacterType() const;
1635 bool isIntegralType(const ASTContext &Ctx) const;
1637 /// Determine whether this type is an integral or enumeration type.
1638 bool isIntegralOrEnumerationType() const;
1639 /// Determine whether this type is an integral or unscoped enumeration type.
1640 bool isIntegralOrUnscopedEnumerationType() const;
1642 /// Floating point categories.
1643 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1644 /// isComplexType() does *not* include complex integers (a GCC extension).
1645 /// isComplexIntegerType() can be used to test for complex integers.
1646 bool isComplexType() const; // C99 6.2.5p11 (complex)
1647 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1648 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1649 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1650 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1651 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1652 bool isVoidType() const; // C99 6.2.5p19
1653 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1654 bool isAggregateType() const;
1655 bool isFundamentalType() const;
1656 bool isCompoundType() const;
1658 // Type Predicates: Check to see if this type is structurally the specified
1659 // type, ignoring typedefs and qualifiers.
1660 bool isFunctionType() const;
1661 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1662 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1663 bool isPointerType() const;
1664 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1665 bool isBlockPointerType() const;
1666 bool isVoidPointerType() const;
1667 bool isReferenceType() const;
1668 bool isLValueReferenceType() const;
1669 bool isRValueReferenceType() const;
1670 bool isFunctionPointerType() const;
1671 bool isMemberPointerType() const;
1672 bool isMemberFunctionPointerType() const;
1673 bool isMemberDataPointerType() const;
1674 bool isArrayType() const;
1675 bool isConstantArrayType() const;
1676 bool isIncompleteArrayType() const;
1677 bool isVariableArrayType() const;
1678 bool isDependentSizedArrayType() const;
1679 bool isRecordType() const;
1680 bool isClassType() const;
1681 bool isStructureType() const;
1682 bool isObjCBoxableRecordType() const;
1683 bool isInterfaceType() const;
1684 bool isStructureOrClassType() const;
1685 bool isUnionType() const;
1686 bool isComplexIntegerType() const; // GCC _Complex integer type.
1687 bool isVectorType() const; // GCC vector type.
1688 bool isExtVectorType() const; // Extended vector type.
1689 bool isObjCObjectPointerType() const; // pointer to ObjC object
1690 bool isObjCRetainableType() const; // ObjC object or block pointer
1691 bool isObjCLifetimeType() const; // (array of)* retainable type
1692 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1693 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1694 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1695 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1696 // for the common case.
1697 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1698 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1699 bool isObjCQualifiedIdType() const; // id<foo>
1700 bool isObjCQualifiedClassType() const; // Class<foo>
1701 bool isObjCObjectOrInterfaceType() const;
1702 bool isObjCIdType() const; // id
1703 bool isObjCInertUnsafeUnretainedType() const;
1705 /// Whether the type is Objective-C 'id' or a __kindof type of an
1706 /// object type, e.g., __kindof NSView * or __kindof id
1709 /// \param bound Will be set to the bound on non-id subtype types,
1710 /// which will be (possibly specialized) Objective-C class type, or
1712 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1713 const ObjCObjectType *&bound) const;
1715 bool isObjCClassType() const; // Class
1717 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1718 /// Class type, e.g., __kindof Class <NSCopying>.
1720 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1721 /// here because Objective-C's type system cannot express "a class
1722 /// object for a subclass of NSFoo".
1723 bool isObjCClassOrClassKindOfType() const;
1725 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1726 bool isObjCSelType() const; // Class
1727 bool isObjCBuiltinType() const; // 'id' or 'Class'
1728 bool isObjCARCBridgableType() const;
1729 bool isCARCBridgableType() const;
1730 bool isTemplateTypeParmType() const; // C++ template type parameter
1731 bool isNullPtrType() const; // C++0x nullptr_t
1732 bool isAtomicType() const; // C11 _Atomic()
1734 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1735 bool is##Id##Type() const;
1736 #include "clang/Basic/OpenCLImageTypes.def"
1738 bool isImageType() const; // Any OpenCL image type
1740 bool isSamplerT() const; // OpenCL sampler_t
1741 bool isEventT() const; // OpenCL event_t
1742 bool isClkEventT() const; // OpenCL clk_event_t
1743 bool isQueueT() const; // OpenCL queue_t
1744 bool isNDRangeT() const; // OpenCL ndrange_t
1745 bool isReserveIDT() const; // OpenCL reserve_id_t
1747 bool isPipeType() const; // OpenCL pipe type
1748 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1750 /// Determines if this type, which must satisfy
1751 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1752 /// than implicitly __strong.
1753 bool isObjCARCImplicitlyUnretainedType() const;
1755 /// Return the implicit lifetime for this type, which must not be dependent.
1756 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1758 enum ScalarTypeKind {
1761 STK_ObjCObjectPointer,
1766 STK_IntegralComplex,
1769 /// Given that this is a scalar type, classify it.
1770 ScalarTypeKind getScalarTypeKind() const;
1772 /// Whether this type is a dependent type, meaning that its definition
1773 /// somehow depends on a template parameter (C++ [temp.dep.type]).
1774 bool isDependentType() const { return TypeBits.Dependent; }
1776 /// \brief Determine whether this type is an instantiation-dependent type,
1777 /// meaning that the type involves a template parameter (even if the
1778 /// definition does not actually depend on the type substituted for that
1779 /// template parameter).
1780 bool isInstantiationDependentType() const {
1781 return TypeBits.InstantiationDependent;
1784 /// \brief Determine whether this type is an undeduced type, meaning that
1785 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1786 bool isUndeducedType() const;
1788 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1789 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1791 /// \brief Whether this type involves a variable-length array type
1792 /// with a definite size.
1793 bool hasSizedVLAType() const;
1795 /// \brief Whether this type is or contains a local or unnamed type.
1796 bool hasUnnamedOrLocalType() const;
1798 bool isOverloadableType() const;
1800 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1801 bool isElaboratedTypeSpecifier() const;
1803 bool canDecayToPointerType() const;
1805 /// Whether this type is represented natively as a pointer. This includes
1806 /// pointers, references, block pointers, and Objective-C interface,
1807 /// qualified id, and qualified interface types, as well as nullptr_t.
1808 bool hasPointerRepresentation() const;
1810 /// Whether this type can represent an objective pointer type for the
1811 /// purpose of GC'ability
1812 bool hasObjCPointerRepresentation() const;
1814 /// \brief Determine whether this type has an integer representation
1815 /// of some sort, e.g., it is an integer type or a vector.
1816 bool hasIntegerRepresentation() const;
1818 /// \brief Determine whether this type has an signed integer representation
1819 /// of some sort, e.g., it is an signed integer type or a vector.
1820 bool hasSignedIntegerRepresentation() const;
1822 /// \brief Determine whether this type has an unsigned integer representation
1823 /// of some sort, e.g., it is an unsigned integer type or a vector.
1824 bool hasUnsignedIntegerRepresentation() const;
1826 /// \brief Determine whether this type has a floating-point representation
1827 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1828 bool hasFloatingRepresentation() const;
1830 // Type Checking Functions: Check to see if this type is structurally the
1831 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1832 // the best type we can.
1833 const RecordType *getAsStructureType() const;
1834 /// NOTE: getAs*ArrayType are methods on ASTContext.
1835 const RecordType *getAsUnionType() const;
1836 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1837 const ObjCObjectType *getAsObjCInterfaceType() const;
1838 // The following is a convenience method that returns an ObjCObjectPointerType
1839 // for object declared using an interface.
1840 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1841 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1842 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1843 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1845 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1846 /// because the type is a RecordType or because it is the injected-class-name
1847 /// type of a class template or class template partial specialization.
1848 CXXRecordDecl *getAsCXXRecordDecl() const;
1850 /// \brief Retrieves the TagDecl that this type refers to, either
1851 /// because the type is a TagType or because it is the injected-class-name
1852 /// type of a class template or class template partial specialization.
1853 TagDecl *getAsTagDecl() const;
1855 /// If this is a pointer or reference to a RecordType, return the
1856 /// CXXRecordDecl that that type refers to.
1858 /// If this is not a pointer or reference, or the type being pointed to does
1859 /// not refer to a CXXRecordDecl, returns NULL.
1860 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1862 /// Get the AutoType whose type will be deduced for a variable with
1863 /// an initializer of this type. This looks through declarators like pointer
1864 /// types, but not through decltype or typedefs.
1865 AutoType *getContainedAutoType() const;
1867 /// Member-template getAs<specific type>'. Look through sugar for
1868 /// an instance of \<specific type>. This scheme will eventually
1869 /// replace the specific getAsXXXX methods above.
1871 /// There are some specializations of this member template listed
1872 /// immediately following this class.
1873 template <typename T> const T *getAs() const;
1875 /// A variant of getAs<> for array types which silently discards
1876 /// qualifiers from the outermost type.
1877 const ArrayType *getAsArrayTypeUnsafe() const;
1879 /// Member-template castAs<specific type>. Look through sugar for
1880 /// the underlying instance of \<specific type>.
1882 /// This method has the same relationship to getAs<T> as cast<T> has
1883 /// to dyn_cast<T>; which is to say, the underlying type *must*
1884 /// have the intended type, and this method will never return null.
1885 template <typename T> const T *castAs() const;
1887 /// A variant of castAs<> for array type which silently discards
1888 /// qualifiers from the outermost type.
1889 const ArrayType *castAsArrayTypeUnsafe() const;
1891 /// Get the base element type of this type, potentially discarding type
1892 /// qualifiers. This should never be used when type qualifiers
1894 const Type *getBaseElementTypeUnsafe() const;
1896 /// If this is an array type, return the element type of the array,
1897 /// potentially with type qualifiers missing.
1898 /// This should never be used when type qualifiers are meaningful.
1899 const Type *getArrayElementTypeNoTypeQual() const;
1901 /// If this is a pointer type, return the pointee type.
1902 /// If this is an array type, return the array element type.
1903 /// This should never be used when type qualifiers are meaningful.
1904 const Type *getPointeeOrArrayElementType() const;
1906 /// If this is a pointer, ObjC object pointer, or block
1907 /// pointer, this returns the respective pointee.
1908 QualType getPointeeType() const;
1910 /// Return the specified type with any "sugar" removed from the type,
1911 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
1912 const Type *getUnqualifiedDesugaredType() const;
1914 /// More type predicates useful for type checking/promotion
1915 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1917 /// Return true if this is an integer type that is
1918 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1919 /// or an enum decl which has a signed representation.
1920 bool isSignedIntegerType() const;
1922 /// Return true if this is an integer type that is
1923 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1924 /// or an enum decl which has an unsigned representation.
1925 bool isUnsignedIntegerType() const;
1927 /// Determines whether this is an integer type that is signed or an
1928 /// enumeration types whose underlying type is a signed integer type.
1929 bool isSignedIntegerOrEnumerationType() const;
1931 /// Determines whether this is an integer type that is unsigned or an
1932 /// enumeration types whose underlying type is a unsigned integer type.
1933 bool isUnsignedIntegerOrEnumerationType() const;
1935 /// Return true if this is not a variable sized type,
1936 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1937 /// incomplete types.
1938 bool isConstantSizeType() const;
1940 /// Returns true if this type can be represented by some
1941 /// set of type specifiers.
1942 bool isSpecifierType() const;
1944 /// Determine the linkage of this type.
1945 Linkage getLinkage() const;
1947 /// Determine the visibility of this type.
1948 Visibility getVisibility() const {
1949 return getLinkageAndVisibility().getVisibility();
1952 /// Return true if the visibility was explicitly set is the code.
1953 bool isVisibilityExplicit() const {
1954 return getLinkageAndVisibility().isVisibilityExplicit();
1957 /// Determine the linkage and visibility of this type.
1958 LinkageInfo getLinkageAndVisibility() const;
1960 /// True if the computed linkage is valid. Used for consistency
1961 /// checking. Should always return true.
1962 bool isLinkageValid() const;
1964 /// Determine the nullability of the given type.
1966 /// Note that nullability is only captured as sugar within the type
1967 /// system, not as part of the canonical type, so nullability will
1968 /// be lost by canonicalization and desugaring.
1969 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
1971 /// Determine whether the given type can have a nullability
1972 /// specifier applied to it, i.e., if it is any kind of pointer type
1973 /// or a dependent type that could instantiate to any kind of
1975 bool canHaveNullability() const;
1977 /// Retrieve the set of substitutions required when accessing a member
1978 /// of the Objective-C receiver type that is declared in the given context.
1980 /// \c *this is the type of the object we're operating on, e.g., the
1981 /// receiver for a message send or the base of a property access, and is
1982 /// expected to be of some object or object pointer type.
1984 /// \param dc The declaration context for which we are building up a
1985 /// substitution mapping, which should be an Objective-C class, extension,
1986 /// category, or method within.
1988 /// \returns an array of type arguments that can be substituted for
1989 /// the type parameters of the given declaration context in any type described
1990 /// within that context, or an empty optional to indicate that no
1991 /// substitution is required.
1992 Optional<ArrayRef<QualType>>
1993 getObjCSubstitutions(const DeclContext *dc) const;
1995 /// Determines if this is an ObjC interface type that may accept type
1997 bool acceptsObjCTypeParams() const;
1999 const char *getTypeClassName() const;
2001 QualType getCanonicalTypeInternal() const {
2002 return CanonicalType;
2004 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2007 friend class ASTReader;
2008 friend class ASTWriter;
2011 /// \brief This will check for a TypedefType by removing any existing sugar
2012 /// until it reaches a TypedefType or a non-sugared type.
2013 template <> const TypedefType *Type::getAs() const;
2015 /// \brief This will check for a TemplateSpecializationType by removing any
2016 /// existing sugar until it reaches a TemplateSpecializationType or a
2017 /// non-sugared type.
2018 template <> const TemplateSpecializationType *Type::getAs() const;
2020 /// \brief This will check for an AttributedType by removing any existing sugar
2021 /// until it reaches an AttributedType or a non-sugared type.
2022 template <> const AttributedType *Type::getAs() const;
2024 // We can do canonical leaf types faster, because we don't have to
2025 // worry about preserving child type decoration.
2026 #define TYPE(Class, Base)
2027 #define LEAF_TYPE(Class) \
2028 template <> inline const Class##Type *Type::getAs() const { \
2029 return dyn_cast<Class##Type>(CanonicalType); \
2031 template <> inline const Class##Type *Type::castAs() const { \
2032 return cast<Class##Type>(CanonicalType); \
2034 #include "clang/AST/TypeNodes.def"
2037 /// This class is used for builtin types like 'int'. Builtin
2038 /// types are always canonical and have a literal name field.
2039 class BuiltinType : public Type {
2042 // OpenCL image types
2043 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2044 #include "clang/Basic/OpenCLImageTypes.def"
2045 // All other builtin types
2046 #define BUILTIN_TYPE(Id, SingletonId) Id,
2047 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2048 #include "clang/AST/BuiltinTypes.def"
2053 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2054 /*InstantiationDependent=*/(K == Dependent),
2055 /*VariablyModified=*/false,
2056 /*Unexpanded paramter pack=*/false) {
2057 BuiltinTypeBits.Kind = K;
2060 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2061 StringRef getName(const PrintingPolicy &Policy) const;
2062 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2063 // The StringRef is null-terminated.
2064 StringRef str = getName(Policy);
2065 assert(!str.empty() && str.data()[str.size()] == '\0');
2069 bool isSugared() const { return false; }
2070 QualType desugar() const { return QualType(this, 0); }
2072 bool isInteger() const {
2073 return getKind() >= Bool && getKind() <= Int128;
2076 bool isSignedInteger() const {
2077 return getKind() >= Char_S && getKind() <= Int128;
2080 bool isUnsignedInteger() const {
2081 return getKind() >= Bool && getKind() <= UInt128;
2084 bool isFloatingPoint() const {
2085 return getKind() >= Half && getKind() <= Float128;
2088 /// Determines whether the given kind corresponds to a placeholder type.
2089 static bool isPlaceholderTypeKind(Kind K) {
2090 return K >= Overload;
2093 /// Determines whether this type is a placeholder type, i.e. a type
2094 /// which cannot appear in arbitrary positions in a fully-formed
2096 bool isPlaceholderType() const {
2097 return isPlaceholderTypeKind(getKind());
2100 /// Determines whether this type is a placeholder type other than
2101 /// Overload. Most placeholder types require only syntactic
2102 /// information about their context in order to be resolved (e.g.
2103 /// whether it is a call expression), which means they can (and
2104 /// should) be resolved in an earlier "phase" of analysis.
2105 /// Overload expressions sometimes pick up further information
2106 /// from their context, like whether the context expects a
2107 /// specific function-pointer type, and so frequently need
2108 /// special treatment.
2109 bool isNonOverloadPlaceholderType() const {
2110 return getKind() > Overload;
2113 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2116 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2117 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2119 class ComplexType : public Type, public llvm::FoldingSetNode {
2120 QualType ElementType;
2121 ComplexType(QualType Element, QualType CanonicalPtr) :
2122 Type(Complex, CanonicalPtr, Element->isDependentType(),
2123 Element->isInstantiationDependentType(),
2124 Element->isVariablyModifiedType(),
2125 Element->containsUnexpandedParameterPack()),
2126 ElementType(Element) {
2128 friend class ASTContext; // ASTContext creates these.
2131 QualType getElementType() const { return ElementType; }
2133 bool isSugared() const { return false; }
2134 QualType desugar() const { return QualType(this, 0); }
2136 void Profile(llvm::FoldingSetNodeID &ID) {
2137 Profile(ID, getElementType());
2139 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2140 ID.AddPointer(Element.getAsOpaquePtr());
2143 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2146 /// Sugar for parentheses used when specifying types.
2148 class ParenType : public Type, public llvm::FoldingSetNode {
2151 ParenType(QualType InnerType, QualType CanonType) :
2152 Type(Paren, CanonType, InnerType->isDependentType(),
2153 InnerType->isInstantiationDependentType(),
2154 InnerType->isVariablyModifiedType(),
2155 InnerType->containsUnexpandedParameterPack()),
2158 friend class ASTContext; // ASTContext creates these.
2162 QualType getInnerType() const { return Inner; }
2164 bool isSugared() const { return true; }
2165 QualType desugar() const { return getInnerType(); }
2167 void Profile(llvm::FoldingSetNodeID &ID) {
2168 Profile(ID, getInnerType());
2170 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2174 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2177 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2179 class PointerType : public Type, public llvm::FoldingSetNode {
2180 QualType PointeeType;
2182 PointerType(QualType Pointee, QualType CanonicalPtr) :
2183 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2184 Pointee->isInstantiationDependentType(),
2185 Pointee->isVariablyModifiedType(),
2186 Pointee->containsUnexpandedParameterPack()),
2187 PointeeType(Pointee) {
2189 friend class ASTContext; // ASTContext creates these.
2193 QualType getPointeeType() const { return PointeeType; }
2195 /// Returns true if address spaces of pointers overlap.
2196 /// OpenCL v2.0 defines conversion rules for pointers to different
2197 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2200 /// address spaces overlap iff they are they same.
2202 /// __generic overlaps with any address space except for __constant.
2203 bool isAddressSpaceOverlapping(const PointerType &other) const {
2204 Qualifiers thisQuals = PointeeType.getQualifiers();
2205 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2206 // Address spaces overlap if at least one of them is a superset of another
2207 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2208 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2211 bool isSugared() const { return false; }
2212 QualType desugar() const { return QualType(this, 0); }
2214 void Profile(llvm::FoldingSetNodeID &ID) {
2215 Profile(ID, getPointeeType());
2217 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2218 ID.AddPointer(Pointee.getAsOpaquePtr());
2221 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2224 /// Represents a type which was implicitly adjusted by the semantic
2225 /// engine for arbitrary reasons. For example, array and function types can
2226 /// decay, and function types can have their calling conventions adjusted.
2227 class AdjustedType : public Type, public llvm::FoldingSetNode {
2228 QualType OriginalTy;
2229 QualType AdjustedTy;
2232 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2233 QualType CanonicalPtr)
2234 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2235 OriginalTy->isInstantiationDependentType(),
2236 OriginalTy->isVariablyModifiedType(),
2237 OriginalTy->containsUnexpandedParameterPack()),
2238 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2240 friend class ASTContext; // ASTContext creates these.
2243 QualType getOriginalType() const { return OriginalTy; }
2244 QualType getAdjustedType() const { return AdjustedTy; }
2246 bool isSugared() const { return true; }
2247 QualType desugar() const { return AdjustedTy; }
2249 void Profile(llvm::FoldingSetNodeID &ID) {
2250 Profile(ID, OriginalTy, AdjustedTy);
2252 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2253 ID.AddPointer(Orig.getAsOpaquePtr());
2254 ID.AddPointer(New.getAsOpaquePtr());
2257 static bool classof(const Type *T) {
2258 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2262 /// Represents a pointer type decayed from an array or function type.
2263 class DecayedType : public AdjustedType {
2265 DecayedType(QualType OriginalType, QualType DecayedPtr, QualType CanonicalPtr)
2266 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
2267 assert(isa<PointerType>(getAdjustedType()));
2270 friend class ASTContext; // ASTContext creates these.
2273 QualType getDecayedType() const { return getAdjustedType(); }
2275 QualType getPointeeType() const {
2276 return cast<PointerType>(getDecayedType())->getPointeeType();
2279 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2282 /// Pointer to a block type.
2283 /// This type is to represent types syntactically represented as
2284 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2286 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2287 QualType PointeeType; // Block is some kind of pointer type
2288 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2289 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2290 Pointee->isInstantiationDependentType(),
2291 Pointee->isVariablyModifiedType(),
2292 Pointee->containsUnexpandedParameterPack()),
2293 PointeeType(Pointee) {
2295 friend class ASTContext; // ASTContext creates these.
2299 // Get the pointee type. Pointee is required to always be a function type.
2300 QualType getPointeeType() const { return PointeeType; }
2302 bool isSugared() const { return false; }
2303 QualType desugar() const { return QualType(this, 0); }
2305 void Profile(llvm::FoldingSetNodeID &ID) {
2306 Profile(ID, getPointeeType());
2308 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2309 ID.AddPointer(Pointee.getAsOpaquePtr());
2312 static bool classof(const Type *T) {
2313 return T->getTypeClass() == BlockPointer;
2317 /// Base for LValueReferenceType and RValueReferenceType
2319 class ReferenceType : public Type, public llvm::FoldingSetNode {
2320 QualType PointeeType;
2323 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2324 bool SpelledAsLValue) :
2325 Type(tc, CanonicalRef, Referencee->isDependentType(),
2326 Referencee->isInstantiationDependentType(),
2327 Referencee->isVariablyModifiedType(),
2328 Referencee->containsUnexpandedParameterPack()),
2329 PointeeType(Referencee)
2331 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2332 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2336 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2337 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2339 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2340 QualType getPointeeType() const {
2341 // FIXME: this might strip inner qualifiers; okay?
2342 const ReferenceType *T = this;
2343 while (T->isInnerRef())
2344 T = T->PointeeType->castAs<ReferenceType>();
2345 return T->PointeeType;
2348 void Profile(llvm::FoldingSetNodeID &ID) {
2349 Profile(ID, PointeeType, isSpelledAsLValue());
2351 static void Profile(llvm::FoldingSetNodeID &ID,
2352 QualType Referencee,
2353 bool SpelledAsLValue) {
2354 ID.AddPointer(Referencee.getAsOpaquePtr());
2355 ID.AddBoolean(SpelledAsLValue);
2358 static bool classof(const Type *T) {
2359 return T->getTypeClass() == LValueReference ||
2360 T->getTypeClass() == RValueReference;
2364 /// An lvalue reference type, per C++11 [dcl.ref].
2366 class LValueReferenceType : public ReferenceType {
2367 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2368 bool SpelledAsLValue) :
2369 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2371 friend class ASTContext; // ASTContext creates these
2373 bool isSugared() const { return false; }
2374 QualType desugar() const { return QualType(this, 0); }
2376 static bool classof(const Type *T) {
2377 return T->getTypeClass() == LValueReference;
2381 /// An rvalue reference type, per C++11 [dcl.ref].
2383 class RValueReferenceType : public ReferenceType {
2384 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2385 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2387 friend class ASTContext; // ASTContext creates these
2389 bool isSugared() const { return false; }
2390 QualType desugar() const { return QualType(this, 0); }
2392 static bool classof(const Type *T) {
2393 return T->getTypeClass() == RValueReference;
2397 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2399 /// This includes both pointers to data members and pointer to member functions.
2401 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2402 QualType PointeeType;
2403 /// The class of which the pointee is a member. Must ultimately be a
2404 /// RecordType, but could be a typedef or a template parameter too.
2407 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2408 Type(MemberPointer, CanonicalPtr,
2409 Cls->isDependentType() || Pointee->isDependentType(),
2410 (Cls->isInstantiationDependentType() ||
2411 Pointee->isInstantiationDependentType()),
2412 Pointee->isVariablyModifiedType(),
2413 (Cls->containsUnexpandedParameterPack() ||
2414 Pointee->containsUnexpandedParameterPack())),
2415 PointeeType(Pointee), Class(Cls) {
2417 friend class ASTContext; // ASTContext creates these.
2420 QualType getPointeeType() const { return PointeeType; }
2422 /// Returns true if the member type (i.e. the pointee type) is a
2423 /// function type rather than a data-member type.
2424 bool isMemberFunctionPointer() const {
2425 return PointeeType->isFunctionProtoType();
2428 /// Returns true if the member type (i.e. the pointee type) is a
2429 /// data type rather than a function type.
2430 bool isMemberDataPointer() const {
2431 return !PointeeType->isFunctionProtoType();
2434 const Type *getClass() const { return Class; }
2435 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2437 bool isSugared() const { return false; }
2438 QualType desugar() const { return QualType(this, 0); }
2440 void Profile(llvm::FoldingSetNodeID &ID) {
2441 Profile(ID, getPointeeType(), getClass());
2443 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2444 const Type *Class) {
2445 ID.AddPointer(Pointee.getAsOpaquePtr());
2446 ID.AddPointer(Class);
2449 static bool classof(const Type *T) {
2450 return T->getTypeClass() == MemberPointer;
2454 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2456 class ArrayType : public Type, public llvm::FoldingSetNode {
2458 /// Capture whether this is a normal array (e.g. int X[4])
2459 /// an array with a static size (e.g. int X[static 4]), or an array
2460 /// with a star size (e.g. int X[*]).
2461 /// 'static' is only allowed on function parameters.
2462 enum ArraySizeModifier {
2463 Normal, Static, Star
2466 /// The element type of the array.
2467 QualType ElementType;
2470 // C++ [temp.dep.type]p1:
2471 // A type is dependent if it is...
2472 // - an array type constructed from any dependent type or whose
2473 // size is specified by a constant expression that is
2475 ArrayType(TypeClass tc, QualType et, QualType can,
2476 ArraySizeModifier sm, unsigned tq,
2477 bool ContainsUnexpandedParameterPack)
2478 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2479 et->isInstantiationDependentType() || tc == DependentSizedArray,
2480 (tc == VariableArray || et->isVariablyModifiedType()),
2481 ContainsUnexpandedParameterPack),
2483 ArrayTypeBits.IndexTypeQuals = tq;
2484 ArrayTypeBits.SizeModifier = sm;
2487 friend class ASTContext; // ASTContext creates these.
2490 QualType getElementType() const { return ElementType; }
2491 ArraySizeModifier getSizeModifier() const {
2492 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2494 Qualifiers getIndexTypeQualifiers() const {
2495 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2497 unsigned getIndexTypeCVRQualifiers() const {
2498 return ArrayTypeBits.IndexTypeQuals;
2501 static bool classof(const Type *T) {
2502 return T->getTypeClass() == ConstantArray ||
2503 T->getTypeClass() == VariableArray ||
2504 T->getTypeClass() == IncompleteArray ||
2505 T->getTypeClass() == DependentSizedArray;
2509 /// Represents the canonical version of C arrays with a specified constant size.
2510 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2511 /// ConstantArrayType where the element type is 'int' and the size is 404.
2512 class ConstantArrayType : public ArrayType {
2513 llvm::APInt Size; // Allows us to unique the type.
2515 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2516 ArraySizeModifier sm, unsigned tq)
2517 : ArrayType(ConstantArray, et, can, sm, tq,
2518 et->containsUnexpandedParameterPack()),
2521 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2522 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2523 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2525 friend class ASTContext; // ASTContext creates these.
2527 const llvm::APInt &getSize() const { return Size; }
2528 bool isSugared() const { return false; }
2529 QualType desugar() const { return QualType(this, 0); }
2532 /// \brief Determine the number of bits required to address a member of
2533 // an array with the given element type and number of elements.
2534 static unsigned getNumAddressingBits(const ASTContext &Context,
2535 QualType ElementType,
2536 const llvm::APInt &NumElements);
2538 /// \brief Determine the maximum number of active bits that an array's size
2539 /// can require, which limits the maximum size of the array.
2540 static unsigned getMaxSizeBits(const ASTContext &Context);
2542 void Profile(llvm::FoldingSetNodeID &ID) {
2543 Profile(ID, getElementType(), getSize(),
2544 getSizeModifier(), getIndexTypeCVRQualifiers());
2546 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2547 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2548 unsigned TypeQuals) {
2549 ID.AddPointer(ET.getAsOpaquePtr());
2550 ID.AddInteger(ArraySize.getZExtValue());
2551 ID.AddInteger(SizeMod);
2552 ID.AddInteger(TypeQuals);
2554 static bool classof(const Type *T) {
2555 return T->getTypeClass() == ConstantArray;
2559 /// Represents a C array with an unspecified size. For example 'int A[]' has
2560 /// an IncompleteArrayType where the element type is 'int' and the size is
2562 class IncompleteArrayType : public ArrayType {
2564 IncompleteArrayType(QualType et, QualType can,
2565 ArraySizeModifier sm, unsigned tq)
2566 : ArrayType(IncompleteArray, et, can, sm, tq,
2567 et->containsUnexpandedParameterPack()) {}
2568 friend class ASTContext; // ASTContext creates these.
2570 bool isSugared() const { return false; }
2571 QualType desugar() const { return QualType(this, 0); }
2573 static bool classof(const Type *T) {
2574 return T->getTypeClass() == IncompleteArray;
2577 friend class StmtIteratorBase;
2579 void Profile(llvm::FoldingSetNodeID &ID) {
2580 Profile(ID, getElementType(), getSizeModifier(),
2581 getIndexTypeCVRQualifiers());
2584 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2585 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2586 ID.AddPointer(ET.getAsOpaquePtr());
2587 ID.AddInteger(SizeMod);
2588 ID.AddInteger(TypeQuals);
2592 /// Represents a C array with a specified size that is not an
2593 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2594 /// Since the size expression is an arbitrary expression, we store it as such.
2596 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2597 /// should not be: two lexically equivalent variable array types could mean
2598 /// different things, for example, these variables do not have the same type
2601 /// void foo(int x) {
2607 class VariableArrayType : public ArrayType {
2608 /// An assignment-expression. VLA's are only permitted within
2609 /// a function block.
2611 /// The range spanned by the left and right array brackets.
2612 SourceRange Brackets;
2614 VariableArrayType(QualType et, QualType can, Expr *e,
2615 ArraySizeModifier sm, unsigned tq,
2616 SourceRange brackets)
2617 : ArrayType(VariableArray, et, can, sm, tq,
2618 et->containsUnexpandedParameterPack()),
2619 SizeExpr((Stmt*) e), Brackets(brackets) {}
2620 friend class ASTContext; // ASTContext creates these.
2623 Expr *getSizeExpr() const {
2624 // We use C-style casts instead of cast<> here because we do not wish
2625 // to have a dependency of Type.h on Stmt.h/Expr.h.
2626 return (Expr*) SizeExpr;
2628 SourceRange getBracketsRange() const { return Brackets; }
2629 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2630 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2632 bool isSugared() const { return false; }
2633 QualType desugar() const { return QualType(this, 0); }
2635 static bool classof(const Type *T) {
2636 return T->getTypeClass() == VariableArray;
2639 friend class StmtIteratorBase;
2641 void Profile(llvm::FoldingSetNodeID &ID) {
2642 llvm_unreachable("Cannot unique VariableArrayTypes.");
2646 /// Represents an array type in C++ whose size is a value-dependent expression.
2650 /// template<typename T, int Size>
2656 /// For these types, we won't actually know what the array bound is
2657 /// until template instantiation occurs, at which point this will
2658 /// become either a ConstantArrayType or a VariableArrayType.
2659 class DependentSizedArrayType : public ArrayType {
2660 const ASTContext &Context;
2662 /// \brief An assignment expression that will instantiate to the
2663 /// size of the array.
2665 /// The expression itself might be null, in which case the array
2666 /// type will have its size deduced from an initializer.
2669 /// The range spanned by the left and right array brackets.
2670 SourceRange Brackets;
2672 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2673 Expr *e, ArraySizeModifier sm, unsigned tq,
2674 SourceRange brackets);
2676 friend class ASTContext; // ASTContext creates these.
2679 Expr *getSizeExpr() const {
2680 // We use C-style casts instead of cast<> here because we do not wish
2681 // to have a dependency of Type.h on Stmt.h/Expr.h.
2682 return (Expr*) SizeExpr;
2684 SourceRange getBracketsRange() const { return Brackets; }
2685 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2686 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2688 bool isSugared() const { return false; }
2689 QualType desugar() const { return QualType(this, 0); }
2691 static bool classof(const Type *T) {
2692 return T->getTypeClass() == DependentSizedArray;
2695 friend class StmtIteratorBase;
2698 void Profile(llvm::FoldingSetNodeID &ID) {
2699 Profile(ID, Context, getElementType(),
2700 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2703 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2704 QualType ET, ArraySizeModifier SizeMod,
2705 unsigned TypeQuals, Expr *E);
2708 /// Represents an extended vector type where either the type or size is
2713 /// template<typename T, int Size>
2715 /// typedef T __attribute__((ext_vector_type(Size))) type;
2718 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2719 const ASTContext &Context;
2721 /// The element type of the array.
2722 QualType ElementType;
2725 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2726 QualType can, Expr *SizeExpr, SourceLocation loc);
2728 friend class ASTContext;
2731 Expr *getSizeExpr() const { return SizeExpr; }
2732 QualType getElementType() const { return ElementType; }
2733 SourceLocation getAttributeLoc() const { return loc; }
2735 bool isSugared() const { return false; }
2736 QualType desugar() const { return QualType(this, 0); }
2738 static bool classof(const Type *T) {
2739 return T->getTypeClass() == DependentSizedExtVector;
2742 void Profile(llvm::FoldingSetNodeID &ID) {
2743 Profile(ID, Context, getElementType(), getSizeExpr());
2746 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2747 QualType ElementType, Expr *SizeExpr);
2751 /// Represents a GCC generic vector type. This type is created using
2752 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2753 /// bytes; or from an Altivec __vector or vector declaration.
2754 /// Since the constructor takes the number of vector elements, the
2755 /// client is responsible for converting the size into the number of elements.
2756 class VectorType : public Type, public llvm::FoldingSetNode {
2759 GenericVector, ///< not a target-specific vector type
2760 AltiVecVector, ///< is AltiVec vector
2761 AltiVecPixel, ///< is AltiVec 'vector Pixel'
2762 AltiVecBool, ///< is AltiVec 'vector bool ...'
2763 NeonVector, ///< is ARM Neon vector
2764 NeonPolyVector ///< is ARM Neon polynomial vector
2767 /// The element type of the vector.
2768 QualType ElementType;
2770 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2771 VectorKind vecKind);
2773 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2774 QualType canonType, VectorKind vecKind);
2776 friend class ASTContext; // ASTContext creates these.
2780 QualType getElementType() const { return ElementType; }
2781 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2782 static bool isVectorSizeTooLarge(unsigned NumElements) {
2783 return NumElements > VectorTypeBitfields::MaxNumElements;
2786 bool isSugared() const { return false; }
2787 QualType desugar() const { return QualType(this, 0); }
2789 VectorKind getVectorKind() const {
2790 return VectorKind(VectorTypeBits.VecKind);
2793 void Profile(llvm::FoldingSetNodeID &ID) {
2794 Profile(ID, getElementType(), getNumElements(),
2795 getTypeClass(), getVectorKind());
2797 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2798 unsigned NumElements, TypeClass TypeClass,
2799 VectorKind VecKind) {
2800 ID.AddPointer(ElementType.getAsOpaquePtr());
2801 ID.AddInteger(NumElements);
2802 ID.AddInteger(TypeClass);
2803 ID.AddInteger(VecKind);
2806 static bool classof(const Type *T) {
2807 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2811 /// ExtVectorType - Extended vector type. This type is created using
2812 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2813 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2814 /// class enables syntactic extensions, like Vector Components for accessing
2815 /// points, colors, and textures (modeled after OpenGL Shading Language).
2816 class ExtVectorType : public VectorType {
2817 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2818 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2819 friend class ASTContext; // ASTContext creates these.
2821 static int getPointAccessorIdx(char c) {
2830 static int getNumericAccessorIdx(char c) {
2844 case 'a': return 10;
2846 case 'b': return 11;
2848 case 'c': return 12;
2850 case 'd': return 13;
2852 case 'e': return 14;
2854 case 'f': return 15;
2858 static int getAccessorIdx(char c) {
2859 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2860 return getNumericAccessorIdx(c);
2863 bool isAccessorWithinNumElements(char c) const {
2864 if (int idx = getAccessorIdx(c)+1)
2865 return unsigned(idx-1) < getNumElements();
2868 bool isSugared() const { return false; }
2869 QualType desugar() const { return QualType(this, 0); }
2871 static bool classof(const Type *T) {
2872 return T->getTypeClass() == ExtVector;
2876 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2877 /// class of FunctionNoProtoType and FunctionProtoType.
2879 class FunctionType : public Type {
2880 // The type returned by the function.
2881 QualType ResultType;
2884 /// A class which abstracts out some details necessary for
2887 /// It is not actually used directly for storing this information in
2888 /// a FunctionType, although FunctionType does currently use the
2889 /// same bit-pattern.
2891 // If you add a field (say Foo), other than the obvious places (both,
2892 // constructors, compile failures), what you need to update is
2896 // * functionType. Add Foo, getFoo.
2897 // * ASTContext::getFooType
2898 // * ASTContext::mergeFunctionTypes
2899 // * FunctionNoProtoType::Profile
2900 // * FunctionProtoType::Profile
2901 // * TypePrinter::PrintFunctionProto
2902 // * AST read and write
2905 // Feel free to rearrange or add bits, but if you go over 9,
2906 // you'll need to adjust both the Bits field below and
2907 // Type::FunctionTypeBitfields.
2909 // | CC |noreturn|produces|regparm|
2910 // |0 .. 3| 4 | 5 | 6 .. 8|
2912 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2913 enum { CallConvMask = 0xF };
2914 enum { NoReturnMask = 0x10 };
2915 enum { ProducesResultMask = 0x20 };
2916 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2917 RegParmOffset = 6 }; // Assumed to be the last field
2921 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2923 friend class FunctionType;
2926 // Constructor with no defaults. Use this when you know that you
2927 // have all the elements (when reading an AST file for example).
2928 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2929 bool producesResult) {
2930 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2931 Bits = ((unsigned) cc) |
2932 (noReturn ? NoReturnMask : 0) |
2933 (producesResult ? ProducesResultMask : 0) |
2934 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2937 // Constructor with all defaults. Use when for example creating a
2938 // function known to use defaults.
2939 ExtInfo() : Bits(CC_C) { }
2941 // Constructor with just the calling convention, which is an important part
2942 // of the canonical type.
2943 ExtInfo(CallingConv CC) : Bits(CC) { }
2945 bool getNoReturn() const { return Bits & NoReturnMask; }
2946 bool getProducesResult() const { return Bits & ProducesResultMask; }
2947 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2948 unsigned getRegParm() const {
2949 unsigned RegParm = Bits >> RegParmOffset;
2954 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2956 bool operator==(ExtInfo Other) const {
2957 return Bits == Other.Bits;
2959 bool operator!=(ExtInfo Other) const {
2960 return Bits != Other.Bits;
2963 // Note that we don't have setters. That is by design, use
2964 // the following with methods instead of mutating these objects.
2966 ExtInfo withNoReturn(bool noReturn) const {
2968 return ExtInfo(Bits | NoReturnMask);
2970 return ExtInfo(Bits & ~NoReturnMask);
2973 ExtInfo withProducesResult(bool producesResult) const {
2975 return ExtInfo(Bits | ProducesResultMask);
2977 return ExtInfo(Bits & ~ProducesResultMask);
2980 ExtInfo withRegParm(unsigned RegParm) const {
2981 assert(RegParm < 7 && "Invalid regparm value");
2982 return ExtInfo((Bits & ~RegParmMask) |
2983 ((RegParm + 1) << RegParmOffset));
2986 ExtInfo withCallingConv(CallingConv cc) const {
2987 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2990 void Profile(llvm::FoldingSetNodeID &ID) const {
2991 ID.AddInteger(Bits);
2996 FunctionType(TypeClass tc, QualType res,
2997 QualType Canonical, bool Dependent,
2998 bool InstantiationDependent,
2999 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3001 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3002 ContainsUnexpandedParameterPack),
3004 FunctionTypeBits.ExtInfo = Info.Bits;
3006 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3009 QualType getReturnType() const { return ResultType; }
3011 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3012 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3013 /// Determine whether this function type includes the GNU noreturn
3014 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3016 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3017 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3018 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3019 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3020 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3021 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3023 /// \brief Determine the type of an expression that calls a function of
3025 QualType getCallResultType(const ASTContext &Context) const {
3026 return getReturnType().getNonLValueExprType(Context);
3029 static StringRef getNameForCallConv(CallingConv CC);
3031 static bool classof(const Type *T) {
3032 return T->getTypeClass() == FunctionNoProto ||
3033 T->getTypeClass() == FunctionProto;
3037 /// Represents a K&R-style 'int foo()' function, which has
3038 /// no information available about its arguments.
3039 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3040 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3041 : FunctionType(FunctionNoProto, Result, Canonical,
3042 /*Dependent=*/false, /*InstantiationDependent=*/false,
3043 Result->isVariablyModifiedType(),
3044 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3046 friend class ASTContext; // ASTContext creates these.
3049 // No additional state past what FunctionType provides.
3051 bool isSugared() const { return false; }
3052 QualType desugar() const { return QualType(this, 0); }
3054 void Profile(llvm::FoldingSetNodeID &ID) {
3055 Profile(ID, getReturnType(), getExtInfo());
3057 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3060 ID.AddPointer(ResultType.getAsOpaquePtr());
3063 static bool classof(const Type *T) {
3064 return T->getTypeClass() == FunctionNoProto;
3068 /// Represents a prototype with parameter type info, e.g.
3069 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3070 /// parameters, not as having a single void parameter. Such a type can have an
3071 /// exception specification, but this specification is not part of the canonical
3073 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3075 /// Interesting information about a specific parameter that can't simply
3076 /// be reflected in parameter's type.
3078 /// It makes sense to model language features this way when there's some
3079 /// sort of parameter-specific override (such as an attribute) that
3080 /// affects how the function is called. For example, the ARC ns_consumed
3081 /// attribute changes whether a parameter is passed at +0 (the default)
3082 /// or +1 (ns_consumed). This must be reflected in the function type,
3083 /// but isn't really a change to the parameter type.
3085 /// One serious disadvantage of modelling language features this way is
3086 /// that they generally do not work with language features that attempt
3087 /// to destructure types. For example, template argument deduction will
3088 /// not be able to match a parameter declared as
3090 /// against an argument of type
3091 /// void (*)(__attribute__((ns_consumed)) id)
3092 /// because the substitution of T=void, U=id into the former will
3093 /// not produce the latter.
3094 class ExtParameterInfo {
3101 ExtParameterInfo() : Data(0) {}
3103 /// Return the ABI treatment of this parameter.
3104 ParameterABI getABI() const {
3105 return ParameterABI(Data & ABIMask);
3107 ExtParameterInfo withABI(ParameterABI kind) const {
3108 ExtParameterInfo copy = *this;
3109 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3113 /// Is this parameter considered "consumed" by Objective-C ARC?
3114 /// Consumed parameters must have retainable object type.
3115 bool isConsumed() const {
3116 return (Data & IsConsumed);
3118 ExtParameterInfo withIsConsumed(bool consumed) const {
3119 ExtParameterInfo copy = *this;
3121 copy.Data |= IsConsumed;
3123 copy.Data &= ~IsConsumed;
3128 unsigned char getOpaqueValue() const { return Data; }
3129 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3130 ExtParameterInfo result;
3135 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3136 return lhs.Data == rhs.Data;
3138 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3139 return lhs.Data != rhs.Data;
3143 struct ExceptionSpecInfo {
3145 : Type(EST_None), NoexceptExpr(nullptr),
3146 SourceDecl(nullptr), SourceTemplate(nullptr) {}
3148 ExceptionSpecInfo(ExceptionSpecificationType EST)
3149 : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
3150 SourceTemplate(nullptr) {}
3152 /// The kind of exception specification this is.
3153 ExceptionSpecificationType Type;
3154 /// Explicitly-specified list of exception types.
3155 ArrayRef<QualType> Exceptions;
3156 /// Noexcept expression, if this is EST_ComputedNoexcept.
3158 /// The function whose exception specification this is, for
3159 /// EST_Unevaluated and EST_Uninstantiated.
3160 FunctionDecl *SourceDecl;
3161 /// The function template whose exception specification this is instantiated
3162 /// from, for EST_Uninstantiated.
3163 FunctionDecl *SourceTemplate;
3166 /// Extra information about a function prototype.
3167 struct ExtProtoInfo {
3169 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3170 RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3172 ExtProtoInfo(CallingConv CC)
3173 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3174 RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3176 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3177 ExtProtoInfo Result(*this);
3178 Result.ExceptionSpec = O;
3182 FunctionType::ExtInfo ExtInfo;
3184 bool HasTrailingReturn : 1;
3185 unsigned char TypeQuals;
3186 RefQualifierKind RefQualifier;
3187 ExceptionSpecInfo ExceptionSpec;
3188 const ExtParameterInfo *ExtParameterInfos;
3192 /// \brief Determine whether there are any argument types that
3193 /// contain an unexpanded parameter pack.
3194 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3196 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3197 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3203 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3204 QualType canonical, const ExtProtoInfo &epi);
3206 /// The number of parameters this function has, not counting '...'.
3207 unsigned NumParams : 15;
3209 /// The number of types in the exception spec, if any.
3210 unsigned NumExceptions : 9;
3212 /// The type of exception specification this function has.
3213 unsigned ExceptionSpecType : 4;
3215 /// Whether this function has extended parameter information.
3216 unsigned HasExtParameterInfos : 1;
3218 /// Whether the function is variadic.
3219 unsigned Variadic : 1;
3221 /// Whether this function has a trailing return type.
3222 unsigned HasTrailingReturn : 1;
3224 // ParamInfo - There is an variable size array after the class in memory that
3225 // holds the parameter types.
3227 // Exceptions - There is another variable size array after ArgInfo that
3228 // holds the exception types.
3230 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3231 // to the expression in the noexcept() specifier.
3233 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3234 // be a pair of FunctionDecl* pointing to the function which should be used to
3235 // instantiate this function type's exception specification, and the function
3236 // from which it should be instantiated.
3238 // ExtParameterInfos - A variable size array, following the exception
3239 // specification and of length NumParams, holding an ExtParameterInfo
3240 // for each of the parameters. This only appears if HasExtParameterInfos
3243 friend class ASTContext; // ASTContext creates these.
3245 const ExtParameterInfo *getExtParameterInfosBuffer() const {
3246 assert(hasExtParameterInfos());
3248 // Find the end of the exception specification.
3249 const char *ptr = reinterpret_cast<const char *>(exception_begin());
3250 ptr += getExceptionSpecSize();
3252 return reinterpret_cast<const ExtParameterInfo *>(ptr);
3255 size_t getExceptionSpecSize() const {
3256 switch (getExceptionSpecType()) {
3257 case EST_None: return 0;
3258 case EST_DynamicNone: return 0;
3259 case EST_MSAny: return 0;
3260 case EST_BasicNoexcept: return 0;
3261 case EST_Unparsed: return 0;
3262 case EST_Dynamic: return getNumExceptions() * sizeof(QualType);
3263 case EST_ComputedNoexcept: return sizeof(Expr*);
3264 case EST_Uninstantiated: return 2 * sizeof(FunctionDecl*);
3265 case EST_Unevaluated: return sizeof(FunctionDecl*);
3267 llvm_unreachable("bad exception specification kind");
3271 unsigned getNumParams() const { return NumParams; }
3272 QualType getParamType(unsigned i) const {
3273 assert(i < NumParams && "invalid parameter index");
3274 return param_type_begin()[i];
3276 ArrayRef<QualType> getParamTypes() const {
3277 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3280 ExtProtoInfo getExtProtoInfo() const {
3282 EPI.ExtInfo = getExtInfo();
3283 EPI.Variadic = isVariadic();
3284 EPI.HasTrailingReturn = hasTrailingReturn();
3285 EPI.ExceptionSpec.Type = getExceptionSpecType();
3286 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3287 EPI.RefQualifier = getRefQualifier();
3288 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3289 EPI.ExceptionSpec.Exceptions = exceptions();
3290 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3291 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3292 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3293 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3294 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3295 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3296 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3298 if (hasExtParameterInfos())
3299 EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3303 /// Get the kind of exception specification on this function.
3304 ExceptionSpecificationType getExceptionSpecType() const {
3305 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3307 /// Return whether this function has any kind of exception spec.
3308 bool hasExceptionSpec() const {
3309 return getExceptionSpecType() != EST_None;
3311 /// Return whether this function has a dynamic (throw) exception spec.
3312 bool hasDynamicExceptionSpec() const {
3313 return isDynamicExceptionSpec(getExceptionSpecType());
3315 /// Return whether this function has a noexcept exception spec.
3316 bool hasNoexceptExceptionSpec() const {
3317 return isNoexceptExceptionSpec(getExceptionSpecType());
3319 /// Return whether this function has a dependent exception spec.
3320 bool hasDependentExceptionSpec() const;
3321 /// Result type of getNoexceptSpec().
3322 enum NoexceptResult {
3323 NR_NoNoexcept, ///< There is no noexcept specifier.
3324 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3325 NR_Dependent, ///< The noexcept specifier is dependent.
3326 NR_Throw, ///< The noexcept specifier evaluates to false.
3327 NR_Nothrow ///< The noexcept specifier evaluates to true.
3329 /// Get the meaning of the noexcept spec on this function, if any.
3330 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3331 unsigned getNumExceptions() const { return NumExceptions; }
3332 QualType getExceptionType(unsigned i) const {
3333 assert(i < NumExceptions && "Invalid exception number!");
3334 return exception_begin()[i];
3336 Expr *getNoexceptExpr() const {
3337 if (getExceptionSpecType() != EST_ComputedNoexcept)
3339 // NoexceptExpr sits where the arguments end.
3340 return *reinterpret_cast<Expr *const *>(param_type_end());
3342 /// \brief If this function type has an exception specification which hasn't
3343 /// been determined yet (either because it has not been evaluated or because
3344 /// it has not been instantiated), this is the function whose exception
3345 /// specification is represented by this type.
3346 FunctionDecl *getExceptionSpecDecl() const {
3347 if (getExceptionSpecType() != EST_Uninstantiated &&
3348 getExceptionSpecType() != EST_Unevaluated)
3350 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3352 /// \brief If this function type has an uninstantiated exception
3353 /// specification, this is the function whose exception specification
3354 /// should be instantiated to find the exception specification for
3356 FunctionDecl *getExceptionSpecTemplate() const {
3357 if (getExceptionSpecType() != EST_Uninstantiated)
3359 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3361 /// Determine whether this function type has a non-throwing exception
3362 /// specification. If this depends on template arguments, returns
3363 /// \c ResultIfDependent.
3364 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const;
3366 bool isVariadic() const { return Variadic; }
3368 /// Determines whether this function prototype contains a
3369 /// parameter pack at the end.
3371 /// A function template whose last parameter is a parameter pack can be
3372 /// called with an arbitrary number of arguments, much like a variadic
3374 bool isTemplateVariadic() const;
3376 bool hasTrailingReturn() const { return HasTrailingReturn; }
3378 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3381 /// Retrieve the ref-qualifier associated with this function type.
3382 RefQualifierKind getRefQualifier() const {
3383 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3386 typedef const QualType *param_type_iterator;
3387 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3389 param_type_range param_types() const {
3390 return param_type_range(param_type_begin(), param_type_end());
3392 param_type_iterator param_type_begin() const {
3393 return reinterpret_cast<const QualType *>(this+1);
3395 param_type_iterator param_type_end() const {
3396 return param_type_begin() + NumParams;
3399 typedef const QualType *exception_iterator;
3401 ArrayRef<QualType> exceptions() const {
3402 return llvm::makeArrayRef(exception_begin(), exception_end());
3404 exception_iterator exception_begin() const {
3405 // exceptions begin where arguments end
3406 return param_type_end();
3408 exception_iterator exception_end() const {
3409 if (getExceptionSpecType() != EST_Dynamic)
3410 return exception_begin();
3411 return exception_begin() + NumExceptions;
3414 /// Is there any interesting extra information for any of the parameters
3415 /// of this function type?
3416 bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3417 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3418 assert(hasExtParameterInfos());
3419 return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3422 /// Return a pointer to the beginning of the array of extra parameter
3423 /// information, if present, or else null if none of the parameters
3424 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
3425 const ExtParameterInfo *getExtParameterInfosOrNull() const {
3426 if (!hasExtParameterInfos())
3428 return getExtParameterInfosBuffer();
3431 ExtParameterInfo getExtParameterInfo(unsigned I) const {
3432 assert(I < getNumParams() && "parameter index out of range");
3433 if (hasExtParameterInfos())
3434 return getExtParameterInfosBuffer()[I];
3435 return ExtParameterInfo();
3438 ParameterABI getParameterABI(unsigned I) const {
3439 assert(I < getNumParams() && "parameter index out of range");
3440 if (hasExtParameterInfos())
3441 return getExtParameterInfosBuffer()[I].getABI();
3442 return ParameterABI::Ordinary;
3445 bool isParamConsumed(unsigned I) const {
3446 assert(I < getNumParams() && "parameter index out of range");
3447 if (hasExtParameterInfos())
3448 return getExtParameterInfosBuffer()[I].isConsumed();
3452 bool isSugared() const { return false; }
3453 QualType desugar() const { return QualType(this, 0); }
3455 void printExceptionSpecification(raw_ostream &OS,
3456 const PrintingPolicy &Policy) const;
3458 static bool classof(const Type *T) {
3459 return T->getTypeClass() == FunctionProto;
3462 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3463 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3464 param_type_iterator ArgTys, unsigned NumArgs,
3465 const ExtProtoInfo &EPI, const ASTContext &Context);
3468 /// \brief Represents the dependent type named by a dependently-scoped
3469 /// typename using declaration, e.g.
3470 /// using typename Base<T>::foo;
3472 /// Template instantiation turns these into the underlying type.
3473 class UnresolvedUsingType : public Type {
3474 UnresolvedUsingTypenameDecl *Decl;
3476 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3477 : Type(UnresolvedUsing, QualType(), true, true, false,
3478 /*ContainsUnexpandedParameterPack=*/false),
3479 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3480 friend class ASTContext; // ASTContext creates these.
3483 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3485 bool isSugared() const { return false; }
3486 QualType desugar() const { return QualType(this, 0); }
3488 static bool classof(const Type *T) {
3489 return T->getTypeClass() == UnresolvedUsing;
3492 void Profile(llvm::FoldingSetNodeID &ID) {
3493 return Profile(ID, Decl);
3495 static void Profile(llvm::FoldingSetNodeID &ID,
3496 UnresolvedUsingTypenameDecl *D) {
3502 class TypedefType : public Type {
3503 TypedefNameDecl *Decl;
3505 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3506 : Type(tc, can, can->isDependentType(),
3507 can->isInstantiationDependentType(),
3508 can->isVariablyModifiedType(),
3509 /*ContainsUnexpandedParameterPack=*/false),
3510 Decl(const_cast<TypedefNameDecl*>(D)) {
3511 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3513 friend class ASTContext; // ASTContext creates these.
3516 TypedefNameDecl *getDecl() const { return Decl; }
3518 bool isSugared() const { return true; }
3519 QualType desugar() const;
3521 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3524 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3525 class TypeOfExprType : public Type {
3529 TypeOfExprType(Expr *E, QualType can = QualType());
3530 friend class ASTContext; // ASTContext creates these.
3532 Expr *getUnderlyingExpr() const { return TOExpr; }
3534 /// \brief Remove a single level of sugar.
3535 QualType desugar() const;
3537 /// \brief Returns whether this type directly provides sugar.
3538 bool isSugared() const;
3540 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3543 /// \brief Internal representation of canonical, dependent
3544 /// `typeof(expr)` types.
3546 /// This class is used internally by the ASTContext to manage
3547 /// canonical, dependent types, only. Clients will only see instances
3548 /// of this class via TypeOfExprType nodes.
3549 class DependentTypeOfExprType
3550 : public TypeOfExprType, public llvm::FoldingSetNode {
3551 const ASTContext &Context;
3554 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3555 : TypeOfExprType(E), Context(Context) { }
3557 void Profile(llvm::FoldingSetNodeID &ID) {
3558 Profile(ID, Context, getUnderlyingExpr());
3561 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3565 /// Represents `typeof(type)`, a GCC extension.
3566 class TypeOfType : public Type {
3568 TypeOfType(QualType T, QualType can)
3569 : Type(TypeOf, can, T->isDependentType(),
3570 T->isInstantiationDependentType(),
3571 T->isVariablyModifiedType(),
3572 T->containsUnexpandedParameterPack()),
3574 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3576 friend class ASTContext; // ASTContext creates these.
3578 QualType getUnderlyingType() const { return TOType; }
3580 /// \brief Remove a single level of sugar.
3581 QualType desugar() const { return getUnderlyingType(); }
3583 /// \brief Returns whether this type directly provides sugar.
3584 bool isSugared() const { return true; }
3586 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3589 /// Represents the type `decltype(expr)` (C++11).
3590 class DecltypeType : public Type {
3592 QualType UnderlyingType;
3595 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3596 friend class ASTContext; // ASTContext creates these.
3598 Expr *getUnderlyingExpr() const { return E; }
3599 QualType getUnderlyingType() const { return UnderlyingType; }
3601 /// \brief Remove a single level of sugar.
3602 QualType desugar() const;
3604 /// \brief Returns whether this type directly provides sugar.
3605 bool isSugared() const;
3607 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3610 /// \brief Internal representation of canonical, dependent
3611 /// decltype(expr) types.
3613 /// This class is used internally by the ASTContext to manage
3614 /// canonical, dependent types, only. Clients will only see instances
3615 /// of this class via DecltypeType nodes.
3616 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3617 const ASTContext &Context;
3620 DependentDecltypeType(const ASTContext &Context, Expr *E);
3622 void Profile(llvm::FoldingSetNodeID &ID) {
3623 Profile(ID, Context, getUnderlyingExpr());
3626 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3630 /// A unary type transform, which is a type constructed from another.
3631 class UnaryTransformType : public Type {
3638 /// The untransformed type.
3640 /// The transformed type if not dependent, otherwise the same as BaseType.
3641 QualType UnderlyingType;
3645 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3646 QualType CanonicalTy);
3647 friend class ASTContext;
3649 bool isSugared() const { return !isDependentType(); }
3650 QualType desugar() const { return UnderlyingType; }
3652 QualType getUnderlyingType() const { return UnderlyingType; }
3653 QualType getBaseType() const { return BaseType; }
3655 UTTKind getUTTKind() const { return UKind; }
3657 static bool classof(const Type *T) {
3658 return T->getTypeClass() == UnaryTransform;
3662 /// \brief Internal representation of canonical, dependent
3663 /// __underlying_type(type) types.
3665 /// This class is used internally by the ASTContext to manage
3666 /// canonical, dependent types, only. Clients will only see instances
3667 /// of this class via UnaryTransformType nodes.
3668 class DependentUnaryTransformType : public UnaryTransformType,
3669 public llvm::FoldingSetNode {
3671 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
3673 void Profile(llvm::FoldingSetNodeID &ID) {
3674 Profile(ID, getBaseType(), getUTTKind());
3677 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
3679 ID.AddPointer(BaseType.getAsOpaquePtr());
3680 ID.AddInteger((unsigned)UKind);
3684 class TagType : public Type {
3685 /// Stores the TagDecl associated with this type. The decl may point to any
3686 /// TagDecl that declares the entity.
3689 friend class ASTReader;
3692 TagType(TypeClass TC, const TagDecl *D, QualType can);
3695 TagDecl *getDecl() const;
3697 /// Determines whether this type is in the process of being defined.
3698 bool isBeingDefined() const;
3700 static bool classof(const Type *T) {
3701 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3705 /// A helper class that allows the use of isa/cast/dyncast
3706 /// to detect TagType objects of structs/unions/classes.
3707 class RecordType : public TagType {
3709 explicit RecordType(const RecordDecl *D)
3710 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3711 explicit RecordType(TypeClass TC, RecordDecl *D)
3712 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3713 friend class ASTContext; // ASTContext creates these.
3716 RecordDecl *getDecl() const {
3717 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3720 // FIXME: This predicate is a helper to QualType/Type. It needs to
3721 // recursively check all fields for const-ness. If any field is declared
3722 // const, it needs to return false.
3723 bool hasConstFields() const { return false; }
3725 bool isSugared() const { return false; }
3726 QualType desugar() const { return QualType(this, 0); }
3728 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3731 /// A helper class that allows the use of isa/cast/dyncast
3732 /// to detect TagType objects of enums.
3733 class EnumType : public TagType {
3734 explicit EnumType(const EnumDecl *D)
3735 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3736 friend class ASTContext; // ASTContext creates these.
3739 EnumDecl *getDecl() const {
3740 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3743 bool isSugared() const { return false; }
3744 QualType desugar() const { return QualType(this, 0); }
3746 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3749 /// An attributed type is a type to which a type attribute has been applied.
3751 /// The "modified type" is the fully-sugared type to which the attributed
3752 /// type was applied; generally it is not canonically equivalent to the
3753 /// attributed type. The "equivalent type" is the minimally-desugared type
3754 /// which the type is canonically equivalent to.
3756 /// For example, in the following attributed type:
3757 /// int32_t __attribute__((vector_size(16)))
3758 /// - the modified type is the TypedefType for int32_t
3759 /// - the equivalent type is VectorType(16, int32_t)
3760 /// - the canonical type is VectorType(16, int)
3761 class AttributedType : public Type, public llvm::FoldingSetNode {
3763 // It is really silly to have yet another attribute-kind enum, but
3764 // clang::attr::Kind doesn't currently cover the pure type attrs.
3766 // Expression operand.
3770 attr_neon_vector_type,
3771 attr_neon_polyvector_type,
3773 FirstExprOperandKind = attr_address_space,
3774 LastExprOperandKind = attr_neon_polyvector_type,
3776 // Enumerated operand (string or keyword).
3778 attr_objc_ownership,
3782 FirstEnumOperandKind = attr_objc_gc,
3783 LastEnumOperandKind = attr_pcs_vfp,
3805 attr_null_unspecified,
3807 attr_objc_inert_unsafe_unretained,
3811 QualType ModifiedType;
3812 QualType EquivalentType;
3814 friend class ASTContext; // creates these
3816 AttributedType(QualType canon, Kind attrKind,
3817 QualType modified, QualType equivalent)
3818 : Type(Attributed, canon, canon->isDependentType(),
3819 canon->isInstantiationDependentType(),
3820 canon->isVariablyModifiedType(),
3821 canon->containsUnexpandedParameterPack()),
3822 ModifiedType(modified), EquivalentType(equivalent) {
3823 AttributedTypeBits.AttrKind = attrKind;
3827 Kind getAttrKind() const {
3828 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3831 QualType getModifiedType() const { return ModifiedType; }
3832 QualType getEquivalentType() const { return EquivalentType; }
3834 bool isSugared() const { return true; }
3835 QualType desugar() const { return getEquivalentType(); }
3837 /// Does this attribute behave like a type qualifier?
3839 /// A type qualifier adjusts a type to provide specialized rules for
3840 /// a specific object, like the standard const and volatile qualifiers.
3841 /// This includes attributes controlling things like nullability,
3842 /// address spaces, and ARC ownership. The value of the object is still
3843 /// largely described by the modified type.
3845 /// In contrast, many type attributes "rewrite" their modified type to
3846 /// produce a fundamentally different type, not necessarily related in any
3847 /// formalizable way to the original type. For example, calling convention
3848 /// and vector attributes are not simple type qualifiers.
3850 /// Type qualifiers are often, but not always, reflected in the canonical
3852 bool isQualifier() const;
3854 bool isMSTypeSpec() const;
3856 bool isCallingConv() const;
3858 llvm::Optional<NullabilityKind> getImmediateNullability() const;
3860 /// Retrieve the attribute kind corresponding to the given
3861 /// nullability kind.
3862 static Kind getNullabilityAttrKind(NullabilityKind kind) {
3864 case NullabilityKind::NonNull:
3865 return attr_nonnull;
3867 case NullabilityKind::Nullable:
3868 return attr_nullable;
3870 case NullabilityKind::Unspecified:
3871 return attr_null_unspecified;
3873 llvm_unreachable("Unknown nullability kind.");
3876 /// Strip off the top-level nullability annotation on the given
3877 /// type, if it's there.
3879 /// \param T The type to strip. If the type is exactly an
3880 /// AttributedType specifying nullability (without looking through
3881 /// type sugar), the nullability is returned and this type changed
3882 /// to the underlying modified type.
3884 /// \returns the top-level nullability, if present.
3885 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
3887 void Profile(llvm::FoldingSetNodeID &ID) {
3888 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3891 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3892 QualType modified, QualType equivalent) {
3893 ID.AddInteger(attrKind);
3894 ID.AddPointer(modified.getAsOpaquePtr());
3895 ID.AddPointer(equivalent.getAsOpaquePtr());
3898 static bool classof(const Type *T) {
3899 return T->getTypeClass() == Attributed;
3903 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3904 // Helper data collector for canonical types.
3905 struct CanonicalTTPTInfo {
3906 unsigned Depth : 15;
3907 unsigned ParameterPack : 1;
3908 unsigned Index : 16;
3912 // Info for the canonical type.
3913 CanonicalTTPTInfo CanTTPTInfo;
3914 // Info for the non-canonical type.
3915 TemplateTypeParmDecl *TTPDecl;
3918 /// Build a non-canonical type.
3919 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3920 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3921 /*InstantiationDependent=*/true,
3922 /*VariablyModified=*/false,
3923 Canon->containsUnexpandedParameterPack()),
3924 TTPDecl(TTPDecl) { }
3926 /// Build the canonical type.
3927 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3928 : Type(TemplateTypeParm, QualType(this, 0),
3930 /*InstantiationDependent=*/true,
3931 /*VariablyModified=*/false, PP) {
3932 CanTTPTInfo.Depth = D;
3933 CanTTPTInfo.Index = I;
3934 CanTTPTInfo.ParameterPack = PP;
3937 friend class ASTContext; // ASTContext creates these
3939 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3940 QualType Can = getCanonicalTypeInternal();
3941 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3945 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3946 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3947 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3949 TemplateTypeParmDecl *getDecl() const {
3950 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3953 IdentifierInfo *getIdentifier() const;
3955 bool isSugared() const { return false; }
3956 QualType desugar() const { return QualType(this, 0); }
3958 void Profile(llvm::FoldingSetNodeID &ID) {
3959 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3962 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3963 unsigned Index, bool ParameterPack,
3964 TemplateTypeParmDecl *TTPDecl) {
3965 ID.AddInteger(Depth);
3966 ID.AddInteger(Index);
3967 ID.AddBoolean(ParameterPack);
3968 ID.AddPointer(TTPDecl);
3971 static bool classof(const Type *T) {
3972 return T->getTypeClass() == TemplateTypeParm;
3976 /// \brief Represents the result of substituting a type for a template
3979 /// Within an instantiated template, all template type parameters have
3980 /// been replaced with these. They are used solely to record that a
3981 /// type was originally written as a template type parameter;
3982 /// therefore they are never canonical.
3983 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3984 // The original type parameter.
3985 const TemplateTypeParmType *Replaced;
3987 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3988 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3989 Canon->isInstantiationDependentType(),
3990 Canon->isVariablyModifiedType(),
3991 Canon->containsUnexpandedParameterPack()),
3994 friend class ASTContext;
3997 /// Gets the template parameter that was substituted for.
3998 const TemplateTypeParmType *getReplacedParameter() const {
4002 /// Gets the type that was substituted for the template
4004 QualType getReplacementType() const {
4005 return getCanonicalTypeInternal();
4008 bool isSugared() const { return true; }
4009 QualType desugar() const { return getReplacementType(); }
4011 void Profile(llvm::FoldingSetNodeID &ID) {
4012 Profile(ID, getReplacedParameter(), getReplacementType());
4014 static void Profile(llvm::FoldingSetNodeID &ID,
4015 const TemplateTypeParmType *Replaced,
4016 QualType Replacement) {
4017 ID.AddPointer(Replaced);
4018 ID.AddPointer(Replacement.getAsOpaquePtr());
4021 static bool classof(const Type *T) {
4022 return T->getTypeClass() == SubstTemplateTypeParm;
4026 /// \brief Represents the result of substituting a set of types for a template
4027 /// type parameter pack.
4029 /// When a pack expansion in the source code contains multiple parameter packs
4030 /// and those parameter packs correspond to different levels of template
4031 /// parameter lists, this type node is used to represent a template type
4032 /// parameter pack from an outer level, which has already had its argument pack
4033 /// substituted but that still lives within a pack expansion that itself
4034 /// could not be instantiated. When actually performing a substitution into
4035 /// that pack expansion (e.g., when all template parameters have corresponding
4036 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4037 /// at the current pack substitution index.
4038 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4039 /// \brief The original type parameter.
4040 const TemplateTypeParmType *Replaced;
4042 /// \brief A pointer to the set of template arguments that this
4043 /// parameter pack is instantiated with.
4044 const TemplateArgument *Arguments;
4046 /// \brief The number of template arguments in \c Arguments.
4047 unsigned NumArguments;
4049 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4051 const TemplateArgument &ArgPack);
4053 friend class ASTContext;
4056 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4058 /// Gets the template parameter that was substituted for.
4059 const TemplateTypeParmType *getReplacedParameter() const {
4063 bool isSugared() const { return false; }
4064 QualType desugar() const { return QualType(this, 0); }
4066 TemplateArgument getArgumentPack() const;
4068 void Profile(llvm::FoldingSetNodeID &ID);
4069 static void Profile(llvm::FoldingSetNodeID &ID,
4070 const TemplateTypeParmType *Replaced,
4071 const TemplateArgument &ArgPack);
4073 static bool classof(const Type *T) {
4074 return T->getTypeClass() == SubstTemplateTypeParmPack;
4078 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
4080 /// These types are usually a placeholder for a deduced type. However, before
4081 /// the initializer is attached, or if the initializer is type-dependent, there
4082 /// is no deduced type and an auto type is canonical. In the latter case, it is
4083 /// also a dependent type.
4084 class AutoType : public Type, public llvm::FoldingSetNode {
4085 AutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent)
4086 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
4087 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
4088 /*VariablyModified=*/false,
4089 /*ContainsParameterPack=*/DeducedType.isNull()
4090 ? false : DeducedType->containsUnexpandedParameterPack()) {
4091 assert((DeducedType.isNull() || !IsDependent) &&
4092 "auto deduced to dependent type");
4093 AutoTypeBits.Keyword = (unsigned)Keyword;
4096 friend class ASTContext; // ASTContext creates these
4099 bool isDecltypeAuto() const {
4100 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4102 AutoTypeKeyword getKeyword() const {
4103 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4106 bool isSugared() const { return !isCanonicalUnqualified(); }
4107 QualType desugar() const { return getCanonicalTypeInternal(); }
4109 /// \brief Get the type deduced for this auto type, or null if it's either
4110 /// not been deduced or was deduced to a dependent type.
4111 QualType getDeducedType() const {
4112 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4114 bool isDeduced() const {
4115 return !isCanonicalUnqualified() || isDependentType();
4118 void Profile(llvm::FoldingSetNodeID &ID) {
4119 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4122 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4123 AutoTypeKeyword Keyword, bool IsDependent) {
4124 ID.AddPointer(Deduced.getAsOpaquePtr());
4125 ID.AddInteger((unsigned)Keyword);
4126 ID.AddBoolean(IsDependent);
4129 static bool classof(const Type *T) {
4130 return T->getTypeClass() == Auto;
4134 /// \brief Represents a type template specialization; the template
4135 /// must be a class template, a type alias template, or a template
4136 /// template parameter. A template which cannot be resolved to one of
4137 /// these, e.g. because it is written with a dependent scope
4138 /// specifier, is instead represented as a
4139 /// @c DependentTemplateSpecializationType.
4141 /// A non-dependent template specialization type is always "sugar",
4142 /// typically for a \c RecordType. For example, a class template
4143 /// specialization type of \c vector<int> will refer to a tag type for
4144 /// the instantiation \c std::vector<int, std::allocator<int>>
4146 /// Template specializations are dependent if either the template or
4147 /// any of the template arguments are dependent, in which case the
4148 /// type may also be canonical.
4150 /// Instances of this type are allocated with a trailing array of
4151 /// TemplateArguments, followed by a QualType representing the
4152 /// non-canonical aliased type when the template is a type alias
4154 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
4156 public llvm::FoldingSetNode {
4157 /// The name of the template being specialized. This is
4158 /// either a TemplateName::Template (in which case it is a
4159 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4160 /// TypeAliasTemplateDecl*), a
4161 /// TemplateName::SubstTemplateTemplateParmPack, or a
4162 /// TemplateName::SubstTemplateTemplateParm (in which case the
4163 /// replacement must, recursively, be one of these).
4164 TemplateName Template;
4166 /// The number of template arguments named in this class template
4168 unsigned NumArgs : 31;
4170 /// Whether this template specialization type is a substituted type alias.
4171 unsigned TypeAlias : 1;
4173 TemplateSpecializationType(TemplateName T,
4174 ArrayRef<TemplateArgument> Args,
4178 friend class ASTContext; // ASTContext creates these
4181 /// Determine whether any of the given template arguments are dependent.
4182 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4183 bool &InstantiationDependent);
4185 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4186 bool &InstantiationDependent);
4188 /// \brief Print a template argument list, including the '<' and '>'
4189 /// enclosing the template arguments.
4190 static void PrintTemplateArgumentList(raw_ostream &OS,
4191 ArrayRef<TemplateArgument> Args,
4192 const PrintingPolicy &Policy,
4193 bool SkipBrackets = false);
4195 static void PrintTemplateArgumentList(raw_ostream &OS,
4196 ArrayRef<TemplateArgumentLoc> Args,
4197 const PrintingPolicy &Policy);
4199 static void PrintTemplateArgumentList(raw_ostream &OS,
4200 const TemplateArgumentListInfo &,
4201 const PrintingPolicy &Policy);
4203 /// True if this template specialization type matches a current
4204 /// instantiation in the context in which it is found.
4205 bool isCurrentInstantiation() const {
4206 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4209 /// \brief Determine if this template specialization type is for a type alias
4210 /// template that has been substituted.
4212 /// Nearly every template specialization type whose template is an alias
4213 /// template will be substituted. However, this is not the case when
4214 /// the specialization contains a pack expansion but the template alias
4215 /// does not have a corresponding parameter pack, e.g.,
4218 /// template<typename T, typename U, typename V> struct S;
4219 /// template<typename T, typename U> using A = S<T, int, U>;
4220 /// template<typename... Ts> struct X {
4221 /// typedef A<Ts...> type; // not a type alias
4224 bool isTypeAlias() const { return TypeAlias; }
4226 /// Get the aliased type, if this is a specialization of a type alias
4228 QualType getAliasedType() const {
4229 assert(isTypeAlias() && "not a type alias template specialization");
4230 return *reinterpret_cast<const QualType*>(end());
4233 typedef const TemplateArgument * iterator;
4235 iterator begin() const { return getArgs(); }
4236 iterator end() const; // defined inline in TemplateBase.h
4238 /// Retrieve the name of the template that we are specializing.
4239 TemplateName getTemplateName() const { return Template; }
4241 /// Retrieve the template arguments.
4242 const TemplateArgument *getArgs() const {
4243 return reinterpret_cast<const TemplateArgument *>(this + 1);
4246 /// Retrieve the number of template arguments.
4247 unsigned getNumArgs() const { return NumArgs; }
4249 /// Retrieve a specific template argument as a type.
4250 /// \pre \c isArgType(Arg)
4251 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4253 ArrayRef<TemplateArgument> template_arguments() const {
4254 return {getArgs(), NumArgs};
4257 bool isSugared() const {
4258 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4260 QualType desugar() const { return getCanonicalTypeInternal(); }
4262 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4263 Profile(ID, Template, template_arguments(), Ctx);
4265 getAliasedType().Profile(ID);
4268 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4269 ArrayRef<TemplateArgument> Args,
4270 const ASTContext &Context);
4272 static bool classof(const Type *T) {
4273 return T->getTypeClass() == TemplateSpecialization;
4277 /// The injected class name of a C++ class template or class
4278 /// template partial specialization. Used to record that a type was
4279 /// spelled with a bare identifier rather than as a template-id; the
4280 /// equivalent for non-templated classes is just RecordType.
4282 /// Injected class name types are always dependent. Template
4283 /// instantiation turns these into RecordTypes.
4285 /// Injected class name types are always canonical. This works
4286 /// because it is impossible to compare an injected class name type
4287 /// with the corresponding non-injected template type, for the same
4288 /// reason that it is impossible to directly compare template
4289 /// parameters from different dependent contexts: injected class name
4290 /// types can only occur within the scope of a particular templated
4291 /// declaration, and within that scope every template specialization
4292 /// will canonicalize to the injected class name (when appropriate
4293 /// according to the rules of the language).
4294 class InjectedClassNameType : public Type {
4295 CXXRecordDecl *Decl;
4297 /// The template specialization which this type represents.
4299 /// template <class T> class A { ... };
4300 /// this is A<T>, whereas in
4301 /// template <class X, class Y> class A<B<X,Y> > { ... };
4302 /// this is A<B<X,Y> >.
4304 /// It is always unqualified, always a template specialization type,
4305 /// and always dependent.
4306 QualType InjectedType;
4308 friend class ASTContext; // ASTContext creates these.
4309 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4310 // currently suitable for AST reading, too much
4311 // interdependencies.
4312 friend class ASTNodeImporter;
4314 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4315 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4316 /*InstantiationDependent=*/true,
4317 /*VariablyModified=*/false,
4318 /*ContainsUnexpandedParameterPack=*/false),
4319 Decl(D), InjectedType(TST) {
4320 assert(isa<TemplateSpecializationType>(TST));
4321 assert(!TST.hasQualifiers());
4322 assert(TST->isDependentType());
4326 QualType getInjectedSpecializationType() const { return InjectedType; }
4327 const TemplateSpecializationType *getInjectedTST() const {
4328 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4331 CXXRecordDecl *getDecl() const;
4333 bool isSugared() const { return false; }
4334 QualType desugar() const { return QualType(this, 0); }
4336 static bool classof(const Type *T) {
4337 return T->getTypeClass() == InjectedClassName;
4341 /// \brief The kind of a tag type.
4343 /// \brief The "struct" keyword.
4345 /// \brief The "__interface" keyword.
4347 /// \brief The "union" keyword.
4349 /// \brief The "class" keyword.
4351 /// \brief The "enum" keyword.
4355 /// \brief The elaboration keyword that precedes a qualified type name or
4356 /// introduces an elaborated-type-specifier.
4357 enum ElaboratedTypeKeyword {
4358 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4360 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4362 /// \brief The "union" keyword introduces the elaborated-type-specifier.
4364 /// \brief The "class" keyword introduces the elaborated-type-specifier.
4366 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4368 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4369 /// \c typename T::type.
4371 /// \brief No keyword precedes the qualified type name.
4375 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4376 /// The keyword in stored in the free bits of the base class.
4377 /// Also provides a few static helpers for converting and printing
4378 /// elaborated type keyword and tag type kind enumerations.
4379 class TypeWithKeyword : public Type {
4381 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4382 QualType Canonical, bool Dependent,
4383 bool InstantiationDependent, bool VariablyModified,
4384 bool ContainsUnexpandedParameterPack)
4385 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4386 ContainsUnexpandedParameterPack) {
4387 TypeWithKeywordBits.Keyword = Keyword;
4391 ElaboratedTypeKeyword getKeyword() const {
4392 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4395 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4396 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4398 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4399 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4400 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4402 /// Converts a TagTypeKind into an elaborated type keyword.
4403 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4405 /// Converts an elaborated type keyword into a TagTypeKind.
4406 /// It is an error to provide an elaborated type keyword
4407 /// which *isn't* a tag kind here.
4408 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4410 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4412 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4414 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4415 return getKeywordName(getKeywordForTagTypeKind(Kind));
4418 class CannotCastToThisType {};
4419 static CannotCastToThisType classof(const Type *);
4422 /// \brief Represents a type that was referred to using an elaborated type
4423 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4426 /// This type is used to keep track of a type name as written in the
4427 /// source code, including tag keywords and any nested-name-specifiers.
4428 /// The type itself is always "sugar", used to express what was written
4429 /// in the source code but containing no additional semantic information.
4430 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4432 /// The nested name specifier containing the qualifier.
4433 NestedNameSpecifier *NNS;
4435 /// The type that this qualified name refers to.
4438 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4439 QualType NamedType, QualType CanonType)
4440 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4441 NamedType->isDependentType(),
4442 NamedType->isInstantiationDependentType(),
4443 NamedType->isVariablyModifiedType(),
4444 NamedType->containsUnexpandedParameterPack()),
4445 NNS(NNS), NamedType(NamedType) {
4446 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4447 "ElaboratedType cannot have elaborated type keyword "
4448 "and name qualifier both null.");
4451 friend class ASTContext; // ASTContext creates these
4456 /// Retrieve the qualification on this type.
4457 NestedNameSpecifier *getQualifier() const { return NNS; }
4459 /// Retrieve the type named by the qualified-id.
4460 QualType getNamedType() const { return NamedType; }
4462 /// Remove a single level of sugar.
4463 QualType desugar() const { return getNamedType(); }
4465 /// Returns whether this type directly provides sugar.
4466 bool isSugared() const { return true; }
4468 void Profile(llvm::FoldingSetNodeID &ID) {
4469 Profile(ID, getKeyword(), NNS, NamedType);
4472 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4473 NestedNameSpecifier *NNS, QualType NamedType) {
4474 ID.AddInteger(Keyword);
4476 NamedType.Profile(ID);
4479 static bool classof(const Type *T) {
4480 return T->getTypeClass() == Elaborated;
4484 /// \brief Represents a qualified type name for which the type name is
4487 /// DependentNameType represents a class of dependent types that involve a
4488 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4489 /// name of a type. The DependentNameType may start with a "typename" (for a
4490 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4491 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4492 /// know that we must be referring to a type, e.g., in a base class specifier).
4493 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4494 /// mode, this type is used with non-dependent names to delay name lookup until
4496 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4498 /// \brief The nested name specifier containing the qualifier.
4499 NestedNameSpecifier *NNS;
4501 /// \brief The type that this typename specifier refers to.
4502 const IdentifierInfo *Name;
4504 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4505 const IdentifierInfo *Name, QualType CanonType)
4506 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4507 /*InstantiationDependent=*/true,
4508 /*VariablyModified=*/false,
4509 NNS->containsUnexpandedParameterPack()),
4510 NNS(NNS), Name(Name) {}
4512 friend class ASTContext; // ASTContext creates these
4515 /// Retrieve the qualification on this type.
4516 NestedNameSpecifier *getQualifier() const { return NNS; }
4518 /// Retrieve the type named by the typename specifier as an identifier.
4520 /// This routine will return a non-NULL identifier pointer when the
4521 /// form of the original typename was terminated by an identifier,
4522 /// e.g., "typename T::type".
4523 const IdentifierInfo *getIdentifier() const {
4527 bool isSugared() const { return false; }
4528 QualType desugar() const { return QualType(this, 0); }
4530 void Profile(llvm::FoldingSetNodeID &ID) {
4531 Profile(ID, getKeyword(), NNS, Name);
4534 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4535 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4536 ID.AddInteger(Keyword);
4538 ID.AddPointer(Name);
4541 static bool classof(const Type *T) {
4542 return T->getTypeClass() == DependentName;
4546 /// Represents a template specialization type whose template cannot be
4548 /// A<T>::template B<T>
4549 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4550 : public TypeWithKeyword,
4551 public llvm::FoldingSetNode {
4553 /// The nested name specifier containing the qualifier.
4554 NestedNameSpecifier *NNS;
4556 /// The identifier of the template.
4557 const IdentifierInfo *Name;
4559 /// \brief The number of template arguments named in this class template
4563 const TemplateArgument *getArgBuffer() const {
4564 return reinterpret_cast<const TemplateArgument*>(this+1);
4566 TemplateArgument *getArgBuffer() {
4567 return reinterpret_cast<TemplateArgument*>(this+1);
4570 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4571 NestedNameSpecifier *NNS,
4572 const IdentifierInfo *Name,
4573 ArrayRef<TemplateArgument> Args,
4576 friend class ASTContext; // ASTContext creates these
4579 NestedNameSpecifier *getQualifier() const { return NNS; }
4580 const IdentifierInfo *getIdentifier() const { return Name; }
4582 /// \brief Retrieve the template arguments.
4583 const TemplateArgument *getArgs() const {
4584 return getArgBuffer();
4587 /// \brief Retrieve the number of template arguments.
4588 unsigned getNumArgs() const { return NumArgs; }
4590 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4592 ArrayRef<TemplateArgument> template_arguments() const {
4593 return {getArgs(), NumArgs};
4596 typedef const TemplateArgument * iterator;
4597 iterator begin() const { return getArgs(); }
4598 iterator end() const; // inline in TemplateBase.h
4600 bool isSugared() const { return false; }
4601 QualType desugar() const { return QualType(this, 0); }
4603 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4604 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
4607 static void Profile(llvm::FoldingSetNodeID &ID,
4608 const ASTContext &Context,
4609 ElaboratedTypeKeyword Keyword,
4610 NestedNameSpecifier *Qualifier,
4611 const IdentifierInfo *Name,
4612 ArrayRef<TemplateArgument> Args);
4614 static bool classof(const Type *T) {
4615 return T->getTypeClass() == DependentTemplateSpecialization;
4619 /// \brief Represents a pack expansion of types.
4621 /// Pack expansions are part of C++11 variadic templates. A pack
4622 /// expansion contains a pattern, which itself contains one or more
4623 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4624 /// produces a series of types, each instantiated from the pattern of
4625 /// the expansion, where the Ith instantiation of the pattern uses the
4626 /// Ith arguments bound to each of the unexpanded parameter packs. The
4627 /// pack expansion is considered to "expand" these unexpanded
4628 /// parameter packs.
4631 /// template<typename ...Types> struct tuple;
4633 /// template<typename ...Types>
4634 /// struct tuple_of_references {
4635 /// typedef tuple<Types&...> type;
4639 /// Here, the pack expansion \c Types&... is represented via a
4640 /// PackExpansionType whose pattern is Types&.
4641 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4642 /// \brief The pattern of the pack expansion.
4645 /// \brief The number of expansions that this pack expansion will
4646 /// generate when substituted (+1), or indicates that
4648 /// This field will only have a non-zero value when some of the parameter
4649 /// packs that occur within the pattern have been substituted but others have
4651 unsigned NumExpansions;
4653 PackExpansionType(QualType Pattern, QualType Canon,
4654 Optional<unsigned> NumExpansions)
4655 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4656 /*InstantiationDependent=*/true,
4657 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4658 /*ContainsUnexpandedParameterPack=*/false),
4660 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4662 friend class ASTContext; // ASTContext creates these
4665 /// \brief Retrieve the pattern of this pack expansion, which is the
4666 /// type that will be repeatedly instantiated when instantiating the
4667 /// pack expansion itself.
4668 QualType getPattern() const { return Pattern; }
4670 /// \brief Retrieve the number of expansions that this pack expansion will
4671 /// generate, if known.
4672 Optional<unsigned> getNumExpansions() const {
4674 return NumExpansions - 1;
4679 bool isSugared() const { return !Pattern->isDependentType(); }
4680 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4682 void Profile(llvm::FoldingSetNodeID &ID) {
4683 Profile(ID, getPattern(), getNumExpansions());
4686 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4687 Optional<unsigned> NumExpansions) {
4688 ID.AddPointer(Pattern.getAsOpaquePtr());
4689 ID.AddBoolean(NumExpansions.hasValue());
4691 ID.AddInteger(*NumExpansions);
4694 static bool classof(const Type *T) {
4695 return T->getTypeClass() == PackExpansion;
4699 /// Represents a class type in Objective C.
4701 /// Every Objective C type is a combination of a base type, a set of
4702 /// type arguments (optional, for parameterized classes) and a list of
4705 /// Given the following declarations:
4711 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4712 /// with base C and no protocols.
4714 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
4715 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
4717 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
4718 /// and protocol list [P].
4720 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4721 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4722 /// and no protocols.
4724 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4725 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4726 /// this should get its own sugar class to better represent the source.
4727 class ObjCObjectType : public Type {
4728 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
4729 // after the ObjCObjectPointerType node.
4730 // ObjCObjectType.NumProtocols - the number of protocols stored
4731 // after the type arguments of ObjCObjectPointerType node.
4733 // These protocols are those written directly on the type. If
4734 // protocol qualifiers ever become additive, the iterators will need
4735 // to get kindof complicated.
4737 // In the canonical object type, these are sorted alphabetically
4740 /// Either a BuiltinType or an InterfaceType or sugar for either.
4743 /// Cached superclass type.
4744 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
4745 CachedSuperClassType;
4747 ObjCProtocolDecl * const *getProtocolStorage() const {
4748 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4751 QualType *getTypeArgStorage();
4752 const QualType *getTypeArgStorage() const {
4753 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
4756 ObjCProtocolDecl **getProtocolStorage();
4759 ObjCObjectType(QualType Canonical, QualType Base,
4760 ArrayRef<QualType> typeArgs,
4761 ArrayRef<ObjCProtocolDecl *> protocols,
4764 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4765 ObjCObjectType(enum Nonce_ObjCInterface)
4766 : Type(ObjCInterface, QualType(), false, false, false, false),
4767 BaseType(QualType(this_(), 0)) {
4768 ObjCObjectTypeBits.NumProtocols = 0;
4769 ObjCObjectTypeBits.NumTypeArgs = 0;
4770 ObjCObjectTypeBits.IsKindOf = 0;
4773 void computeSuperClassTypeSlow() const;
4776 /// Gets the base type of this object type. This is always (possibly
4777 /// sugar for) one of:
4778 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4779 /// user, which is a typedef for an ObjCObjectPointerType)
4780 /// - the 'Class' builtin type (same caveat)
4781 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4782 QualType getBaseType() const { return BaseType; }
4784 bool isObjCId() const {
4785 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4787 bool isObjCClass() const {
4788 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4790 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4791 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4792 bool isObjCUnqualifiedIdOrClass() const {
4793 if (!qual_empty()) return false;
4794 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4795 return T->getKind() == BuiltinType::ObjCId ||
4796 T->getKind() == BuiltinType::ObjCClass;
4799 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4800 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4802 /// Gets the interface declaration for this object type, if the base type
4803 /// really is an interface.
4804 ObjCInterfaceDecl *getInterface() const;
4806 /// Determine whether this object type is "specialized", meaning
4807 /// that it has type arguments.
4808 bool isSpecialized() const;
4810 /// Determine whether this object type was written with type arguments.
4811 bool isSpecializedAsWritten() const {
4812 return ObjCObjectTypeBits.NumTypeArgs > 0;
4815 /// Determine whether this object type is "unspecialized", meaning
4816 /// that it has no type arguments.
4817 bool isUnspecialized() const { return !isSpecialized(); }
4819 /// Determine whether this object type is "unspecialized" as
4820 /// written, meaning that it has no type arguments.
4821 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4823 /// Retrieve the type arguments of this object type (semantically).
4824 ArrayRef<QualType> getTypeArgs() const;
4826 /// Retrieve the type arguments of this object type as they were
4828 ArrayRef<QualType> getTypeArgsAsWritten() const {
4829 return llvm::makeArrayRef(getTypeArgStorage(),
4830 ObjCObjectTypeBits.NumTypeArgs);
4833 typedef ObjCProtocolDecl * const *qual_iterator;
4834 typedef llvm::iterator_range<qual_iterator> qual_range;
4836 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4837 qual_iterator qual_begin() const { return getProtocolStorage(); }
4838 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4840 bool qual_empty() const { return getNumProtocols() == 0; }
4842 /// Return the number of qualifying protocols in this interface type,
4843 /// or 0 if there are none.
4844 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4846 /// Fetch a protocol by index.
4847 ObjCProtocolDecl *getProtocol(unsigned I) const {
4848 assert(I < getNumProtocols() && "Out-of-range protocol access");
4849 return qual_begin()[I];
4852 /// Retrieve all of the protocol qualifiers.
4853 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
4854 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
4857 /// Whether this is a "__kindof" type as written.
4858 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
4860 /// Whether this ia a "__kindof" type (semantically).
4861 bool isKindOfType() const;
4863 /// Retrieve the type of the superclass of this object type.
4865 /// This operation substitutes any type arguments into the
4866 /// superclass of the current class type, potentially producing a
4867 /// specialization of the superclass type. Produces a null type if
4868 /// there is no superclass.
4869 QualType getSuperClassType() const {
4870 if (!CachedSuperClassType.getInt())
4871 computeSuperClassTypeSlow();
4873 assert(CachedSuperClassType.getInt() && "Superclass not set?");
4874 return QualType(CachedSuperClassType.getPointer(), 0);
4877 /// Strip off the Objective-C "kindof" type and (with it) any
4878 /// protocol qualifiers.
4879 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
4881 bool isSugared() const { return false; }
4882 QualType desugar() const { return QualType(this, 0); }
4884 static bool classof(const Type *T) {
4885 return T->getTypeClass() == ObjCObject ||
4886 T->getTypeClass() == ObjCInterface;
4890 /// A class providing a concrete implementation
4891 /// of ObjCObjectType, so as to not increase the footprint of
4892 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4893 /// system should not reference this type.
4894 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4895 friend class ASTContext;
4897 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4898 // will need to be modified.
4900 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4901 ArrayRef<QualType> typeArgs,
4902 ArrayRef<ObjCProtocolDecl *> protocols,
4904 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
4907 void Profile(llvm::FoldingSetNodeID &ID);
4908 static void Profile(llvm::FoldingSetNodeID &ID,
4910 ArrayRef<QualType> typeArgs,
4911 ArrayRef<ObjCProtocolDecl *> protocols,
4915 inline QualType *ObjCObjectType::getTypeArgStorage() {
4916 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
4919 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4920 return reinterpret_cast<ObjCProtocolDecl**>(
4921 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
4924 /// Interfaces are the core concept in Objective-C for object oriented design.
4925 /// They basically correspond to C++ classes. There are two kinds of interface
4926 /// types: normal interfaces like `NSString`, and qualified interfaces, which
4927 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
4929 /// ObjCInterfaceType guarantees the following properties when considered
4930 /// as a subtype of its superclass, ObjCObjectType:
4931 /// - There are no protocol qualifiers. To reinforce this, code which
4932 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4933 /// fail to compile.
4934 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4935 /// T->getBaseType() == QualType(T, 0).
4936 class ObjCInterfaceType : public ObjCObjectType {
4937 mutable ObjCInterfaceDecl *Decl;
4939 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4940 : ObjCObjectType(Nonce_ObjCInterface),
4941 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4942 friend class ASTContext; // ASTContext creates these.
4943 friend class ASTReader;
4944 friend class ObjCInterfaceDecl;
4947 /// Get the declaration of this interface.
4948 ObjCInterfaceDecl *getDecl() const { return Decl; }
4950 bool isSugared() const { return false; }
4951 QualType desugar() const { return QualType(this, 0); }
4953 static bool classof(const Type *T) {
4954 return T->getTypeClass() == ObjCInterface;
4957 // Nonsense to "hide" certain members of ObjCObjectType within this
4958 // class. People asking for protocols on an ObjCInterfaceType are
4959 // not going to get what they want: ObjCInterfaceTypes are
4960 // guaranteed to have no protocols.
4970 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4971 QualType baseType = getBaseType();
4972 while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
4973 if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
4974 return T->getDecl();
4976 baseType = ObjT->getBaseType();
4982 /// Represents a pointer to an Objective C object.
4984 /// These are constructed from pointer declarators when the pointee type is
4985 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
4986 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
4987 /// and 'Class<P>' are translated into these.
4989 /// Pointers to pointers to Objective C objects are still PointerTypes;
4990 /// only the first level of pointer gets it own type implementation.
4991 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4992 QualType PointeeType;
4994 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4995 : Type(ObjCObjectPointer, Canonical,
4996 Pointee->isDependentType(),
4997 Pointee->isInstantiationDependentType(),
4998 Pointee->isVariablyModifiedType(),
4999 Pointee->containsUnexpandedParameterPack()),
5000 PointeeType(Pointee) {}
5001 friend class ASTContext; // ASTContext creates these.
5004 /// Gets the type pointed to by this ObjC pointer.
5005 /// The result will always be an ObjCObjectType or sugar thereof.
5006 QualType getPointeeType() const { return PointeeType; }
5008 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5010 /// This method is equivalent to getPointeeType() except that
5011 /// it discards any typedefs (or other sugar) between this
5012 /// type and the "outermost" object type. So for:
5014 /// \@class A; \@protocol P; \@protocol Q;
5015 /// typedef A<P> AP;
5017 /// typedef A1<P> A1P;
5018 /// typedef A1P<Q> A1PQ;
5020 /// For 'A*', getObjectType() will return 'A'.
5021 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5022 /// For 'AP*', getObjectType() will return 'A<P>'.
5023 /// For 'A1*', getObjectType() will return 'A'.
5024 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5025 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5026 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5027 /// adding protocols to a protocol-qualified base discards the
5028 /// old qualifiers (for now). But if it didn't, getObjectType()
5029 /// would return 'A1P<Q>' (and we'd have to make iterating over
5030 /// qualifiers more complicated).
5031 const ObjCObjectType *getObjectType() const {
5032 return PointeeType->castAs<ObjCObjectType>();
5035 /// If this pointer points to an Objective C
5036 /// \@interface type, gets the type for that interface. Any protocol
5037 /// qualifiers on the interface are ignored.
5039 /// \return null if the base type for this pointer is 'id' or 'Class'
5040 const ObjCInterfaceType *getInterfaceType() const;
5042 /// If this pointer points to an Objective \@interface
5043 /// type, gets the declaration for that interface.
5045 /// \return null if the base type for this pointer is 'id' or 'Class'
5046 ObjCInterfaceDecl *getInterfaceDecl() const {
5047 return getObjectType()->getInterface();
5050 /// True if this is equivalent to the 'id' type, i.e. if
5051 /// its object type is the primitive 'id' type with no protocols.
5052 bool isObjCIdType() const {
5053 return getObjectType()->isObjCUnqualifiedId();
5056 /// True if this is equivalent to the 'Class' type,
5057 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5058 bool isObjCClassType() const {
5059 return getObjectType()->isObjCUnqualifiedClass();
5062 /// True if this is equivalent to the 'id' or 'Class' type,
5063 bool isObjCIdOrClassType() const {
5064 return getObjectType()->isObjCUnqualifiedIdOrClass();
5067 /// True if this is equivalent to 'id<P>' for some non-empty set of
5069 bool isObjCQualifiedIdType() const {
5070 return getObjectType()->isObjCQualifiedId();
5073 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5075 bool isObjCQualifiedClassType() const {
5076 return getObjectType()->isObjCQualifiedClass();
5079 /// Whether this is a "__kindof" type.
5080 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5082 /// Whether this type is specialized, meaning that it has type arguments.
5083 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5085 /// Whether this type is specialized, meaning that it has type arguments.
5086 bool isSpecializedAsWritten() const {
5087 return getObjectType()->isSpecializedAsWritten();
5090 /// Whether this type is unspecialized, meaning that is has no type arguments.
5091 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5093 /// Determine whether this object type is "unspecialized" as
5094 /// written, meaning that it has no type arguments.
5095 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5097 /// Retrieve the type arguments for this type.
5098 ArrayRef<QualType> getTypeArgs() const {
5099 return getObjectType()->getTypeArgs();
5102 /// Retrieve the type arguments for this type.
5103 ArrayRef<QualType> getTypeArgsAsWritten() const {
5104 return getObjectType()->getTypeArgsAsWritten();
5107 /// An iterator over the qualifiers on the object type. Provided
5108 /// for convenience. This will always iterate over the full set of
5109 /// protocols on a type, not just those provided directly.
5110 typedef ObjCObjectType::qual_iterator qual_iterator;
5111 typedef llvm::iterator_range<qual_iterator> qual_range;
5113 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5114 qual_iterator qual_begin() const {
5115 return getObjectType()->qual_begin();
5117 qual_iterator qual_end() const {
5118 return getObjectType()->qual_end();
5120 bool qual_empty() const { return getObjectType()->qual_empty(); }
5122 /// Return the number of qualifying protocols on the object type.
5123 unsigned getNumProtocols() const {
5124 return getObjectType()->getNumProtocols();
5127 /// Retrieve a qualifying protocol by index on the object type.
5128 ObjCProtocolDecl *getProtocol(unsigned I) const {
5129 return getObjectType()->getProtocol(I);
5132 bool isSugared() const { return false; }
5133 QualType desugar() const { return QualType(this, 0); }
5135 /// Retrieve the type of the superclass of this object pointer type.
5137 /// This operation substitutes any type arguments into the
5138 /// superclass of the current class type, potentially producing a
5139 /// pointer to a specialization of the superclass type. Produces a
5140 /// null type if there is no superclass.
5141 QualType getSuperClassType() const;
5143 /// Strip off the Objective-C "kindof" type and (with it) any
5144 /// protocol qualifiers.
5145 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5146 const ASTContext &ctx) const;
5148 void Profile(llvm::FoldingSetNodeID &ID) {
5149 Profile(ID, getPointeeType());
5151 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5152 ID.AddPointer(T.getAsOpaquePtr());
5154 static bool classof(const Type *T) {
5155 return T->getTypeClass() == ObjCObjectPointer;
5159 class AtomicType : public Type, public llvm::FoldingSetNode {
5162 AtomicType(QualType ValTy, QualType Canonical)
5163 : Type(Atomic, Canonical, ValTy->isDependentType(),
5164 ValTy->isInstantiationDependentType(),
5165 ValTy->isVariablyModifiedType(),
5166 ValTy->containsUnexpandedParameterPack()),
5168 friend class ASTContext; // ASTContext creates these.
5171 /// Gets the type contained by this atomic type, i.e.
5172 /// the type returned by performing an atomic load of this atomic type.
5173 QualType getValueType() const { return ValueType; }
5175 bool isSugared() const { return false; }
5176 QualType desugar() const { return QualType(this, 0); }
5178 void Profile(llvm::FoldingSetNodeID &ID) {
5179 Profile(ID, getValueType());
5181 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5182 ID.AddPointer(T.getAsOpaquePtr());
5184 static bool classof(const Type *T) {
5185 return T->getTypeClass() == Atomic;
5189 /// PipeType - OpenCL20.
5190 class PipeType : public Type, public llvm::FoldingSetNode {
5191 QualType ElementType;
5193 PipeType(QualType elemType, QualType CanonicalPtr) :
5194 Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5195 elemType->isInstantiationDependentType(),
5196 elemType->isVariablyModifiedType(),
5197 elemType->containsUnexpandedParameterPack()),
5198 ElementType(elemType) {}
5199 friend class ASTContext; // ASTContext creates these.
5203 QualType getElementType() const { return ElementType; }
5205 bool isSugared() const { return false; }
5207 QualType desugar() const { return QualType(this, 0); }
5209 void Profile(llvm::FoldingSetNodeID &ID) {
5210 Profile(ID, getElementType());
5213 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5214 ID.AddPointer(T.getAsOpaquePtr());
5218 static bool classof(const Type *T) {
5219 return T->getTypeClass() == Pipe;
5224 /// A qualifier set is used to build a set of qualifiers.
5225 class QualifierCollector : public Qualifiers {
5227 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5229 /// Collect any qualifiers on the given type and return an
5230 /// unqualified type. The qualifiers are assumed to be consistent
5231 /// with those already in the type.
5232 const Type *strip(QualType type) {
5233 addFastQualifiers(type.getLocalFastQualifiers());
5234 if (!type.hasLocalNonFastQualifiers())
5235 return type.getTypePtrUnsafe();
5237 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5238 addConsistentQualifiers(extQuals->getQualifiers());
5239 return extQuals->getBaseType();
5242 /// Apply the collected qualifiers to the given type.
5243 QualType apply(const ASTContext &Context, QualType QT) const;
5245 /// Apply the collected qualifiers to the given type.
5246 QualType apply(const ASTContext &Context, const Type* T) const;
5250 // Inline function definitions.
5252 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5253 SplitQualType desugar =
5254 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5255 desugar.Quals.addConsistentQualifiers(Quals);
5259 inline const Type *QualType::getTypePtr() const {
5260 return getCommonPtr()->BaseType;
5263 inline const Type *QualType::getTypePtrOrNull() const {
5264 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5267 inline SplitQualType QualType::split() const {
5268 if (!hasLocalNonFastQualifiers())
5269 return SplitQualType(getTypePtrUnsafe(),
5270 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5272 const ExtQuals *eq = getExtQualsUnsafe();
5273 Qualifiers qs = eq->getQualifiers();
5274 qs.addFastQualifiers(getLocalFastQualifiers());
5275 return SplitQualType(eq->getBaseType(), qs);
5278 inline Qualifiers QualType::getLocalQualifiers() const {
5280 if (hasLocalNonFastQualifiers())
5281 Quals = getExtQualsUnsafe()->getQualifiers();
5282 Quals.addFastQualifiers(getLocalFastQualifiers());
5286 inline Qualifiers QualType::getQualifiers() const {
5287 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5288 quals.addFastQualifiers(getLocalFastQualifiers());
5292 inline unsigned QualType::getCVRQualifiers() const {
5293 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5294 cvr |= getLocalCVRQualifiers();
5298 inline QualType QualType::getCanonicalType() const {
5299 QualType canon = getCommonPtr()->CanonicalType;
5300 return canon.withFastQualifiers(getLocalFastQualifiers());
5303 inline bool QualType::isCanonical() const {
5304 return getTypePtr()->isCanonicalUnqualified();
5307 inline bool QualType::isCanonicalAsParam() const {
5308 if (!isCanonical()) return false;
5309 if (hasLocalQualifiers()) return false;
5311 const Type *T = getTypePtr();
5312 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5315 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5318 inline bool QualType::isConstQualified() const {
5319 return isLocalConstQualified() ||
5320 getCommonPtr()->CanonicalType.isLocalConstQualified();
5323 inline bool QualType::isRestrictQualified() const {
5324 return isLocalRestrictQualified() ||
5325 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5329 inline bool QualType::isVolatileQualified() const {
5330 return isLocalVolatileQualified() ||
5331 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5334 inline bool QualType::hasQualifiers() const {
5335 return hasLocalQualifiers() ||
5336 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5339 inline QualType QualType::getUnqualifiedType() const {
5340 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5341 return QualType(getTypePtr(), 0);
5343 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5346 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5347 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5350 return getSplitUnqualifiedTypeImpl(*this);
5353 inline void QualType::removeLocalConst() {
5354 removeLocalFastQualifiers(Qualifiers::Const);
5357 inline void QualType::removeLocalRestrict() {
5358 removeLocalFastQualifiers(Qualifiers::Restrict);
5361 inline void QualType::removeLocalVolatile() {
5362 removeLocalFastQualifiers(Qualifiers::Volatile);
5365 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5366 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5367 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5368 "Fast bits differ from CVR bits!");
5370 // Fast path: we don't need to touch the slow qualifiers.
5371 removeLocalFastQualifiers(Mask);
5374 /// Return the address space of this type.
5375 inline unsigned QualType::getAddressSpace() const {
5376 return getQualifiers().getAddressSpace();
5379 /// Return the gc attribute of this type.
5380 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5381 return getQualifiers().getObjCGCAttr();
5384 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5385 if (const PointerType *PT = t.getAs<PointerType>()) {
5386 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5387 return FT->getExtInfo();
5388 } else if (const FunctionType *FT = t.getAs<FunctionType>())
5389 return FT->getExtInfo();
5391 return FunctionType::ExtInfo();
5394 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5395 return getFunctionExtInfo(*t);
5398 /// Determine whether this type is more
5399 /// qualified than the Other type. For example, "const volatile int"
5400 /// is more qualified than "const int", "volatile int", and
5401 /// "int". However, it is not more qualified than "const volatile
5403 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5404 Qualifiers MyQuals = getQualifiers();
5405 Qualifiers OtherQuals = other.getQualifiers();
5406 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
5409 /// Determine whether this type is at last
5410 /// as qualified as the Other type. For example, "const volatile
5411 /// int" is at least as qualified as "const int", "volatile int",
5412 /// "int", and "const volatile int".
5413 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5414 Qualifiers OtherQuals = other.getQualifiers();
5416 // Ignore __unaligned qualifier if this type is a void.
5417 if (getUnqualifiedType()->isVoidType())
5418 OtherQuals.removeUnaligned();
5420 return getQualifiers().compatiblyIncludes(OtherQuals);
5423 /// If Type is a reference type (e.g., const
5424 /// int&), returns the type that the reference refers to ("const
5425 /// int"). Otherwise, returns the type itself. This routine is used
5426 /// throughout Sema to implement C++ 5p6:
5428 /// If an expression initially has the type "reference to T" (8.3.2,
5429 /// 8.5.3), the type is adjusted to "T" prior to any further
5430 /// analysis, the expression designates the object or function
5431 /// denoted by the reference, and the expression is an lvalue.
5432 inline QualType QualType::getNonReferenceType() const {
5433 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5434 return RefType->getPointeeType();
5439 inline bool QualType::isCForbiddenLValueType() const {
5440 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5441 getTypePtr()->isFunctionType());
5444 /// Tests whether the type is categorized as a fundamental type.
5446 /// \returns True for types specified in C++0x [basic.fundamental].
5447 inline bool Type::isFundamentalType() const {
5448 return isVoidType() ||
5449 // FIXME: It's really annoying that we don't have an
5450 // 'isArithmeticType()' which agrees with the standard definition.
5451 (isArithmeticType() && !isEnumeralType());
5454 /// Tests whether the type is categorized as a compound type.
5456 /// \returns True for types specified in C++0x [basic.compound].
5457 inline bool Type::isCompoundType() const {
5458 // C++0x [basic.compound]p1:
5459 // Compound types can be constructed in the following ways:
5460 // -- arrays of objects of a given type [...];
5461 return isArrayType() ||
5462 // -- functions, which have parameters of given types [...];
5464 // -- pointers to void or objects or functions [...];
5466 // -- references to objects or functions of a given type. [...]
5467 isReferenceType() ||
5468 // -- classes containing a sequence of objects of various types, [...];
5470 // -- unions, which are classes capable of containing objects of different
5471 // types at different times;
5473 // -- enumerations, which comprise a set of named constant values. [...];
5475 // -- pointers to non-static class members, [...].
5476 isMemberPointerType();
5479 inline bool Type::isFunctionType() const {
5480 return isa<FunctionType>(CanonicalType);
5482 inline bool Type::isPointerType() const {
5483 return isa<PointerType>(CanonicalType);
5485 inline bool Type::isAnyPointerType() const {
5486 return isPointerType() || isObjCObjectPointerType();
5488 inline bool Type::isBlockPointerType() const {
5489 return isa<BlockPointerType>(CanonicalType);
5491 inline bool Type::isReferenceType() const {
5492 return isa<ReferenceType>(CanonicalType);
5494 inline bool Type::isLValueReferenceType() const {
5495 return isa<LValueReferenceType>(CanonicalType);
5497 inline bool Type::isRValueReferenceType() const {
5498 return isa<RValueReferenceType>(CanonicalType);
5500 inline bool Type::isFunctionPointerType() const {
5501 if (const PointerType *T = getAs<PointerType>())
5502 return T->getPointeeType()->isFunctionType();
5506 inline bool Type::isMemberPointerType() const {
5507 return isa<MemberPointerType>(CanonicalType);
5509 inline bool Type::isMemberFunctionPointerType() const {
5510 if (const MemberPointerType* T = getAs<MemberPointerType>())
5511 return T->isMemberFunctionPointer();
5515 inline bool Type::isMemberDataPointerType() const {
5516 if (const MemberPointerType* T = getAs<MemberPointerType>())
5517 return T->isMemberDataPointer();
5521 inline bool Type::isArrayType() const {
5522 return isa<ArrayType>(CanonicalType);
5524 inline bool Type::isConstantArrayType() const {
5525 return isa<ConstantArrayType>(CanonicalType);
5527 inline bool Type::isIncompleteArrayType() const {
5528 return isa<IncompleteArrayType>(CanonicalType);
5530 inline bool Type::isVariableArrayType() const {
5531 return isa<VariableArrayType>(CanonicalType);
5533 inline bool Type::isDependentSizedArrayType() const {
5534 return isa<DependentSizedArrayType>(CanonicalType);
5536 inline bool Type::isBuiltinType() const {
5537 return isa<BuiltinType>(CanonicalType);
5539 inline bool Type::isRecordType() const {
5540 return isa<RecordType>(CanonicalType);
5542 inline bool Type::isEnumeralType() const {
5543 return isa<EnumType>(CanonicalType);
5545 inline bool Type::isAnyComplexType() const {
5546 return isa<ComplexType>(CanonicalType);
5548 inline bool Type::isVectorType() const {
5549 return isa<VectorType>(CanonicalType);
5551 inline bool Type::isExtVectorType() const {
5552 return isa<ExtVectorType>(CanonicalType);
5554 inline bool Type::isObjCObjectPointerType() const {
5555 return isa<ObjCObjectPointerType>(CanonicalType);
5557 inline bool Type::isObjCObjectType() const {
5558 return isa<ObjCObjectType>(CanonicalType);
5560 inline bool Type::isObjCObjectOrInterfaceType() const {
5561 return isa<ObjCInterfaceType>(CanonicalType) ||
5562 isa<ObjCObjectType>(CanonicalType);
5564 inline bool Type::isAtomicType() const {
5565 return isa<AtomicType>(CanonicalType);
5568 inline bool Type::isObjCQualifiedIdType() const {
5569 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5570 return OPT->isObjCQualifiedIdType();
5573 inline bool Type::isObjCQualifiedClassType() const {
5574 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5575 return OPT->isObjCQualifiedClassType();
5578 inline bool Type::isObjCIdType() const {
5579 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5580 return OPT->isObjCIdType();
5583 inline bool Type::isObjCClassType() const {
5584 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5585 return OPT->isObjCClassType();
5588 inline bool Type::isObjCSelType() const {
5589 if (const PointerType *OPT = getAs<PointerType>())
5590 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5593 inline bool Type::isObjCBuiltinType() const {
5594 return isObjCIdType() || isObjCClassType() || isObjCSelType();
5597 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5598 inline bool Type::is##Id##Type() const { \
5599 return isSpecificBuiltinType(BuiltinType::Id); \
5601 #include "clang/Basic/OpenCLImageTypes.def"
5603 inline bool Type::isSamplerT() const {
5604 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5607 inline bool Type::isEventT() const {
5608 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5611 inline bool Type::isClkEventT() const {
5612 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
5615 inline bool Type::isQueueT() const {
5616 return isSpecificBuiltinType(BuiltinType::OCLQueue);
5619 inline bool Type::isNDRangeT() const {
5620 return isSpecificBuiltinType(BuiltinType::OCLNDRange);
5623 inline bool Type::isReserveIDT() const {
5624 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
5627 inline bool Type::isImageType() const {
5628 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
5630 #include "clang/Basic/OpenCLImageTypes.def"
5631 0; // end boolean or operation
5634 inline bool Type::isPipeType() const {
5635 return isa<PipeType>(CanonicalType);
5638 inline bool Type::isOpenCLSpecificType() const {
5639 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
5640 isQueueT() || isNDRangeT() || isReserveIDT() || isPipeType();
5643 inline bool Type::isTemplateTypeParmType() const {
5644 return isa<TemplateTypeParmType>(CanonicalType);
5647 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5648 if (const BuiltinType *BT = getAs<BuiltinType>())
5649 if (BT->getKind() == (BuiltinType::Kind) K)
5654 inline bool Type::isPlaceholderType() const {
5655 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5656 return BT->isPlaceholderType();
5660 inline const BuiltinType *Type::getAsPlaceholderType() const {
5661 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5662 if (BT->isPlaceholderType())
5667 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5668 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5669 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5670 return (BT->getKind() == (BuiltinType::Kind) K);
5674 inline bool Type::isNonOverloadPlaceholderType() const {
5675 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5676 return BT->isNonOverloadPlaceholderType();
5680 inline bool Type::isVoidType() const {
5681 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5682 return BT->getKind() == BuiltinType::Void;
5686 inline bool Type::isHalfType() const {
5687 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5688 return BT->getKind() == BuiltinType::Half;
5689 // FIXME: Should we allow complex __fp16? Probably not.
5693 inline bool Type::isNullPtrType() const {
5694 if (const BuiltinType *BT = getAs<BuiltinType>())
5695 return BT->getKind() == BuiltinType::NullPtr;
5699 extern bool IsEnumDeclComplete(EnumDecl *);
5700 extern bool IsEnumDeclScoped(EnumDecl *);
5702 inline bool Type::isIntegerType() const {
5703 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5704 return BT->getKind() >= BuiltinType::Bool &&
5705 BT->getKind() <= BuiltinType::Int128;
5706 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5707 // Incomplete enum types are not treated as integer types.
5708 // FIXME: In C++, enum types are never integer types.
5709 return IsEnumDeclComplete(ET->getDecl()) &&
5710 !IsEnumDeclScoped(ET->getDecl());
5715 inline bool Type::isScalarType() const {
5716 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5717 return BT->getKind() > BuiltinType::Void &&
5718 BT->getKind() <= BuiltinType::NullPtr;
5719 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5720 // Enums are scalar types, but only if they are defined. Incomplete enums
5721 // are not treated as scalar types.
5722 return IsEnumDeclComplete(ET->getDecl());
5723 return isa<PointerType>(CanonicalType) ||
5724 isa<BlockPointerType>(CanonicalType) ||
5725 isa<MemberPointerType>(CanonicalType) ||
5726 isa<ComplexType>(CanonicalType) ||
5727 isa<ObjCObjectPointerType>(CanonicalType);
5730 inline bool Type::isIntegralOrEnumerationType() const {
5731 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5732 return BT->getKind() >= BuiltinType::Bool &&
5733 BT->getKind() <= BuiltinType::Int128;
5735 // Check for a complete enum type; incomplete enum types are not properly an
5736 // enumeration type in the sense required here.
5737 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5738 return IsEnumDeclComplete(ET->getDecl());
5743 inline bool Type::isBooleanType() const {
5744 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5745 return BT->getKind() == BuiltinType::Bool;
5749 inline bool Type::isUndeducedType() const {
5750 const AutoType *AT = getContainedAutoType();
5751 return AT && !AT->isDeduced();
5754 /// \brief Determines whether this is a type for which one can define
5755 /// an overloaded operator.
5756 inline bool Type::isOverloadableType() const {
5757 return isDependentType() || isRecordType() || isEnumeralType();
5760 /// \brief Determines whether this type can decay to a pointer type.
5761 inline bool Type::canDecayToPointerType() const {
5762 return isFunctionType() || isArrayType();
5765 inline bool Type::hasPointerRepresentation() const {
5766 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5767 isObjCObjectPointerType() || isNullPtrType());
5770 inline bool Type::hasObjCPointerRepresentation() const {
5771 return isObjCObjectPointerType();
5774 inline const Type *Type::getBaseElementTypeUnsafe() const {
5775 const Type *type = this;
5776 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5777 type = arrayType->getElementType().getTypePtr();
5781 inline const Type *Type::getPointeeOrArrayElementType() const {
5782 const Type *type = this;
5783 if (type->isAnyPointerType())
5784 return type->getPointeeType().getTypePtr();
5785 else if (type->isArrayType())
5786 return type->getBaseElementTypeUnsafe();
5790 /// Insertion operator for diagnostics. This allows sending QualType's into a
5791 /// diagnostic with <<.
5792 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5794 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5795 DiagnosticsEngine::ak_qualtype);
5799 /// Insertion operator for partial diagnostics. This allows sending QualType's
5800 /// into a diagnostic with <<.
5801 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5803 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5804 DiagnosticsEngine::ak_qualtype);
5808 // Helper class template that is used by Type::getAs to ensure that one does
5809 // not try to look through a qualified type to get to an array type.
5810 template <typename T, bool isArrayType = (std::is_same<T, ArrayType>::value ||
5811 std::is_base_of<ArrayType, T>::value)>
5812 struct ArrayType_cannot_be_used_with_getAs {};
5814 template<typename T>
5815 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5817 // Member-template getAs<specific type>'.
5818 template <typename T> const T *Type::getAs() const {
5819 ArrayType_cannot_be_used_with_getAs<T> at;
5822 // If this is directly a T type, return it.
5823 if (const T *Ty = dyn_cast<T>(this))
5826 // If the canonical form of this type isn't the right kind, reject it.
5827 if (!isa<T>(CanonicalType))
5830 // If this is a typedef for the type, strip the typedef off without
5831 // losing all typedef information.
5832 return cast<T>(getUnqualifiedDesugaredType());
5835 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5836 // If this is directly an array type, return it.
5837 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5840 // If the canonical form of this type isn't the right kind, reject it.
5841 if (!isa<ArrayType>(CanonicalType))
5844 // If this is a typedef for the type, strip the typedef off without
5845 // losing all typedef information.
5846 return cast<ArrayType>(getUnqualifiedDesugaredType());
5849 template <typename T> const T *Type::castAs() const {
5850 ArrayType_cannot_be_used_with_getAs<T> at;
5853 if (const T *ty = dyn_cast<T>(this)) return ty;
5854 assert(isa<T>(CanonicalType));
5855 return cast<T>(getUnqualifiedDesugaredType());
5858 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5859 assert(isa<ArrayType>(CanonicalType));
5860 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5861 return cast<ArrayType>(getUnqualifiedDesugaredType());
5864 } // end namespace clang