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 /// * Embedded C (TR18037): address spaces
115 /// * Objective C: the GC attributes (none, weak, or strong)
118 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
122 CVRMask = Const | Volatile | Restrict
132 /// There is no lifetime qualification on this type.
135 /// This object can be modified without requiring retains or
139 /// Assigning into this object requires the old value to be
140 /// released and the new value to be retained. The timing of the
141 /// release of the old value is inexact: it may be moved to
142 /// immediately after the last known point where the value is
146 /// Reading or writing from this object requires a barrier call.
149 /// Assigning into this object requires a lifetime extension.
154 /// The maximum supported address space number.
155 /// 24 bits should be enough for anyone.
156 MaxAddressSpace = 0xffffffu,
158 /// The width of the "fast" qualifier mask.
161 /// The fast qualifier mask.
162 FastMask = (1 << FastWidth) - 1
165 Qualifiers() : Mask(0) {}
167 /// Returns the common set of qualifiers while removing them from
169 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
170 // If both are only CVR-qualified, bit operations are sufficient.
171 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
173 Q.Mask = L.Mask & R.Mask;
180 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
181 Q.addCVRQualifiers(CommonCRV);
182 L.removeCVRQualifiers(CommonCRV);
183 R.removeCVRQualifiers(CommonCRV);
185 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
186 Q.setObjCGCAttr(L.getObjCGCAttr());
187 L.removeObjCGCAttr();
188 R.removeObjCGCAttr();
191 if (L.getObjCLifetime() == R.getObjCLifetime()) {
192 Q.setObjCLifetime(L.getObjCLifetime());
193 L.removeObjCLifetime();
194 R.removeObjCLifetime();
197 if (L.getAddressSpace() == R.getAddressSpace()) {
198 Q.setAddressSpace(L.getAddressSpace());
199 L.removeAddressSpace();
200 R.removeAddressSpace();
205 static Qualifiers fromFastMask(unsigned Mask) {
207 Qs.addFastQualifiers(Mask);
211 static Qualifiers fromCVRMask(unsigned CVR) {
213 Qs.addCVRQualifiers(CVR);
217 // Deserialize qualifiers from an opaque representation.
218 static Qualifiers fromOpaqueValue(unsigned opaque) {
224 // Serialize these qualifiers into an opaque representation.
225 unsigned getAsOpaqueValue() const {
229 bool hasConst() const { return Mask & Const; }
230 void setConst(bool flag) {
231 Mask = (Mask & ~Const) | (flag ? Const : 0);
233 void removeConst() { Mask &= ~Const; }
234 void addConst() { Mask |= Const; }
236 bool hasVolatile() const { return Mask & Volatile; }
237 void setVolatile(bool flag) {
238 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
240 void removeVolatile() { Mask &= ~Volatile; }
241 void addVolatile() { Mask |= Volatile; }
243 bool hasRestrict() const { return Mask & Restrict; }
244 void setRestrict(bool flag) {
245 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
247 void removeRestrict() { Mask &= ~Restrict; }
248 void addRestrict() { Mask |= Restrict; }
250 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
251 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
252 void setCVRQualifiers(unsigned mask) {
253 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
254 Mask = (Mask & ~CVRMask) | mask;
256 void removeCVRQualifiers(unsigned mask) {
257 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
260 void removeCVRQualifiers() {
261 removeCVRQualifiers(CVRMask);
263 void addCVRQualifiers(unsigned mask) {
264 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
268 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
269 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
270 void setObjCGCAttr(GC type) {
271 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
273 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
274 void addObjCGCAttr(GC type) {
278 Qualifiers withoutObjCGCAttr() const {
279 Qualifiers qs = *this;
280 qs.removeObjCGCAttr();
283 Qualifiers withoutObjCLifetime() const {
284 Qualifiers qs = *this;
285 qs.removeObjCLifetime();
289 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
290 ObjCLifetime getObjCLifetime() const {
291 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
293 void setObjCLifetime(ObjCLifetime type) {
294 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
296 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
297 void addObjCLifetime(ObjCLifetime type) {
299 assert(!hasObjCLifetime());
300 Mask |= (type << LifetimeShift);
303 /// True if the lifetime is neither None or ExplicitNone.
304 bool hasNonTrivialObjCLifetime() const {
305 ObjCLifetime lifetime = getObjCLifetime();
306 return (lifetime > OCL_ExplicitNone);
309 /// True if the lifetime is either strong or weak.
310 bool hasStrongOrWeakObjCLifetime() const {
311 ObjCLifetime lifetime = getObjCLifetime();
312 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
315 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
316 unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
317 void setAddressSpace(unsigned space) {
318 assert(space <= MaxAddressSpace);
319 Mask = (Mask & ~AddressSpaceMask)
320 | (((uint32_t) space) << AddressSpaceShift);
322 void removeAddressSpace() { setAddressSpace(0); }
323 void addAddressSpace(unsigned space) {
325 setAddressSpace(space);
328 // Fast qualifiers are those that can be allocated directly
329 // on a QualType object.
330 bool hasFastQualifiers() const { return getFastQualifiers(); }
331 unsigned getFastQualifiers() const { return Mask & FastMask; }
332 void setFastQualifiers(unsigned mask) {
333 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
334 Mask = (Mask & ~FastMask) | mask;
336 void removeFastQualifiers(unsigned mask) {
337 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
340 void removeFastQualifiers() {
341 removeFastQualifiers(FastMask);
343 void addFastQualifiers(unsigned mask) {
344 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
348 /// Return true if the set contains any qualifiers which require an ExtQuals
349 /// node to be allocated.
350 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
351 Qualifiers getNonFastQualifiers() const {
352 Qualifiers Quals = *this;
353 Quals.setFastQualifiers(0);
357 /// Return true if the set contains any qualifiers.
358 bool hasQualifiers() const { return Mask; }
359 bool empty() const { return !Mask; }
361 /// Add the qualifiers from the given set to this set.
362 void addQualifiers(Qualifiers Q) {
363 // If the other set doesn't have any non-boolean qualifiers, just
365 if (!(Q.Mask & ~CVRMask))
368 Mask |= (Q.Mask & CVRMask);
369 if (Q.hasAddressSpace())
370 addAddressSpace(Q.getAddressSpace());
371 if (Q.hasObjCGCAttr())
372 addObjCGCAttr(Q.getObjCGCAttr());
373 if (Q.hasObjCLifetime())
374 addObjCLifetime(Q.getObjCLifetime());
378 /// \brief Remove the qualifiers from the given set from this set.
379 void removeQualifiers(Qualifiers Q) {
380 // If the other set doesn't have any non-boolean qualifiers, just
381 // bit-and the inverse in.
382 if (!(Q.Mask & ~CVRMask))
385 Mask &= ~(Q.Mask & CVRMask);
386 if (getObjCGCAttr() == Q.getObjCGCAttr())
388 if (getObjCLifetime() == Q.getObjCLifetime())
389 removeObjCLifetime();
390 if (getAddressSpace() == Q.getAddressSpace())
391 removeAddressSpace();
395 /// Add the qualifiers from the given set to this set, given that
396 /// they don't conflict.
397 void addConsistentQualifiers(Qualifiers qs) {
398 assert(getAddressSpace() == qs.getAddressSpace() ||
399 !hasAddressSpace() || !qs.hasAddressSpace());
400 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
401 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
402 assert(getObjCLifetime() == qs.getObjCLifetime() ||
403 !hasObjCLifetime() || !qs.hasObjCLifetime());
407 /// Returns true if this address space is a superset of the other one.
408 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
409 /// overlapping address spaces.
411 /// every address space is a superset of itself.
413 /// __generic is a superset of any address space except for __constant.
414 bool isAddressSpaceSupersetOf(Qualifiers other) const {
416 // Address spaces must match exactly.
417 getAddressSpace() == other.getAddressSpace() ||
418 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
419 // for __constant can be used as __generic.
420 (getAddressSpace() == LangAS::opencl_generic &&
421 other.getAddressSpace() != LangAS::opencl_constant);
424 /// Determines if these qualifiers compatibly include another set.
425 /// Generally this answers the question of whether an object with the other
426 /// qualifiers can be safely used as an object with these qualifiers.
427 bool compatiblyIncludes(Qualifiers other) const {
428 return isAddressSpaceSupersetOf(other) &&
429 // ObjC GC qualifiers can match, be added, or be removed, but can't
431 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
432 !other.hasObjCGCAttr()) &&
433 // ObjC lifetime qualifiers must match exactly.
434 getObjCLifetime() == other.getObjCLifetime() &&
435 // CVR qualifiers may subset.
436 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
439 /// \brief Determines if these qualifiers compatibly include another set of
440 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
442 /// One set of Objective-C lifetime qualifiers compatibly includes the other
443 /// if the lifetime qualifiers match, or if both are non-__weak and the
444 /// including set also contains the 'const' qualifier, or both are non-__weak
445 /// and one is None (which can only happen in non-ARC modes).
446 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
447 if (getObjCLifetime() == other.getObjCLifetime())
450 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
453 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
459 /// \brief Determine whether this set of qualifiers is a strict superset of
460 /// another set of qualifiers, not considering qualifier compatibility.
461 bool isStrictSupersetOf(Qualifiers Other) const;
463 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
464 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
466 explicit operator bool() const { return hasQualifiers(); }
468 Qualifiers &operator+=(Qualifiers R) {
473 // Union two qualifier sets. If an enumerated qualifier appears
474 // in both sets, use the one from the right.
475 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
480 Qualifiers &operator-=(Qualifiers R) {
485 /// \brief Compute the difference between two qualifier sets.
486 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
491 std::string getAsString() const;
492 std::string getAsString(const PrintingPolicy &Policy) const;
494 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
495 void print(raw_ostream &OS, const PrintingPolicy &Policy,
496 bool appendSpaceIfNonEmpty = false) const;
498 void Profile(llvm::FoldingSetNodeID &ID) const {
504 // bits: |0 1 2|3 .. 4|5 .. 7|8 ... 31|
505 // |C R V|GCAttr|Lifetime|AddressSpace|
508 static const uint32_t GCAttrMask = 0x18;
509 static const uint32_t GCAttrShift = 3;
510 static const uint32_t LifetimeMask = 0xE0;
511 static const uint32_t LifetimeShift = 5;
512 static const uint32_t AddressSpaceMask = ~(CVRMask|GCAttrMask|LifetimeMask);
513 static const uint32_t AddressSpaceShift = 8;
516 /// A std::pair-like structure for storing a qualified type split
517 /// into its local qualifiers and its locally-unqualified type.
518 struct SplitQualType {
519 /// The locally-unqualified type.
522 /// The local qualifiers.
525 SplitQualType() : Ty(nullptr), Quals() {}
526 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
528 SplitQualType getSingleStepDesugaredType() const; // end of this file
530 // Make std::tie work.
531 std::pair<const Type *,Qualifiers> asPair() const {
532 return std::pair<const Type *, Qualifiers>(Ty, Quals);
535 friend bool operator==(SplitQualType a, SplitQualType b) {
536 return a.Ty == b.Ty && a.Quals == b.Quals;
538 friend bool operator!=(SplitQualType a, SplitQualType b) {
539 return a.Ty != b.Ty || a.Quals != b.Quals;
543 /// The kind of type we are substituting Objective-C type arguments into.
545 /// The kind of substitution affects the replacement of type parameters when
546 /// no concrete type information is provided, e.g., when dealing with an
547 /// unspecialized type.
548 enum class ObjCSubstitutionContext {
549 /// An ordinary type.
551 /// The result type of a method or function.
553 /// The parameter type of a method or function.
555 /// The type of a property.
557 /// The superclass of a type.
561 /// A (possibly-)qualified type.
563 /// For efficiency, we don't store CV-qualified types as nodes on their
564 /// own: instead each reference to a type stores the qualifiers. This
565 /// greatly reduces the number of nodes we need to allocate for types (for
566 /// example we only need one for 'int', 'const int', 'volatile int',
567 /// 'const volatile int', etc).
569 /// As an added efficiency bonus, instead of making this a pair, we
570 /// just store the two bits we care about in the low bits of the
571 /// pointer. To handle the packing/unpacking, we make QualType be a
572 /// simple wrapper class that acts like a smart pointer. A third bit
573 /// indicates whether there are extended qualifiers present, in which
574 /// case the pointer points to a special structure.
576 // Thankfully, these are efficiently composable.
577 llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
578 Qualifiers::FastWidth> Value;
580 const ExtQuals *getExtQualsUnsafe() const {
581 return Value.getPointer().get<const ExtQuals*>();
584 const Type *getTypePtrUnsafe() const {
585 return Value.getPointer().get<const Type*>();
588 const ExtQualsTypeCommonBase *getCommonPtr() const {
589 assert(!isNull() && "Cannot retrieve a NULL type pointer");
590 uintptr_t CommonPtrVal
591 = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
592 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
593 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
596 friend class QualifierCollector;
600 QualType(const Type *Ptr, unsigned Quals)
601 : Value(Ptr, Quals) {}
602 QualType(const ExtQuals *Ptr, unsigned Quals)
603 : Value(Ptr, Quals) {}
605 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
606 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
608 /// Retrieves a pointer to the underlying (unqualified) type.
610 /// This function requires that the type not be NULL. If the type might be
611 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
612 const Type *getTypePtr() const;
614 const Type *getTypePtrOrNull() const;
616 /// Retrieves a pointer to the name of the base type.
617 const IdentifierInfo *getBaseTypeIdentifier() const;
619 /// Divides a QualType into its unqualified type and a set of local
621 SplitQualType split() const;
623 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
624 static QualType getFromOpaquePtr(const void *Ptr) {
626 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
630 const Type &operator*() const {
631 return *getTypePtr();
634 const Type *operator->() const {
638 bool isCanonical() const;
639 bool isCanonicalAsParam() const;
641 /// Return true if this QualType doesn't point to a type yet.
642 bool isNull() const {
643 return Value.getPointer().isNull();
646 /// \brief Determine whether this particular QualType instance has the
647 /// "const" qualifier set, without looking through typedefs that may have
648 /// added "const" at a different level.
649 bool isLocalConstQualified() const {
650 return (getLocalFastQualifiers() & Qualifiers::Const);
653 /// \brief Determine whether this type is const-qualified.
654 bool isConstQualified() const;
656 /// \brief Determine whether this particular QualType instance has the
657 /// "restrict" qualifier set, without looking through typedefs that may have
658 /// added "restrict" at a different level.
659 bool isLocalRestrictQualified() const {
660 return (getLocalFastQualifiers() & Qualifiers::Restrict);
663 /// \brief Determine whether this type is restrict-qualified.
664 bool isRestrictQualified() const;
666 /// \brief Determine whether this particular QualType instance has the
667 /// "volatile" qualifier set, without looking through typedefs that may have
668 /// added "volatile" at a different level.
669 bool isLocalVolatileQualified() const {
670 return (getLocalFastQualifiers() & Qualifiers::Volatile);
673 /// \brief Determine whether this type is volatile-qualified.
674 bool isVolatileQualified() const;
676 /// \brief Determine whether this particular QualType instance has any
677 /// qualifiers, without looking through any typedefs that might add
678 /// qualifiers at a different level.
679 bool hasLocalQualifiers() const {
680 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
683 /// \brief Determine whether this type has any qualifiers.
684 bool hasQualifiers() const;
686 /// \brief Determine whether this particular QualType instance has any
687 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
689 bool hasLocalNonFastQualifiers() const {
690 return Value.getPointer().is<const ExtQuals*>();
693 /// \brief Retrieve the set of qualifiers local to this particular QualType
694 /// instance, not including any qualifiers acquired through typedefs or
696 Qualifiers getLocalQualifiers() const;
698 /// \brief Retrieve the set of qualifiers applied to this type.
699 Qualifiers getQualifiers() const;
701 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
702 /// local to this particular QualType instance, not including any qualifiers
703 /// acquired through typedefs or other sugar.
704 unsigned getLocalCVRQualifiers() const {
705 return getLocalFastQualifiers();
708 /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
709 /// applied to this type.
710 unsigned getCVRQualifiers() const;
712 bool isConstant(ASTContext& Ctx) const {
713 return QualType::isConstant(*this, Ctx);
716 /// \brief Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
717 bool isPODType(ASTContext &Context) const;
719 /// Return true if this is a POD type according to the rules of the C++98
720 /// standard, regardless of the current compilation's language.
721 bool isCXX98PODType(ASTContext &Context) const;
723 /// Return true if this is a POD type according to the more relaxed rules
724 /// of the C++11 standard, regardless of the current compilation's language.
725 /// (C++0x [basic.types]p9)
726 bool isCXX11PODType(ASTContext &Context) const;
728 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
729 bool isTrivialType(ASTContext &Context) const;
731 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
732 bool isTriviallyCopyableType(ASTContext &Context) const;
734 // Don't promise in the API that anything besides 'const' can be
737 /// Add the `const` type qualifier to this QualType.
739 addFastQualifiers(Qualifiers::Const);
741 QualType withConst() const {
742 return withFastQualifiers(Qualifiers::Const);
745 /// Add the `volatile` type qualifier to this QualType.
747 addFastQualifiers(Qualifiers::Volatile);
749 QualType withVolatile() const {
750 return withFastQualifiers(Qualifiers::Volatile);
753 /// Add the `restrict` qualifier to this QualType.
755 addFastQualifiers(Qualifiers::Restrict);
757 QualType withRestrict() const {
758 return withFastQualifiers(Qualifiers::Restrict);
761 QualType withCVRQualifiers(unsigned CVR) const {
762 return withFastQualifiers(CVR);
765 void addFastQualifiers(unsigned TQs) {
766 assert(!(TQs & ~Qualifiers::FastMask)
767 && "non-fast qualifier bits set in mask!");
768 Value.setInt(Value.getInt() | TQs);
771 void removeLocalConst();
772 void removeLocalVolatile();
773 void removeLocalRestrict();
774 void removeLocalCVRQualifiers(unsigned Mask);
776 void removeLocalFastQualifiers() { Value.setInt(0); }
777 void removeLocalFastQualifiers(unsigned Mask) {
778 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
779 Value.setInt(Value.getInt() & ~Mask);
782 // Creates a type with the given qualifiers in addition to any
783 // qualifiers already on this type.
784 QualType withFastQualifiers(unsigned TQs) const {
786 T.addFastQualifiers(TQs);
790 // Creates a type with exactly the given fast qualifiers, removing
791 // any existing fast qualifiers.
792 QualType withExactLocalFastQualifiers(unsigned TQs) const {
793 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
796 // Removes fast qualifiers, but leaves any extended qualifiers in place.
797 QualType withoutLocalFastQualifiers() const {
799 T.removeLocalFastQualifiers();
803 QualType getCanonicalType() const;
805 /// \brief Return this type with all of the instance-specific qualifiers
806 /// removed, but without removing any qualifiers that may have been applied
807 /// through typedefs.
808 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
810 /// \brief Retrieve the unqualified variant of the given type,
811 /// removing as little sugar as possible.
813 /// This routine looks through various kinds of sugar to find the
814 /// least-desugared type that is unqualified. For example, given:
817 /// typedef int Integer;
818 /// typedef const Integer CInteger;
819 /// typedef CInteger DifferenceType;
822 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
823 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
825 /// The resulting type might still be qualified if it's sugar for an array
826 /// type. To strip qualifiers even from within a sugared array type, use
827 /// ASTContext::getUnqualifiedArrayType.
828 inline QualType getUnqualifiedType() const;
830 /// Retrieve the unqualified variant of the given type, removing as little
831 /// sugar as possible.
833 /// Like getUnqualifiedType(), but also returns the set of
834 /// qualifiers that were built up.
836 /// The resulting type might still be qualified if it's sugar for an array
837 /// type. To strip qualifiers even from within a sugared array type, use
838 /// ASTContext::getUnqualifiedArrayType.
839 inline SplitQualType getSplitUnqualifiedType() const;
841 /// \brief Determine whether this type is more qualified than the other
842 /// given type, requiring exact equality for non-CVR qualifiers.
843 bool isMoreQualifiedThan(QualType Other) const;
845 /// \brief Determine whether this type is at least as qualified as the other
846 /// given type, requiring exact equality for non-CVR qualifiers.
847 bool isAtLeastAsQualifiedAs(QualType Other) const;
849 QualType getNonReferenceType() const;
851 /// \brief Determine the type of a (typically non-lvalue) expression with the
852 /// specified result type.
854 /// This routine should be used for expressions for which the return type is
855 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
856 /// an lvalue. It removes a top-level reference (since there are no
857 /// expressions of reference type) and deletes top-level cvr-qualifiers
858 /// from non-class types (in C++) or all types (in C).
859 QualType getNonLValueExprType(const ASTContext &Context) const;
861 /// Return the specified type with any "sugar" removed from
862 /// the type. This takes off typedefs, typeof's etc. If the outer level of
863 /// the type is already concrete, it returns it unmodified. This is similar
864 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
865 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
868 /// Qualifiers are left in place.
869 QualType getDesugaredType(const ASTContext &Context) const {
870 return getDesugaredType(*this, Context);
873 SplitQualType getSplitDesugaredType() const {
874 return getSplitDesugaredType(*this);
877 /// \brief Return the specified type with one level of "sugar" removed from
880 /// This routine takes off the first typedef, typeof, etc. If the outer level
881 /// of the type is already concrete, it returns it unmodified.
882 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
883 return getSingleStepDesugaredTypeImpl(*this, Context);
886 /// Returns the specified type after dropping any
887 /// outer-level parentheses.
888 QualType IgnoreParens() const {
889 if (isa<ParenType>(*this))
890 return QualType::IgnoreParens(*this);
894 /// Indicate whether the specified types and qualifiers are identical.
895 friend bool operator==(const QualType &LHS, const QualType &RHS) {
896 return LHS.Value == RHS.Value;
898 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
899 return LHS.Value != RHS.Value;
901 std::string getAsString() const {
902 return getAsString(split());
904 static std::string getAsString(SplitQualType split) {
905 return getAsString(split.Ty, split.Quals);
907 static std::string getAsString(const Type *ty, Qualifiers qs);
909 std::string getAsString(const PrintingPolicy &Policy) const;
911 void print(raw_ostream &OS, const PrintingPolicy &Policy,
912 const Twine &PlaceHolder = Twine()) const {
913 print(split(), OS, Policy, PlaceHolder);
915 static void print(SplitQualType split, raw_ostream &OS,
916 const PrintingPolicy &policy, const Twine &PlaceHolder) {
917 return print(split.Ty, split.Quals, OS, policy, PlaceHolder);
919 static void print(const Type *ty, Qualifiers qs,
920 raw_ostream &OS, const PrintingPolicy &policy,
921 const Twine &PlaceHolder);
923 void getAsStringInternal(std::string &Str,
924 const PrintingPolicy &Policy) const {
925 return getAsStringInternal(split(), Str, Policy);
927 static void getAsStringInternal(SplitQualType split, std::string &out,
928 const PrintingPolicy &policy) {
929 return getAsStringInternal(split.Ty, split.Quals, out, policy);
931 static void getAsStringInternal(const Type *ty, Qualifiers qs,
933 const PrintingPolicy &policy);
935 class StreamedQualTypeHelper {
937 const PrintingPolicy &Policy;
938 const Twine &PlaceHolder;
940 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
941 const Twine &PlaceHolder)
942 : T(T), Policy(Policy), PlaceHolder(PlaceHolder) { }
944 friend raw_ostream &operator<<(raw_ostream &OS,
945 const StreamedQualTypeHelper &SQT) {
946 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder);
951 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
952 const Twine &PlaceHolder = Twine()) const {
953 return StreamedQualTypeHelper(*this, Policy, PlaceHolder);
956 void dump(const char *s) const;
959 void Profile(llvm::FoldingSetNodeID &ID) const {
960 ID.AddPointer(getAsOpaquePtr());
963 /// Return the address space of this type.
964 inline unsigned getAddressSpace() const;
966 /// Returns gc attribute of this type.
967 inline Qualifiers::GC getObjCGCAttr() const;
969 /// true when Type is objc's weak.
970 bool isObjCGCWeak() const {
971 return getObjCGCAttr() == Qualifiers::Weak;
974 /// true when Type is objc's strong.
975 bool isObjCGCStrong() const {
976 return getObjCGCAttr() == Qualifiers::Strong;
979 /// Returns lifetime attribute of this type.
980 Qualifiers::ObjCLifetime getObjCLifetime() const {
981 return getQualifiers().getObjCLifetime();
984 bool hasNonTrivialObjCLifetime() const {
985 return getQualifiers().hasNonTrivialObjCLifetime();
988 bool hasStrongOrWeakObjCLifetime() const {
989 return getQualifiers().hasStrongOrWeakObjCLifetime();
992 enum DestructionKind {
995 DK_objc_strong_lifetime,
996 DK_objc_weak_lifetime
999 /// Returns a nonzero value if objects of this type require
1000 /// non-trivial work to clean up after. Non-zero because it's
1001 /// conceivable that qualifiers (objc_gc(weak)?) could make
1002 /// something require destruction.
1003 DestructionKind isDestructedType() const {
1004 return isDestructedTypeImpl(*this);
1007 /// Determine whether expressions of the given type are forbidden
1008 /// from being lvalues in C.
1010 /// The expression types that are forbidden to be lvalues are:
1011 /// - 'void', but not qualified void
1012 /// - function types
1014 /// The exact rule here is C99 6.3.2.1:
1015 /// An lvalue is an expression with an object type or an incomplete
1016 /// type other than void.
1017 bool isCForbiddenLValueType() const;
1019 /// Substitute type arguments for the Objective-C type parameters used in the
1022 /// \param ctx ASTContext in which the type exists.
1024 /// \param typeArgs The type arguments that will be substituted for the
1025 /// Objective-C type parameters in the subject type, which are generally
1026 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1027 /// parameters will be replaced with their bounds or id/Class, as appropriate
1028 /// for the context.
1030 /// \param context The context in which the subject type was written.
1032 /// \returns the resulting type.
1033 QualType substObjCTypeArgs(ASTContext &ctx,
1034 ArrayRef<QualType> typeArgs,
1035 ObjCSubstitutionContext context) const;
1037 /// Substitute type arguments from an object type for the Objective-C type
1038 /// parameters used in the subject type.
1040 /// This operation combines the computation of type arguments for
1041 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1042 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1043 /// callers that need to perform a single substitution in isolation.
1045 /// \param objectType The type of the object whose member type we're
1046 /// substituting into. For example, this might be the receiver of a message
1047 /// or the base of a property access.
1049 /// \param dc The declaration context from which the subject type was
1050 /// retrieved, which indicates (for example) which type parameters should
1053 /// \param context The context in which the subject type was written.
1055 /// \returns the subject type after replacing all of the Objective-C type
1056 /// parameters with their corresponding arguments.
1057 QualType substObjCMemberType(QualType objectType,
1058 const DeclContext *dc,
1059 ObjCSubstitutionContext context) const;
1061 /// Strip Objective-C "__kindof" types from the given type.
1062 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1065 // These methods are implemented in a separate translation unit;
1066 // "static"-ize them to avoid creating temporary QualTypes in the
1068 static bool isConstant(QualType T, ASTContext& Ctx);
1069 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1070 static SplitQualType getSplitDesugaredType(QualType T);
1071 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1072 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1073 const ASTContext &C);
1074 static QualType IgnoreParens(QualType T);
1075 static DestructionKind isDestructedTypeImpl(QualType type);
1081 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1082 /// to a specific Type class.
1083 template<> struct simplify_type< ::clang::QualType> {
1084 typedef const ::clang::Type *SimpleType;
1085 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1086 return Val.getTypePtr();
1090 // Teach SmallPtrSet that QualType is "basically a pointer".
1092 class PointerLikeTypeTraits<clang::QualType> {
1094 static inline void *getAsVoidPointer(clang::QualType P) {
1095 return P.getAsOpaquePtr();
1097 static inline clang::QualType getFromVoidPointer(void *P) {
1098 return clang::QualType::getFromOpaquePtr(P);
1100 // Various qualifiers go in low bits.
1101 enum { NumLowBitsAvailable = 0 };
1104 } // end namespace llvm
1108 /// \brief Base class that is common to both the \c ExtQuals and \c Type
1109 /// classes, which allows \c QualType to access the common fields between the
1112 class ExtQualsTypeCommonBase {
1113 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1114 : BaseType(baseType), CanonicalType(canon) {}
1116 /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
1117 /// a self-referential pointer (for \c Type).
1119 /// This pointer allows an efficient mapping from a QualType to its
1120 /// underlying type pointer.
1121 const Type *const BaseType;
1123 /// \brief The canonical type of this type. A QualType.
1124 QualType CanonicalType;
1126 friend class QualType;
1128 friend class ExtQuals;
1131 /// We can encode up to four bits in the low bits of a
1132 /// type pointer, but there are many more type qualifiers that we want
1133 /// to be able to apply to an arbitrary type. Therefore we have this
1134 /// struct, intended to be heap-allocated and used by QualType to
1135 /// store qualifiers.
1137 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1138 /// in three low bits on the QualType pointer; a fourth bit records whether
1139 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1140 /// Objective-C GC attributes) are much more rare.
1141 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1142 // NOTE: changing the fast qualifiers should be straightforward as
1143 // long as you don't make 'const' non-fast.
1145 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1146 // Fast qualifiers must occupy the low-order bits.
1147 // b) Update Qualifiers::FastWidth and FastMask.
1149 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1150 // b) Update remove{Volatile,Restrict}, defined near the end of
1153 // a) Update get{Volatile,Restrict}Type.
1155 /// The immutable set of qualifiers applied by this node. Always contains
1156 /// extended qualifiers.
1159 ExtQuals *this_() { return this; }
1162 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1163 : ExtQualsTypeCommonBase(baseType,
1164 canon.isNull() ? QualType(this_(), 0) : canon),
1167 assert(Quals.hasNonFastQualifiers()
1168 && "ExtQuals created with no fast qualifiers");
1169 assert(!Quals.hasFastQualifiers()
1170 && "ExtQuals created with fast qualifiers");
1173 Qualifiers getQualifiers() const { return Quals; }
1175 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1176 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1178 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1179 Qualifiers::ObjCLifetime getObjCLifetime() const {
1180 return Quals.getObjCLifetime();
1183 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1184 unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
1186 const Type *getBaseType() const { return BaseType; }
1189 void Profile(llvm::FoldingSetNodeID &ID) const {
1190 Profile(ID, getBaseType(), Quals);
1192 static void Profile(llvm::FoldingSetNodeID &ID,
1193 const Type *BaseType,
1195 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1196 ID.AddPointer(BaseType);
1201 /// The kind of C++11 ref-qualifier associated with a function type.
1202 /// This determines whether a member function's "this" object can be an
1203 /// lvalue, rvalue, or neither.
1204 enum RefQualifierKind {
1205 /// \brief No ref-qualifier was provided.
1207 /// \brief An lvalue ref-qualifier was provided (\c &).
1209 /// \brief An rvalue ref-qualifier was provided (\c &&).
1213 /// Which keyword(s) were used to create an AutoType.
1214 enum class AutoTypeKeyword {
1217 /// \brief decltype(auto)
1219 /// \brief __auto_type (GNU extension)
1223 /// The base class of the type hierarchy.
1225 /// A central concept with types is that each type always has a canonical
1226 /// type. A canonical type is the type with any typedef names stripped out
1227 /// of it or the types it references. For example, consider:
1229 /// typedef int foo;
1230 /// typedef foo* bar;
1231 /// 'int *' 'foo *' 'bar'
1233 /// There will be a Type object created for 'int'. Since int is canonical, its
1234 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1235 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1236 /// there is a PointerType that represents 'int*', which, like 'int', is
1237 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1238 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1241 /// Non-canonical types are useful for emitting diagnostics, without losing
1242 /// information about typedefs being used. Canonical types are useful for type
1243 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1244 /// about whether something has a particular form (e.g. is a function type),
1245 /// because they implicitly, recursively, strip all typedefs out of a type.
1247 /// Types, once created, are immutable.
1249 class Type : public ExtQualsTypeCommonBase {
1252 #define TYPE(Class, Base) Class,
1253 #define LAST_TYPE(Class) TypeLast = Class,
1254 #define ABSTRACT_TYPE(Class, Base)
1255 #include "clang/AST/TypeNodes.def"
1256 TagFirst = Record, TagLast = Enum
1260 Type(const Type &) = delete;
1261 void operator=(const Type &) = delete;
1263 /// Bitfields required by the Type class.
1264 class TypeBitfields {
1266 template <class T> friend class TypePropertyCache;
1268 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1271 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1272 unsigned Dependent : 1;
1274 /// Whether this type somehow involves a template parameter, even
1275 /// if the resolution of the type does not depend on a template parameter.
1276 unsigned InstantiationDependent : 1;
1278 /// Whether this type is a variably-modified type (C99 6.7.5).
1279 unsigned VariablyModified : 1;
1281 /// \brief Whether this type contains an unexpanded parameter pack
1282 /// (for C++11 variadic templates).
1283 unsigned ContainsUnexpandedParameterPack : 1;
1285 /// \brief True if the cache (i.e. the bitfields here starting with
1286 /// 'Cache') is valid.
1287 mutable unsigned CacheValid : 1;
1289 /// \brief Linkage of this type.
1290 mutable unsigned CachedLinkage : 3;
1292 /// \brief Whether this type involves and local or unnamed types.
1293 mutable unsigned CachedLocalOrUnnamed : 1;
1295 /// \brief Whether this type comes from an AST file.
1296 mutable unsigned FromAST : 1;
1298 bool isCacheValid() const {
1301 Linkage getLinkage() const {
1302 assert(isCacheValid() && "getting linkage from invalid cache");
1303 return static_cast<Linkage>(CachedLinkage);
1305 bool hasLocalOrUnnamedType() const {
1306 assert(isCacheValid() && "getting linkage from invalid cache");
1307 return CachedLocalOrUnnamed;
1310 enum { NumTypeBits = 18 };
1313 // These classes allow subclasses to somewhat cleanly pack bitfields
1316 class ArrayTypeBitfields {
1317 friend class ArrayType;
1319 unsigned : NumTypeBits;
1321 /// CVR qualifiers from declarations like
1322 /// 'int X[static restrict 4]'. For function parameters only.
1323 unsigned IndexTypeQuals : 3;
1325 /// Storage class qualifiers from declarations like
1326 /// 'int X[static restrict 4]'. For function parameters only.
1327 /// Actually an ArrayType::ArraySizeModifier.
1328 unsigned SizeModifier : 3;
1331 class BuiltinTypeBitfields {
1332 friend class BuiltinType;
1334 unsigned : NumTypeBits;
1336 /// The kind (BuiltinType::Kind) of builtin type this is.
1340 class FunctionTypeBitfields {
1341 friend class FunctionType;
1342 friend class FunctionProtoType;
1344 unsigned : NumTypeBits;
1346 /// Extra information which affects how the function is called, like
1347 /// regparm and the calling convention.
1348 unsigned ExtInfo : 9;
1350 /// Used only by FunctionProtoType, put here to pack with the
1351 /// other bitfields.
1352 /// The qualifiers are part of FunctionProtoType because...
1354 /// C++ 8.3.5p4: The return type, the parameter type list and the
1355 /// cv-qualifier-seq, [...], are part of the function type.
1356 unsigned TypeQuals : 3;
1358 /// \brief The ref-qualifier associated with a \c FunctionProtoType.
1360 /// This is a value of type \c RefQualifierKind.
1361 unsigned RefQualifier : 2;
1364 class ObjCObjectTypeBitfields {
1365 friend class ObjCObjectType;
1367 unsigned : NumTypeBits;
1369 /// The number of type arguments stored directly on this object type.
1370 unsigned NumTypeArgs : 7;
1372 /// The number of protocols stored directly on this object type.
1373 unsigned NumProtocols : 6;
1375 /// Whether this is a "kindof" type.
1376 unsigned IsKindOf : 1;
1378 static_assert(NumTypeBits + 7 + 6 + 1 <= 32, "Does not fit in an unsigned");
1380 class ReferenceTypeBitfields {
1381 friend class ReferenceType;
1383 unsigned : NumTypeBits;
1385 /// True if the type was originally spelled with an lvalue sigil.
1386 /// This is never true of rvalue references but can also be false
1387 /// on lvalue references because of C++0x [dcl.typedef]p9,
1390 /// typedef int &ref; // lvalue, spelled lvalue
1391 /// typedef int &&rvref; // rvalue
1392 /// ref &a; // lvalue, inner ref, spelled lvalue
1393 /// ref &&a; // lvalue, inner ref
1394 /// rvref &a; // lvalue, inner ref, spelled lvalue
1395 /// rvref &&a; // rvalue, inner ref
1396 unsigned SpelledAsLValue : 1;
1398 /// True if the inner type is a reference type. This only happens
1399 /// in non-canonical forms.
1400 unsigned InnerRef : 1;
1403 class TypeWithKeywordBitfields {
1404 friend class TypeWithKeyword;
1406 unsigned : NumTypeBits;
1408 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1409 unsigned Keyword : 8;
1412 class VectorTypeBitfields {
1413 friend class VectorType;
1415 unsigned : NumTypeBits;
1417 /// The kind of vector, either a generic vector type or some
1418 /// target-specific vector type such as for AltiVec or Neon.
1419 unsigned VecKind : 3;
1421 /// The number of elements in the vector.
1422 unsigned NumElements : 29 - NumTypeBits;
1424 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1427 class AttributedTypeBitfields {
1428 friend class AttributedType;
1430 unsigned : NumTypeBits;
1432 /// An AttributedType::Kind
1433 unsigned AttrKind : 32 - NumTypeBits;
1436 class AutoTypeBitfields {
1437 friend class AutoType;
1439 unsigned : NumTypeBits;
1441 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1442 /// or '__auto_type'? AutoTypeKeyword value.
1443 unsigned Keyword : 2;
1447 TypeBitfields TypeBits;
1448 ArrayTypeBitfields ArrayTypeBits;
1449 AttributedTypeBitfields AttributedTypeBits;
1450 AutoTypeBitfields AutoTypeBits;
1451 BuiltinTypeBitfields BuiltinTypeBits;
1452 FunctionTypeBitfields FunctionTypeBits;
1453 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1454 ReferenceTypeBitfields ReferenceTypeBits;
1455 TypeWithKeywordBitfields TypeWithKeywordBits;
1456 VectorTypeBitfields VectorTypeBits;
1460 /// \brief Set whether this type comes from an AST file.
1461 void setFromAST(bool V = true) const {
1462 TypeBits.FromAST = V;
1465 template <class T> friend class TypePropertyCache;
1468 // silence VC++ warning C4355: 'this' : used in base member initializer list
1469 Type *this_() { return this; }
1470 Type(TypeClass tc, QualType canon, bool Dependent,
1471 bool InstantiationDependent, bool VariablyModified,
1472 bool ContainsUnexpandedParameterPack)
1473 : ExtQualsTypeCommonBase(this,
1474 canon.isNull() ? QualType(this_(), 0) : canon) {
1476 TypeBits.Dependent = Dependent;
1477 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1478 TypeBits.VariablyModified = VariablyModified;
1479 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1480 TypeBits.CacheValid = false;
1481 TypeBits.CachedLocalOrUnnamed = false;
1482 TypeBits.CachedLinkage = NoLinkage;
1483 TypeBits.FromAST = false;
1485 friend class ASTContext;
1487 void setDependent(bool D = true) {
1488 TypeBits.Dependent = D;
1490 TypeBits.InstantiationDependent = true;
1492 void setInstantiationDependent(bool D = true) {
1493 TypeBits.InstantiationDependent = D; }
1494 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM;
1496 void setContainsUnexpandedParameterPack(bool PP = true) {
1497 TypeBits.ContainsUnexpandedParameterPack = PP;
1501 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1503 /// \brief Whether this type comes from an AST file.
1504 bool isFromAST() const { return TypeBits.FromAST; }
1506 /// \brief Whether this type is or contains an unexpanded parameter
1507 /// pack, used to support C++0x variadic templates.
1509 /// A type that contains a parameter pack shall be expanded by the
1510 /// ellipsis operator at some point. For example, the typedef in the
1511 /// following example contains an unexpanded parameter pack 'T':
1514 /// template<typename ...T>
1516 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1520 /// Note that this routine does not specify which
1521 bool containsUnexpandedParameterPack() const {
1522 return TypeBits.ContainsUnexpandedParameterPack;
1525 /// Determines if this type would be canonical if it had no further
1527 bool isCanonicalUnqualified() const {
1528 return CanonicalType == QualType(this, 0);
1531 /// Pull a single level of sugar off of this locally-unqualified type.
1532 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1533 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1534 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1536 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1537 /// object types, function types, and incomplete types.
1539 /// Return true if this is an incomplete type.
1540 /// A type that can describe objects, but which lacks information needed to
1541 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1542 /// routine will need to determine if the size is actually required.
1544 /// \brief Def If non-null, and the type refers to some kind of declaration
1545 /// that can be completed (such as a C struct, C++ class, or Objective-C
1546 /// class), will be set to the declaration.
1547 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1549 /// Return true if this is an incomplete or object
1550 /// type, in other words, not a function type.
1551 bool isIncompleteOrObjectType() const {
1552 return !isFunctionType();
1555 /// \brief Determine whether this type is an object type.
1556 bool isObjectType() const {
1557 // C++ [basic.types]p8:
1558 // An object type is a (possibly cv-qualified) type that is not a
1559 // function type, not a reference type, and not a void type.
1560 return !isReferenceType() && !isFunctionType() && !isVoidType();
1563 /// Return true if this is a literal type
1564 /// (C++11 [basic.types]p10)
1565 bool isLiteralType(const ASTContext &Ctx) const;
1567 /// Test if this type is a standard-layout type.
1568 /// (C++0x [basic.type]p9)
1569 bool isStandardLayoutType() const;
1571 /// Helper methods to distinguish type categories. All type predicates
1572 /// operate on the canonical type, ignoring typedefs and qualifiers.
1574 /// Returns true if the type is a builtin type.
1575 bool isBuiltinType() const;
1577 /// Test for a particular builtin type.
1578 bool isSpecificBuiltinType(unsigned K) const;
1580 /// Test for a type which does not represent an actual type-system type but
1581 /// is instead used as a placeholder for various convenient purposes within
1582 /// Clang. All such types are BuiltinTypes.
1583 bool isPlaceholderType() const;
1584 const BuiltinType *getAsPlaceholderType() const;
1586 /// Test for a specific placeholder type.
1587 bool isSpecificPlaceholderType(unsigned K) const;
1589 /// Test for a placeholder type other than Overload; see
1590 /// BuiltinType::isNonOverloadPlaceholderType.
1591 bool isNonOverloadPlaceholderType() const;
1593 /// isIntegerType() does *not* include complex integers (a GCC extension).
1594 /// isComplexIntegerType() can be used to test for complex integers.
1595 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1596 bool isEnumeralType() const;
1597 bool isBooleanType() const;
1598 bool isCharType() const;
1599 bool isWideCharType() const;
1600 bool isChar16Type() const;
1601 bool isChar32Type() const;
1602 bool isAnyCharacterType() const;
1603 bool isIntegralType(ASTContext &Ctx) const;
1605 /// Determine whether this type is an integral or enumeration type.
1606 bool isIntegralOrEnumerationType() const;
1607 /// Determine whether this type is an integral or unscoped enumeration type.
1608 bool isIntegralOrUnscopedEnumerationType() const;
1610 /// Floating point categories.
1611 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1612 /// isComplexType() does *not* include complex integers (a GCC extension).
1613 /// isComplexIntegerType() can be used to test for complex integers.
1614 bool isComplexType() const; // C99 6.2.5p11 (complex)
1615 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1616 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1617 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1618 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1619 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1620 bool isVoidType() const; // C99 6.2.5p19
1621 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1622 bool isAggregateType() const;
1623 bool isFundamentalType() const;
1624 bool isCompoundType() const;
1626 // Type Predicates: Check to see if this type is structurally the specified
1627 // type, ignoring typedefs and qualifiers.
1628 bool isFunctionType() const;
1629 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1630 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1631 bool isPointerType() const;
1632 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1633 bool isBlockPointerType() const;
1634 bool isVoidPointerType() const;
1635 bool isReferenceType() const;
1636 bool isLValueReferenceType() const;
1637 bool isRValueReferenceType() const;
1638 bool isFunctionPointerType() const;
1639 bool isMemberPointerType() const;
1640 bool isMemberFunctionPointerType() const;
1641 bool isMemberDataPointerType() const;
1642 bool isArrayType() const;
1643 bool isConstantArrayType() const;
1644 bool isIncompleteArrayType() const;
1645 bool isVariableArrayType() const;
1646 bool isDependentSizedArrayType() const;
1647 bool isRecordType() const;
1648 bool isClassType() const;
1649 bool isStructureType() const;
1650 bool isObjCBoxableRecordType() const;
1651 bool isInterfaceType() const;
1652 bool isStructureOrClassType() const;
1653 bool isUnionType() const;
1654 bool isComplexIntegerType() const; // GCC _Complex integer type.
1655 bool isVectorType() const; // GCC vector type.
1656 bool isExtVectorType() const; // Extended vector type.
1657 bool isObjCObjectPointerType() const; // pointer to ObjC object
1658 bool isObjCRetainableType() const; // ObjC object or block pointer
1659 bool isObjCLifetimeType() const; // (array of)* retainable type
1660 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1661 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1662 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1663 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1664 // for the common case.
1665 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1666 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1667 bool isObjCQualifiedIdType() const; // id<foo>
1668 bool isObjCQualifiedClassType() const; // Class<foo>
1669 bool isObjCObjectOrInterfaceType() const;
1670 bool isObjCIdType() const; // id
1671 bool isObjCInertUnsafeUnretainedType() const;
1673 /// Whether the type is Objective-C 'id' or a __kindof type of an
1674 /// object type, e.g., __kindof NSView * or __kindof id
1677 /// \param bound Will be set to the bound on non-id subtype types,
1678 /// which will be (possibly specialized) Objective-C class type, or
1680 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1681 const ObjCObjectType *&bound) const;
1683 bool isObjCClassType() const; // Class
1685 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1686 /// Class type, e.g., __kindof Class <NSCopying>.
1688 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
1689 /// here because Objective-C's type system cannot express "a class
1690 /// object for a subclass of NSFoo".
1691 bool isObjCClassOrClassKindOfType() const;
1693 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
1694 bool isObjCSelType() const; // Class
1695 bool isObjCBuiltinType() const; // 'id' or 'Class'
1696 bool isObjCARCBridgableType() const;
1697 bool isCARCBridgableType() const;
1698 bool isTemplateTypeParmType() const; // C++ template type parameter
1699 bool isNullPtrType() const; // C++0x nullptr_t
1700 bool isAtomicType() const; // C11 _Atomic()
1702 bool isImage1dT() const; // OpenCL image1d_t
1703 bool isImage1dArrayT() const; // OpenCL image1d_array_t
1704 bool isImage1dBufferT() const; // OpenCL image1d_buffer_t
1705 bool isImage2dT() const; // OpenCL image2d_t
1706 bool isImage2dArrayT() const; // OpenCL image2d_array_t
1707 bool isImage2dDepthT() const; // OpenCL image_2d_depth_t
1708 bool isImage2dArrayDepthT() const; // OpenCL image_2d_array_depth_t
1709 bool isImage2dMSAAT() const; // OpenCL image_2d_msaa_t
1710 bool isImage2dArrayMSAAT() const; // OpenCL image_2d_array_msaa_t
1711 bool isImage2dMSAATDepth() const; // OpenCL image_2d_msaa_depth_t
1712 bool isImage2dArrayMSAATDepth() const; // OpenCL image_2d_array_msaa_depth_t
1713 bool isImage3dT() const; // OpenCL image3d_t
1715 bool isImageType() const; // Any OpenCL image type
1717 bool isSamplerT() const; // OpenCL sampler_t
1718 bool isEventT() const; // OpenCL event_t
1719 bool isClkEventT() const; // OpenCL clk_event_t
1720 bool isQueueT() const; // OpenCL queue_t
1721 bool isNDRangeT() const; // OpenCL ndrange_t
1722 bool isReserveIDT() const; // OpenCL reserve_id_t
1724 bool isPipeType() const; // OpenCL pipe type
1725 bool isOpenCLSpecificType() const; // Any OpenCL specific type
1727 /// Determines if this type, which must satisfy
1728 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
1729 /// than implicitly __strong.
1730 bool isObjCARCImplicitlyUnretainedType() const;
1732 /// Return the implicit lifetime for this type, which must not be dependent.
1733 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
1735 enum ScalarTypeKind {
1738 STK_ObjCObjectPointer,
1743 STK_IntegralComplex,
1746 /// Given that this is a scalar type, classify it.
1747 ScalarTypeKind getScalarTypeKind() const;
1749 /// Whether this type is a dependent type, meaning that its definition
1750 /// somehow depends on a template parameter (C++ [temp.dep.type]).
1751 bool isDependentType() const { return TypeBits.Dependent; }
1753 /// \brief Determine whether this type is an instantiation-dependent type,
1754 /// meaning that the type involves a template parameter (even if the
1755 /// definition does not actually depend on the type substituted for that
1756 /// template parameter).
1757 bool isInstantiationDependentType() const {
1758 return TypeBits.InstantiationDependent;
1761 /// \brief Determine whether this type is an undeduced type, meaning that
1762 /// it somehow involves a C++11 'auto' type which has not yet been deduced.
1763 bool isUndeducedType() const;
1765 /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1766 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1768 /// \brief Whether this type involves a variable-length array type
1769 /// with a definite size.
1770 bool hasSizedVLAType() const;
1772 /// \brief Whether this type is or contains a local or unnamed type.
1773 bool hasUnnamedOrLocalType() const;
1775 bool isOverloadableType() const;
1777 /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1778 bool isElaboratedTypeSpecifier() const;
1780 bool canDecayToPointerType() const;
1782 /// Whether this type is represented natively as a pointer. This includes
1783 /// pointers, references, block pointers, and Objective-C interface,
1784 /// qualified id, and qualified interface types, as well as nullptr_t.
1785 bool hasPointerRepresentation() const;
1787 /// Whether this type can represent an objective pointer type for the
1788 /// purpose of GC'ability
1789 bool hasObjCPointerRepresentation() const;
1791 /// \brief Determine whether this type has an integer representation
1792 /// of some sort, e.g., it is an integer type or a vector.
1793 bool hasIntegerRepresentation() const;
1795 /// \brief Determine whether this type has an signed integer representation
1796 /// of some sort, e.g., it is an signed integer type or a vector.
1797 bool hasSignedIntegerRepresentation() const;
1799 /// \brief Determine whether this type has an unsigned integer representation
1800 /// of some sort, e.g., it is an unsigned integer type or a vector.
1801 bool hasUnsignedIntegerRepresentation() const;
1803 /// \brief Determine whether this type has a floating-point representation
1804 /// of some sort, e.g., it is a floating-point type or a vector thereof.
1805 bool hasFloatingRepresentation() const;
1807 // Type Checking Functions: Check to see if this type is structurally the
1808 // specified type, ignoring typedefs and qualifiers, and return a pointer to
1809 // the best type we can.
1810 const RecordType *getAsStructureType() const;
1811 /// NOTE: getAs*ArrayType are methods on ASTContext.
1812 const RecordType *getAsUnionType() const;
1813 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1814 const ObjCObjectType *getAsObjCInterfaceType() const;
1815 // The following is a convenience method that returns an ObjCObjectPointerType
1816 // for object declared using an interface.
1817 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1818 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1819 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
1820 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1822 /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1823 /// because the type is a RecordType or because it is the injected-class-name
1824 /// type of a class template or class template partial specialization.
1825 CXXRecordDecl *getAsCXXRecordDecl() const;
1827 /// \brief Retrieves the TagDecl that this type refers to, either
1828 /// because the type is a TagType or because it is the injected-class-name
1829 /// type of a class template or class template partial specialization.
1830 TagDecl *getAsTagDecl() const;
1832 /// If this is a pointer or reference to a RecordType, return the
1833 /// CXXRecordDecl that that type refers to.
1835 /// If this is not a pointer or reference, or the type being pointed to does
1836 /// not refer to a CXXRecordDecl, returns NULL.
1837 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
1839 /// Get the AutoType whose type will be deduced for a variable with
1840 /// an initializer of this type. This looks through declarators like pointer
1841 /// types, but not through decltype or typedefs.
1842 AutoType *getContainedAutoType() const;
1844 /// Member-template getAs<specific type>'. Look through sugar for
1845 /// an instance of \<specific type>. This scheme will eventually
1846 /// replace the specific getAsXXXX methods above.
1848 /// There are some specializations of this member template listed
1849 /// immediately following this class.
1850 template <typename T> const T *getAs() const;
1852 /// A variant of getAs<> for array types which silently discards
1853 /// qualifiers from the outermost type.
1854 const ArrayType *getAsArrayTypeUnsafe() const;
1856 /// Member-template castAs<specific type>. Look through sugar for
1857 /// the underlying instance of \<specific type>.
1859 /// This method has the same relationship to getAs<T> as cast<T> has
1860 /// to dyn_cast<T>; which is to say, the underlying type *must*
1861 /// have the intended type, and this method will never return null.
1862 template <typename T> const T *castAs() const;
1864 /// A variant of castAs<> for array type which silently discards
1865 /// qualifiers from the outermost type.
1866 const ArrayType *castAsArrayTypeUnsafe() const;
1868 /// Get the base element type of this type, potentially discarding type
1869 /// qualifiers. This should never be used when type qualifiers
1871 const Type *getBaseElementTypeUnsafe() const;
1873 /// If this is an array type, return the element type of the array,
1874 /// potentially with type qualifiers missing.
1875 /// This should never be used when type qualifiers are meaningful.
1876 const Type *getArrayElementTypeNoTypeQual() const;
1878 /// If this is a pointer, ObjC object pointer, or block
1879 /// pointer, this returns the respective pointee.
1880 QualType getPointeeType() const;
1882 /// Return the specified type with any "sugar" removed from the type,
1883 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
1884 const Type *getUnqualifiedDesugaredType() const;
1886 /// More type predicates useful for type checking/promotion
1887 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1889 /// Return true if this is an integer type that is
1890 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1891 /// or an enum decl which has a signed representation.
1892 bool isSignedIntegerType() const;
1894 /// Return true if this is an integer type that is
1895 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
1896 /// or an enum decl which has an unsigned representation.
1897 bool isUnsignedIntegerType() const;
1899 /// Determines whether this is an integer type that is signed or an
1900 /// enumeration types whose underlying type is a signed integer type.
1901 bool isSignedIntegerOrEnumerationType() const;
1903 /// Determines whether this is an integer type that is unsigned or an
1904 /// enumeration types whose underlying type is a unsigned integer type.
1905 bool isUnsignedIntegerOrEnumerationType() const;
1907 /// Return true if this is not a variable sized type,
1908 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
1909 /// incomplete types.
1910 bool isConstantSizeType() const;
1912 /// Returns true if this type can be represented by some
1913 /// set of type specifiers.
1914 bool isSpecifierType() const;
1916 /// Determine the linkage of this type.
1917 Linkage getLinkage() const;
1919 /// Determine the visibility of this type.
1920 Visibility getVisibility() const {
1921 return getLinkageAndVisibility().getVisibility();
1924 /// Return true if the visibility was explicitly set is the code.
1925 bool isVisibilityExplicit() const {
1926 return getLinkageAndVisibility().isVisibilityExplicit();
1929 /// Determine the linkage and visibility of this type.
1930 LinkageInfo getLinkageAndVisibility() const;
1932 /// True if the computed linkage is valid. Used for consistency
1933 /// checking. Should always return true.
1934 bool isLinkageValid() const;
1936 /// Determine the nullability of the given type.
1938 /// Note that nullability is only captured as sugar within the type
1939 /// system, not as part of the canonical type, so nullability will
1940 /// be lost by canonicalization and desugaring.
1941 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
1943 /// Determine whether the given type can have a nullability
1944 /// specifier applied to it, i.e., if it is any kind of pointer type
1945 /// or a dependent type that could instantiate to any kind of
1947 bool canHaveNullability() const;
1949 /// Retrieve the set of substitutions required when accessing a member
1950 /// of the Objective-C receiver type that is declared in the given context.
1952 /// \c *this is the type of the object we're operating on, e.g., the
1953 /// receiver for a message send or the base of a property access, and is
1954 /// expected to be of some object or object pointer type.
1956 /// \param dc The declaration context for which we are building up a
1957 /// substitution mapping, which should be an Objective-C class, extension,
1958 /// category, or method within.
1960 /// \returns an array of type arguments that can be substituted for
1961 /// the type parameters of the given declaration context in any type described
1962 /// within that context, or an empty optional to indicate that no
1963 /// substitution is required.
1964 Optional<ArrayRef<QualType>>
1965 getObjCSubstitutions(const DeclContext *dc) const;
1967 /// Determines if this is an ObjC interface type that may accept type
1969 bool acceptsObjCTypeParams() const;
1971 const char *getTypeClassName() const;
1973 QualType getCanonicalTypeInternal() const {
1974 return CanonicalType;
1976 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1979 friend class ASTReader;
1980 friend class ASTWriter;
1983 /// \brief This will check for a TypedefType by removing any existing sugar
1984 /// until it reaches a TypedefType or a non-sugared type.
1985 template <> const TypedefType *Type::getAs() const;
1987 /// \brief This will check for a TemplateSpecializationType by removing any
1988 /// existing sugar until it reaches a TemplateSpecializationType or a
1989 /// non-sugared type.
1990 template <> const TemplateSpecializationType *Type::getAs() const;
1992 /// \brief This will check for an AttributedType by removing any existing sugar
1993 /// until it reaches an AttributedType or a non-sugared type.
1994 template <> const AttributedType *Type::getAs() const;
1996 // We can do canonical leaf types faster, because we don't have to
1997 // worry about preserving child type decoration.
1998 #define TYPE(Class, Base)
1999 #define LEAF_TYPE(Class) \
2000 template <> inline const Class##Type *Type::getAs() const { \
2001 return dyn_cast<Class##Type>(CanonicalType); \
2003 template <> inline const Class##Type *Type::castAs() const { \
2004 return cast<Class##Type>(CanonicalType); \
2006 #include "clang/AST/TypeNodes.def"
2009 /// This class is used for builtin types like 'int'. Builtin
2010 /// types are always canonical and have a literal name field.
2011 class BuiltinType : public Type {
2014 #define BUILTIN_TYPE(Id, SingletonId) Id,
2015 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2016 #include "clang/AST/BuiltinTypes.def"
2021 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2022 /*InstantiationDependent=*/(K == Dependent),
2023 /*VariablyModified=*/false,
2024 /*Unexpanded paramter pack=*/false) {
2025 BuiltinTypeBits.Kind = K;
2028 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2029 StringRef getName(const PrintingPolicy &Policy) const;
2030 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2031 // The StringRef is null-terminated.
2032 StringRef str = getName(Policy);
2033 assert(!str.empty() && str.data()[str.size()] == '\0');
2037 bool isSugared() const { return false; }
2038 QualType desugar() const { return QualType(this, 0); }
2040 bool isInteger() const {
2041 return getKind() >= Bool && getKind() <= Int128;
2044 bool isSignedInteger() const {
2045 return getKind() >= Char_S && getKind() <= Int128;
2048 bool isUnsignedInteger() const {
2049 return getKind() >= Bool && getKind() <= UInt128;
2052 bool isFloatingPoint() const {
2053 return getKind() >= Half && getKind() <= LongDouble;
2056 /// Determines whether the given kind corresponds to a placeholder type.
2057 static bool isPlaceholderTypeKind(Kind K) {
2058 return K >= Overload;
2061 /// Determines whether this type is a placeholder type, i.e. a type
2062 /// which cannot appear in arbitrary positions in a fully-formed
2064 bool isPlaceholderType() const {
2065 return isPlaceholderTypeKind(getKind());
2068 /// Determines whether this type is a placeholder type other than
2069 /// Overload. Most placeholder types require only syntactic
2070 /// information about their context in order to be resolved (e.g.
2071 /// whether it is a call expression), which means they can (and
2072 /// should) be resolved in an earlier "phase" of analysis.
2073 /// Overload expressions sometimes pick up further information
2074 /// from their context, like whether the context expects a
2075 /// specific function-pointer type, and so frequently need
2076 /// special treatment.
2077 bool isNonOverloadPlaceholderType() const {
2078 return getKind() > Overload;
2081 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2084 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2085 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2087 class ComplexType : public Type, public llvm::FoldingSetNode {
2088 QualType ElementType;
2089 ComplexType(QualType Element, QualType CanonicalPtr) :
2090 Type(Complex, CanonicalPtr, Element->isDependentType(),
2091 Element->isInstantiationDependentType(),
2092 Element->isVariablyModifiedType(),
2093 Element->containsUnexpandedParameterPack()),
2094 ElementType(Element) {
2096 friend class ASTContext; // ASTContext creates these.
2099 QualType getElementType() const { return ElementType; }
2101 bool isSugared() const { return false; }
2102 QualType desugar() const { return QualType(this, 0); }
2104 void Profile(llvm::FoldingSetNodeID &ID) {
2105 Profile(ID, getElementType());
2107 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2108 ID.AddPointer(Element.getAsOpaquePtr());
2111 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2114 /// Sugar for parentheses used when specifying types.
2116 class ParenType : public Type, public llvm::FoldingSetNode {
2119 ParenType(QualType InnerType, QualType CanonType) :
2120 Type(Paren, CanonType, InnerType->isDependentType(),
2121 InnerType->isInstantiationDependentType(),
2122 InnerType->isVariablyModifiedType(),
2123 InnerType->containsUnexpandedParameterPack()),
2126 friend class ASTContext; // ASTContext creates these.
2130 QualType getInnerType() const { return Inner; }
2132 bool isSugared() const { return true; }
2133 QualType desugar() const { return getInnerType(); }
2135 void Profile(llvm::FoldingSetNodeID &ID) {
2136 Profile(ID, getInnerType());
2138 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2142 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2145 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2147 class PointerType : public Type, public llvm::FoldingSetNode {
2148 QualType PointeeType;
2150 PointerType(QualType Pointee, QualType CanonicalPtr) :
2151 Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2152 Pointee->isInstantiationDependentType(),
2153 Pointee->isVariablyModifiedType(),
2154 Pointee->containsUnexpandedParameterPack()),
2155 PointeeType(Pointee) {
2157 friend class ASTContext; // ASTContext creates these.
2161 QualType getPointeeType() const { return PointeeType; }
2163 /// Returns true if address spaces of pointers overlap.
2164 /// OpenCL v2.0 defines conversion rules for pointers to different
2165 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2168 /// address spaces overlap iff they are they same.
2170 /// __generic overlaps with any address space except for __constant.
2171 bool isAddressSpaceOverlapping(const PointerType &other) const {
2172 Qualifiers thisQuals = PointeeType.getQualifiers();
2173 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2174 // Address spaces overlap if at least one of them is a superset of another
2175 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2176 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2179 bool isSugared() const { return false; }
2180 QualType desugar() const { return QualType(this, 0); }
2182 void Profile(llvm::FoldingSetNodeID &ID) {
2183 Profile(ID, getPointeeType());
2185 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2186 ID.AddPointer(Pointee.getAsOpaquePtr());
2189 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2192 /// Represents a type which was implicitly adjusted by the semantic
2193 /// engine for arbitrary reasons. For example, array and function types can
2194 /// decay, and function types can have their calling conventions adjusted.
2195 class AdjustedType : public Type, public llvm::FoldingSetNode {
2196 QualType OriginalTy;
2197 QualType AdjustedTy;
2200 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2201 QualType CanonicalPtr)
2202 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2203 OriginalTy->isInstantiationDependentType(),
2204 OriginalTy->isVariablyModifiedType(),
2205 OriginalTy->containsUnexpandedParameterPack()),
2206 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2208 friend class ASTContext; // ASTContext creates these.
2211 QualType getOriginalType() const { return OriginalTy; }
2212 QualType getAdjustedType() const { return AdjustedTy; }
2214 bool isSugared() const { return true; }
2215 QualType desugar() const { return AdjustedTy; }
2217 void Profile(llvm::FoldingSetNodeID &ID) {
2218 Profile(ID, OriginalTy, AdjustedTy);
2220 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2221 ID.AddPointer(Orig.getAsOpaquePtr());
2222 ID.AddPointer(New.getAsOpaquePtr());
2225 static bool classof(const Type *T) {
2226 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2230 /// Represents a pointer type decayed from an array or function type.
2231 class DecayedType : public AdjustedType {
2233 DecayedType(QualType OriginalType, QualType DecayedPtr, QualType CanonicalPtr)
2234 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
2235 assert(isa<PointerType>(getAdjustedType()));
2238 friend class ASTContext; // ASTContext creates these.
2241 QualType getDecayedType() const { return getAdjustedType(); }
2243 QualType getPointeeType() const {
2244 return cast<PointerType>(getDecayedType())->getPointeeType();
2247 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2250 /// Pointer to a block type.
2251 /// This type is to represent types syntactically represented as
2252 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2254 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2255 QualType PointeeType; // Block is some kind of pointer type
2256 BlockPointerType(QualType Pointee, QualType CanonicalCls) :
2257 Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2258 Pointee->isInstantiationDependentType(),
2259 Pointee->isVariablyModifiedType(),
2260 Pointee->containsUnexpandedParameterPack()),
2261 PointeeType(Pointee) {
2263 friend class ASTContext; // ASTContext creates these.
2267 // Get the pointee type. Pointee is required to always be a function type.
2268 QualType getPointeeType() const { return PointeeType; }
2270 bool isSugared() const { return false; }
2271 QualType desugar() const { return QualType(this, 0); }
2273 void Profile(llvm::FoldingSetNodeID &ID) {
2274 Profile(ID, getPointeeType());
2276 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2277 ID.AddPointer(Pointee.getAsOpaquePtr());
2280 static bool classof(const Type *T) {
2281 return T->getTypeClass() == BlockPointer;
2285 /// Base for LValueReferenceType and RValueReferenceType
2287 class ReferenceType : public Type, public llvm::FoldingSetNode {
2288 QualType PointeeType;
2291 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2292 bool SpelledAsLValue) :
2293 Type(tc, CanonicalRef, Referencee->isDependentType(),
2294 Referencee->isInstantiationDependentType(),
2295 Referencee->isVariablyModifiedType(),
2296 Referencee->containsUnexpandedParameterPack()),
2297 PointeeType(Referencee)
2299 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2300 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2304 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2305 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2307 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2308 QualType getPointeeType() const {
2309 // FIXME: this might strip inner qualifiers; okay?
2310 const ReferenceType *T = this;
2311 while (T->isInnerRef())
2312 T = T->PointeeType->castAs<ReferenceType>();
2313 return T->PointeeType;
2316 void Profile(llvm::FoldingSetNodeID &ID) {
2317 Profile(ID, PointeeType, isSpelledAsLValue());
2319 static void Profile(llvm::FoldingSetNodeID &ID,
2320 QualType Referencee,
2321 bool SpelledAsLValue) {
2322 ID.AddPointer(Referencee.getAsOpaquePtr());
2323 ID.AddBoolean(SpelledAsLValue);
2326 static bool classof(const Type *T) {
2327 return T->getTypeClass() == LValueReference ||
2328 T->getTypeClass() == RValueReference;
2332 /// An lvalue reference type, per C++11 [dcl.ref].
2334 class LValueReferenceType : public ReferenceType {
2335 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2336 bool SpelledAsLValue) :
2337 ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
2339 friend class ASTContext; // ASTContext creates these
2341 bool isSugared() const { return false; }
2342 QualType desugar() const { return QualType(this, 0); }
2344 static bool classof(const Type *T) {
2345 return T->getTypeClass() == LValueReference;
2349 /// An rvalue reference type, per C++11 [dcl.ref].
2351 class RValueReferenceType : public ReferenceType {
2352 RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
2353 ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
2355 friend class ASTContext; // ASTContext creates these
2357 bool isSugared() const { return false; }
2358 QualType desugar() const { return QualType(this, 0); }
2360 static bool classof(const Type *T) {
2361 return T->getTypeClass() == RValueReference;
2365 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2367 /// This includes both pointers to data members and pointer to member functions.
2369 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2370 QualType PointeeType;
2371 /// The class of which the pointee is a member. Must ultimately be a
2372 /// RecordType, but could be a typedef or a template parameter too.
2375 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
2376 Type(MemberPointer, CanonicalPtr,
2377 Cls->isDependentType() || Pointee->isDependentType(),
2378 (Cls->isInstantiationDependentType() ||
2379 Pointee->isInstantiationDependentType()),
2380 Pointee->isVariablyModifiedType(),
2381 (Cls->containsUnexpandedParameterPack() ||
2382 Pointee->containsUnexpandedParameterPack())),
2383 PointeeType(Pointee), Class(Cls) {
2385 friend class ASTContext; // ASTContext creates these.
2388 QualType getPointeeType() const { return PointeeType; }
2390 /// Returns true if the member type (i.e. the pointee type) is a
2391 /// function type rather than a data-member type.
2392 bool isMemberFunctionPointer() const {
2393 return PointeeType->isFunctionProtoType();
2396 /// Returns true if the member type (i.e. the pointee type) is a
2397 /// data type rather than a function type.
2398 bool isMemberDataPointer() const {
2399 return !PointeeType->isFunctionProtoType();
2402 const Type *getClass() const { return Class; }
2403 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2405 bool isSugared() const { return false; }
2406 QualType desugar() const { return QualType(this, 0); }
2408 void Profile(llvm::FoldingSetNodeID &ID) {
2409 Profile(ID, getPointeeType(), getClass());
2411 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2412 const Type *Class) {
2413 ID.AddPointer(Pointee.getAsOpaquePtr());
2414 ID.AddPointer(Class);
2417 static bool classof(const Type *T) {
2418 return T->getTypeClass() == MemberPointer;
2422 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2424 class ArrayType : public Type, public llvm::FoldingSetNode {
2426 /// Capture whether this is a normal array (e.g. int X[4])
2427 /// an array with a static size (e.g. int X[static 4]), or an array
2428 /// with a star size (e.g. int X[*]).
2429 /// 'static' is only allowed on function parameters.
2430 enum ArraySizeModifier {
2431 Normal, Static, Star
2434 /// The element type of the array.
2435 QualType ElementType;
2438 // C++ [temp.dep.type]p1:
2439 // A type is dependent if it is...
2440 // - an array type constructed from any dependent type or whose
2441 // size is specified by a constant expression that is
2443 ArrayType(TypeClass tc, QualType et, QualType can,
2444 ArraySizeModifier sm, unsigned tq,
2445 bool ContainsUnexpandedParameterPack)
2446 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2447 et->isInstantiationDependentType() || tc == DependentSizedArray,
2448 (tc == VariableArray || et->isVariablyModifiedType()),
2449 ContainsUnexpandedParameterPack),
2451 ArrayTypeBits.IndexTypeQuals = tq;
2452 ArrayTypeBits.SizeModifier = sm;
2455 friend class ASTContext; // ASTContext creates these.
2458 QualType getElementType() const { return ElementType; }
2459 ArraySizeModifier getSizeModifier() const {
2460 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2462 Qualifiers getIndexTypeQualifiers() const {
2463 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2465 unsigned getIndexTypeCVRQualifiers() const {
2466 return ArrayTypeBits.IndexTypeQuals;
2469 static bool classof(const Type *T) {
2470 return T->getTypeClass() == ConstantArray ||
2471 T->getTypeClass() == VariableArray ||
2472 T->getTypeClass() == IncompleteArray ||
2473 T->getTypeClass() == DependentSizedArray;
2477 /// Represents the canonical version of C arrays with a specified constant size.
2478 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2479 /// ConstantArrayType where the element type is 'int' and the size is 404.
2480 class ConstantArrayType : public ArrayType {
2481 llvm::APInt Size; // Allows us to unique the type.
2483 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2484 ArraySizeModifier sm, unsigned tq)
2485 : ArrayType(ConstantArray, et, can, sm, tq,
2486 et->containsUnexpandedParameterPack()),
2489 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2490 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2491 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2493 friend class ASTContext; // ASTContext creates these.
2495 const llvm::APInt &getSize() const { return Size; }
2496 bool isSugared() const { return false; }
2497 QualType desugar() const { return QualType(this, 0); }
2500 /// \brief Determine the number of bits required to address a member of
2501 // an array with the given element type and number of elements.
2502 static unsigned getNumAddressingBits(ASTContext &Context,
2503 QualType ElementType,
2504 const llvm::APInt &NumElements);
2506 /// \brief Determine the maximum number of active bits that an array's size
2507 /// can require, which limits the maximum size of the array.
2508 static unsigned getMaxSizeBits(ASTContext &Context);
2510 void Profile(llvm::FoldingSetNodeID &ID) {
2511 Profile(ID, getElementType(), getSize(),
2512 getSizeModifier(), getIndexTypeCVRQualifiers());
2514 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2515 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2516 unsigned TypeQuals) {
2517 ID.AddPointer(ET.getAsOpaquePtr());
2518 ID.AddInteger(ArraySize.getZExtValue());
2519 ID.AddInteger(SizeMod);
2520 ID.AddInteger(TypeQuals);
2522 static bool classof(const Type *T) {
2523 return T->getTypeClass() == ConstantArray;
2527 /// Represents a C array with an unspecified size. For example 'int A[]' has
2528 /// an IncompleteArrayType where the element type is 'int' and the size is
2530 class IncompleteArrayType : public ArrayType {
2532 IncompleteArrayType(QualType et, QualType can,
2533 ArraySizeModifier sm, unsigned tq)
2534 : ArrayType(IncompleteArray, et, can, sm, tq,
2535 et->containsUnexpandedParameterPack()) {}
2536 friend class ASTContext; // ASTContext creates these.
2538 bool isSugared() const { return false; }
2539 QualType desugar() const { return QualType(this, 0); }
2541 static bool classof(const Type *T) {
2542 return T->getTypeClass() == IncompleteArray;
2545 friend class StmtIteratorBase;
2547 void Profile(llvm::FoldingSetNodeID &ID) {
2548 Profile(ID, getElementType(), getSizeModifier(),
2549 getIndexTypeCVRQualifiers());
2552 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2553 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2554 ID.AddPointer(ET.getAsOpaquePtr());
2555 ID.AddInteger(SizeMod);
2556 ID.AddInteger(TypeQuals);
2560 /// Represents a C array with a specified size that is not an
2561 /// integer-constant-expression. For example, 'int s[x+foo()]'.
2562 /// Since the size expression is an arbitrary expression, we store it as such.
2564 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2565 /// should not be: two lexically equivalent variable array types could mean
2566 /// different things, for example, these variables do not have the same type
2569 /// void foo(int x) {
2575 class VariableArrayType : public ArrayType {
2576 /// An assignment-expression. VLA's are only permitted within
2577 /// a function block.
2579 /// The range spanned by the left and right array brackets.
2580 SourceRange Brackets;
2582 VariableArrayType(QualType et, QualType can, Expr *e,
2583 ArraySizeModifier sm, unsigned tq,
2584 SourceRange brackets)
2585 : ArrayType(VariableArray, et, can, sm, tq,
2586 et->containsUnexpandedParameterPack()),
2587 SizeExpr((Stmt*) e), Brackets(brackets) {}
2588 friend class ASTContext; // ASTContext creates these.
2591 Expr *getSizeExpr() const {
2592 // We use C-style casts instead of cast<> here because we do not wish
2593 // to have a dependency of Type.h on Stmt.h/Expr.h.
2594 return (Expr*) SizeExpr;
2596 SourceRange getBracketsRange() const { return Brackets; }
2597 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2598 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2600 bool isSugared() const { return false; }
2601 QualType desugar() const { return QualType(this, 0); }
2603 static bool classof(const Type *T) {
2604 return T->getTypeClass() == VariableArray;
2607 friend class StmtIteratorBase;
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 llvm_unreachable("Cannot unique VariableArrayTypes.");
2614 /// Represents an array type in C++ whose size is a value-dependent expression.
2618 /// template<typename T, int Size>
2624 /// For these types, we won't actually know what the array bound is
2625 /// until template instantiation occurs, at which point this will
2626 /// become either a ConstantArrayType or a VariableArrayType.
2627 class DependentSizedArrayType : public ArrayType {
2628 const ASTContext &Context;
2630 /// \brief An assignment expression that will instantiate to the
2631 /// size of the array.
2633 /// The expression itself might be null, in which case the array
2634 /// type will have its size deduced from an initializer.
2637 /// The range spanned by the left and right array brackets.
2638 SourceRange Brackets;
2640 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2641 Expr *e, ArraySizeModifier sm, unsigned tq,
2642 SourceRange brackets);
2644 friend class ASTContext; // ASTContext creates these.
2647 Expr *getSizeExpr() const {
2648 // We use C-style casts instead of cast<> here because we do not wish
2649 // to have a dependency of Type.h on Stmt.h/Expr.h.
2650 return (Expr*) SizeExpr;
2652 SourceRange getBracketsRange() const { return Brackets; }
2653 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2654 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2656 bool isSugared() const { return false; }
2657 QualType desugar() const { return QualType(this, 0); }
2659 static bool classof(const Type *T) {
2660 return T->getTypeClass() == DependentSizedArray;
2663 friend class StmtIteratorBase;
2666 void Profile(llvm::FoldingSetNodeID &ID) {
2667 Profile(ID, Context, getElementType(),
2668 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2671 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2672 QualType ET, ArraySizeModifier SizeMod,
2673 unsigned TypeQuals, Expr *E);
2676 /// Represents an extended vector type where either the type or size is
2681 /// template<typename T, int Size>
2683 /// typedef T __attribute__((ext_vector_type(Size))) type;
2686 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2687 const ASTContext &Context;
2689 /// The element type of the array.
2690 QualType ElementType;
2693 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2694 QualType can, Expr *SizeExpr, SourceLocation loc);
2696 friend class ASTContext;
2699 Expr *getSizeExpr() const { return SizeExpr; }
2700 QualType getElementType() const { return ElementType; }
2701 SourceLocation getAttributeLoc() const { return loc; }
2703 bool isSugared() const { return false; }
2704 QualType desugar() const { return QualType(this, 0); }
2706 static bool classof(const Type *T) {
2707 return T->getTypeClass() == DependentSizedExtVector;
2710 void Profile(llvm::FoldingSetNodeID &ID) {
2711 Profile(ID, Context, getElementType(), getSizeExpr());
2714 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2715 QualType ElementType, Expr *SizeExpr);
2719 /// Represents a GCC generic vector type. This type is created using
2720 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
2721 /// bytes; or from an Altivec __vector or vector declaration.
2722 /// Since the constructor takes the number of vector elements, the
2723 /// client is responsible for converting the size into the number of elements.
2724 class VectorType : public Type, public llvm::FoldingSetNode {
2727 GenericVector, ///< not a target-specific vector type
2728 AltiVecVector, ///< is AltiVec vector
2729 AltiVecPixel, ///< is AltiVec 'vector Pixel'
2730 AltiVecBool, ///< is AltiVec 'vector bool ...'
2731 NeonVector, ///< is ARM Neon vector
2732 NeonPolyVector ///< is ARM Neon polynomial vector
2735 /// The element type of the vector.
2736 QualType ElementType;
2738 VectorType(QualType vecType, unsigned nElements, QualType canonType,
2739 VectorKind vecKind);
2741 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2742 QualType canonType, VectorKind vecKind);
2744 friend class ASTContext; // ASTContext creates these.
2748 QualType getElementType() const { return ElementType; }
2749 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2750 static bool isVectorSizeTooLarge(unsigned NumElements) {
2751 return NumElements > VectorTypeBitfields::MaxNumElements;
2754 bool isSugared() const { return false; }
2755 QualType desugar() const { return QualType(this, 0); }
2757 VectorKind getVectorKind() const {
2758 return VectorKind(VectorTypeBits.VecKind);
2761 void Profile(llvm::FoldingSetNodeID &ID) {
2762 Profile(ID, getElementType(), getNumElements(),
2763 getTypeClass(), getVectorKind());
2765 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2766 unsigned NumElements, TypeClass TypeClass,
2767 VectorKind VecKind) {
2768 ID.AddPointer(ElementType.getAsOpaquePtr());
2769 ID.AddInteger(NumElements);
2770 ID.AddInteger(TypeClass);
2771 ID.AddInteger(VecKind);
2774 static bool classof(const Type *T) {
2775 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2779 /// ExtVectorType - Extended vector type. This type is created using
2780 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2781 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2782 /// class enables syntactic extensions, like Vector Components for accessing
2783 /// points, colors, and textures (modeled after OpenGL Shading Language).
2784 class ExtVectorType : public VectorType {
2785 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2786 VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2787 friend class ASTContext; // ASTContext creates these.
2789 static int getPointAccessorIdx(char c) {
2798 static int getNumericAccessorIdx(char c) {
2812 case 'a': return 10;
2814 case 'b': return 11;
2816 case 'c': return 12;
2818 case 'd': return 13;
2820 case 'e': return 14;
2822 case 'f': return 15;
2826 static int getAccessorIdx(char c) {
2827 if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2828 return getNumericAccessorIdx(c);
2831 bool isAccessorWithinNumElements(char c) const {
2832 if (int idx = getAccessorIdx(c)+1)
2833 return unsigned(idx-1) < getNumElements();
2836 bool isSugared() const { return false; }
2837 QualType desugar() const { return QualType(this, 0); }
2839 static bool classof(const Type *T) {
2840 return T->getTypeClass() == ExtVector;
2844 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
2845 /// class of FunctionNoProtoType and FunctionProtoType.
2847 class FunctionType : public Type {
2848 // The type returned by the function.
2849 QualType ResultType;
2852 /// A class which abstracts out some details necessary for
2855 /// It is not actually used directly for storing this information in
2856 /// a FunctionType, although FunctionType does currently use the
2857 /// same bit-pattern.
2859 // If you add a field (say Foo), other than the obvious places (both,
2860 // constructors, compile failures), what you need to update is
2864 // * functionType. Add Foo, getFoo.
2865 // * ASTContext::getFooType
2866 // * ASTContext::mergeFunctionTypes
2867 // * FunctionNoProtoType::Profile
2868 // * FunctionProtoType::Profile
2869 // * TypePrinter::PrintFunctionProto
2870 // * AST read and write
2873 // Feel free to rearrange or add bits, but if you go over 9,
2874 // you'll need to adjust both the Bits field below and
2875 // Type::FunctionTypeBitfields.
2877 // | CC |noreturn|produces|regparm|
2878 // |0 .. 3| 4 | 5 | 6 .. 8|
2880 // regparm is either 0 (no regparm attribute) or the regparm value+1.
2881 enum { CallConvMask = 0xF };
2882 enum { NoReturnMask = 0x10 };
2883 enum { ProducesResultMask = 0x20 };
2884 enum { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2885 RegParmOffset = 6 }; // Assumed to be the last field
2889 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2891 friend class FunctionType;
2894 // Constructor with no defaults. Use this when you know that you
2895 // have all the elements (when reading an AST file for example).
2896 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2897 bool producesResult) {
2898 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2899 Bits = ((unsigned) cc) |
2900 (noReturn ? NoReturnMask : 0) |
2901 (producesResult ? ProducesResultMask : 0) |
2902 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2905 // Constructor with all defaults. Use when for example creating a
2906 // function known to use defaults.
2907 ExtInfo() : Bits(CC_C) { }
2909 // Constructor with just the calling convention, which is an important part
2910 // of the canonical type.
2911 ExtInfo(CallingConv CC) : Bits(CC) { }
2913 bool getNoReturn() const { return Bits & NoReturnMask; }
2914 bool getProducesResult() const { return Bits & ProducesResultMask; }
2915 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2916 unsigned getRegParm() const {
2917 unsigned RegParm = Bits >> RegParmOffset;
2922 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2924 bool operator==(ExtInfo Other) const {
2925 return Bits == Other.Bits;
2927 bool operator!=(ExtInfo Other) const {
2928 return Bits != Other.Bits;
2931 // Note that we don't have setters. That is by design, use
2932 // the following with methods instead of mutating these objects.
2934 ExtInfo withNoReturn(bool noReturn) const {
2936 return ExtInfo(Bits | NoReturnMask);
2938 return ExtInfo(Bits & ~NoReturnMask);
2941 ExtInfo withProducesResult(bool producesResult) const {
2943 return ExtInfo(Bits | ProducesResultMask);
2945 return ExtInfo(Bits & ~ProducesResultMask);
2948 ExtInfo withRegParm(unsigned RegParm) const {
2949 assert(RegParm < 7 && "Invalid regparm value");
2950 return ExtInfo((Bits & ~RegParmMask) |
2951 ((RegParm + 1) << RegParmOffset));
2954 ExtInfo withCallingConv(CallingConv cc) const {
2955 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2958 void Profile(llvm::FoldingSetNodeID &ID) const {
2959 ID.AddInteger(Bits);
2964 FunctionType(TypeClass tc, QualType res,
2965 QualType Canonical, bool Dependent,
2966 bool InstantiationDependent,
2967 bool VariablyModified, bool ContainsUnexpandedParameterPack,
2969 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
2970 ContainsUnexpandedParameterPack),
2972 FunctionTypeBits.ExtInfo = Info.Bits;
2974 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2977 QualType getReturnType() const { return ResultType; }
2979 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2980 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2981 /// Determine whether this function type includes the GNU noreturn
2982 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
2984 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2985 CallingConv getCallConv() const { return getExtInfo().getCC(); }
2986 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2987 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
2988 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
2989 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
2991 /// \brief Determine the type of an expression that calls a function of
2993 QualType getCallResultType(ASTContext &Context) const {
2994 return getReturnType().getNonLValueExprType(Context);
2997 static StringRef getNameForCallConv(CallingConv CC);
2999 static bool classof(const Type *T) {
3000 return T->getTypeClass() == FunctionNoProto ||
3001 T->getTypeClass() == FunctionProto;
3005 /// Represents a K&R-style 'int foo()' function, which has
3006 /// no information available about its arguments.
3007 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3008 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3009 : FunctionType(FunctionNoProto, Result, Canonical,
3010 /*Dependent=*/false, /*InstantiationDependent=*/false,
3011 Result->isVariablyModifiedType(),
3012 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3014 friend class ASTContext; // ASTContext creates these.
3017 // No additional state past what FunctionType provides.
3019 bool isSugared() const { return false; }
3020 QualType desugar() const { return QualType(this, 0); }
3022 void Profile(llvm::FoldingSetNodeID &ID) {
3023 Profile(ID, getReturnType(), getExtInfo());
3025 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3028 ID.AddPointer(ResultType.getAsOpaquePtr());
3031 static bool classof(const Type *T) {
3032 return T->getTypeClass() == FunctionNoProto;
3036 /// Represents a prototype with parameter type info, e.g.
3037 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3038 /// parameters, not as having a single void parameter. Such a type can have an
3039 /// exception specification, but this specification is not part of the canonical
3041 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3043 struct ExceptionSpecInfo {
3045 : Type(EST_None), NoexceptExpr(nullptr),
3046 SourceDecl(nullptr), SourceTemplate(nullptr) {}
3048 ExceptionSpecInfo(ExceptionSpecificationType EST)
3049 : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
3050 SourceTemplate(nullptr) {}
3052 /// The kind of exception specification this is.
3053 ExceptionSpecificationType Type;
3054 /// Explicitly-specified list of exception types.
3055 ArrayRef<QualType> Exceptions;
3056 /// Noexcept expression, if this is EST_ComputedNoexcept.
3058 /// The function whose exception specification this is, for
3059 /// EST_Unevaluated and EST_Uninstantiated.
3060 FunctionDecl *SourceDecl;
3061 /// The function template whose exception specification this is instantiated
3062 /// from, for EST_Uninstantiated.
3063 FunctionDecl *SourceTemplate;
3066 /// Extra information about a function prototype.
3067 struct ExtProtoInfo {
3069 : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3070 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
3072 ExtProtoInfo(CallingConv CC)
3073 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3074 RefQualifier(RQ_None), ConsumedParameters(nullptr) {}
3076 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3077 ExtProtoInfo Result(*this);
3078 Result.ExceptionSpec = O;
3082 FunctionType::ExtInfo ExtInfo;
3084 bool HasTrailingReturn : 1;
3085 unsigned char TypeQuals;
3086 RefQualifierKind RefQualifier;
3087 ExceptionSpecInfo ExceptionSpec;
3088 const bool *ConsumedParameters;
3092 /// \brief Determine whether there are any argument types that
3093 /// contain an unexpanded parameter pack.
3094 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3096 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3097 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3103 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3104 QualType canonical, const ExtProtoInfo &epi);
3106 /// The number of parameters this function has, not counting '...'.
3107 unsigned NumParams : 15;
3109 /// The number of types in the exception spec, if any.
3110 unsigned NumExceptions : 9;
3112 /// The type of exception specification this function has.
3113 unsigned ExceptionSpecType : 4;
3115 /// Whether this function has any consumed parameters.
3116 unsigned HasAnyConsumedParams : 1;
3118 /// Whether the function is variadic.
3119 unsigned Variadic : 1;
3121 /// Whether this function has a trailing return type.
3122 unsigned HasTrailingReturn : 1;
3124 // ParamInfo - There is an variable size array after the class in memory that
3125 // holds the parameter types.
3127 // Exceptions - There is another variable size array after ArgInfo that
3128 // holds the exception types.
3130 // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3131 // to the expression in the noexcept() specifier.
3133 // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3134 // be a pair of FunctionDecl* pointing to the function which should be used to
3135 // instantiate this function type's exception specification, and the function
3136 // from which it should be instantiated.
3138 // ConsumedParameters - A variable size array, following Exceptions
3139 // and of length NumParams, holding flags indicating which parameters
3140 // are consumed. This only appears if HasAnyConsumedParams is true.
3142 friend class ASTContext; // ASTContext creates these.
3144 const bool *getConsumedParamsBuffer() const {
3145 assert(hasAnyConsumedParams());
3147 // Find the end of the exceptions.
3148 Expr *const *eh_end = reinterpret_cast<Expr *const *>(exception_end());
3149 if (getExceptionSpecType() == EST_ComputedNoexcept)
3150 eh_end += 1; // NoexceptExpr
3151 // The memory layout of these types isn't handled here, so
3152 // hopefully this is never called for them?
3153 assert(getExceptionSpecType() != EST_Uninstantiated &&
3154 getExceptionSpecType() != EST_Unevaluated);
3156 return reinterpret_cast<const bool*>(eh_end);
3160 unsigned getNumParams() const { return NumParams; }
3161 QualType getParamType(unsigned i) const {
3162 assert(i < NumParams && "invalid parameter index");
3163 return param_type_begin()[i];
3165 ArrayRef<QualType> getParamTypes() const {
3166 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3169 ExtProtoInfo getExtProtoInfo() const {
3171 EPI.ExtInfo = getExtInfo();
3172 EPI.Variadic = isVariadic();
3173 EPI.HasTrailingReturn = hasTrailingReturn();
3174 EPI.ExceptionSpec.Type = getExceptionSpecType();
3175 EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3176 EPI.RefQualifier = getRefQualifier();
3177 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3178 EPI.ExceptionSpec.Exceptions = exceptions();
3179 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3180 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3181 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3182 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3183 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3184 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3185 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3187 if (hasAnyConsumedParams())
3188 EPI.ConsumedParameters = getConsumedParamsBuffer();
3192 /// Get the kind of exception specification on this function.
3193 ExceptionSpecificationType getExceptionSpecType() const {
3194 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3196 /// Return whether this function has any kind of exception spec.
3197 bool hasExceptionSpec() const {
3198 return getExceptionSpecType() != EST_None;
3200 /// Return whether this function has a dynamic (throw) exception spec.
3201 bool hasDynamicExceptionSpec() const {
3202 return isDynamicExceptionSpec(getExceptionSpecType());
3204 /// Return whether this function has a noexcept exception spec.
3205 bool hasNoexceptExceptionSpec() const {
3206 return isNoexceptExceptionSpec(getExceptionSpecType());
3208 /// Return whether this function has a dependent exception spec.
3209 bool hasDependentExceptionSpec() const;
3210 /// Result type of getNoexceptSpec().
3211 enum NoexceptResult {
3212 NR_NoNoexcept, ///< There is no noexcept specifier.
3213 NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3214 NR_Dependent, ///< The noexcept specifier is dependent.
3215 NR_Throw, ///< The noexcept specifier evaluates to false.
3216 NR_Nothrow ///< The noexcept specifier evaluates to true.
3218 /// Get the meaning of the noexcept spec on this function, if any.
3219 NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3220 unsigned getNumExceptions() const { return NumExceptions; }
3221 QualType getExceptionType(unsigned i) const {
3222 assert(i < NumExceptions && "Invalid exception number!");
3223 return exception_begin()[i];
3225 Expr *getNoexceptExpr() const {
3226 if (getExceptionSpecType() != EST_ComputedNoexcept)
3228 // NoexceptExpr sits where the arguments end.
3229 return *reinterpret_cast<Expr *const *>(param_type_end());
3231 /// \brief If this function type has an exception specification which hasn't
3232 /// been determined yet (either because it has not been evaluated or because
3233 /// it has not been instantiated), this is the function whose exception
3234 /// specification is represented by this type.
3235 FunctionDecl *getExceptionSpecDecl() const {
3236 if (getExceptionSpecType() != EST_Uninstantiated &&
3237 getExceptionSpecType() != EST_Unevaluated)
3239 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3241 /// \brief If this function type has an uninstantiated exception
3242 /// specification, this is the function whose exception specification
3243 /// should be instantiated to find the exception specification for
3245 FunctionDecl *getExceptionSpecTemplate() const {
3246 if (getExceptionSpecType() != EST_Uninstantiated)
3248 return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3250 /// Determine whether this function type has a non-throwing exception
3251 /// specification. If this depends on template arguments, returns
3252 /// \c ResultIfDependent.
3253 bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const;
3255 bool isVariadic() const { return Variadic; }
3257 /// Determines whether this function prototype contains a
3258 /// parameter pack at the end.
3260 /// A function template whose last parameter is a parameter pack can be
3261 /// called with an arbitrary number of arguments, much like a variadic
3263 bool isTemplateVariadic() const;
3265 bool hasTrailingReturn() const { return HasTrailingReturn; }
3267 unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3270 /// Retrieve the ref-qualifier associated with this function type.
3271 RefQualifierKind getRefQualifier() const {
3272 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3275 typedef const QualType *param_type_iterator;
3276 typedef llvm::iterator_range<param_type_iterator> param_type_range;
3278 param_type_range param_types() const {
3279 return param_type_range(param_type_begin(), param_type_end());
3281 param_type_iterator param_type_begin() const {
3282 return reinterpret_cast<const QualType *>(this+1);
3284 param_type_iterator param_type_end() const {
3285 return param_type_begin() + NumParams;
3288 typedef const QualType *exception_iterator;
3290 ArrayRef<QualType> exceptions() const {
3291 return llvm::makeArrayRef(exception_begin(), exception_end());
3293 exception_iterator exception_begin() const {
3294 // exceptions begin where arguments end
3295 return param_type_end();
3297 exception_iterator exception_end() const {
3298 if (getExceptionSpecType() != EST_Dynamic)
3299 return exception_begin();
3300 return exception_begin() + NumExceptions;
3303 bool hasAnyConsumedParams() const { return HasAnyConsumedParams; }
3304 bool isParamConsumed(unsigned I) const {
3305 assert(I < getNumParams() && "parameter index out of range");
3306 if (hasAnyConsumedParams())
3307 return getConsumedParamsBuffer()[I];
3311 bool isSugared() const { return false; }
3312 QualType desugar() const { return QualType(this, 0); }
3314 void printExceptionSpecification(raw_ostream &OS,
3315 const PrintingPolicy &Policy) const;
3317 static bool classof(const Type *T) {
3318 return T->getTypeClass() == FunctionProto;
3321 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3322 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3323 param_type_iterator ArgTys, unsigned NumArgs,
3324 const ExtProtoInfo &EPI, const ASTContext &Context);
3327 /// \brief Represents the dependent type named by a dependently-scoped
3328 /// typename using declaration, e.g.
3329 /// using typename Base<T>::foo;
3331 /// Template instantiation turns these into the underlying type.
3332 class UnresolvedUsingType : public Type {
3333 UnresolvedUsingTypenameDecl *Decl;
3335 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3336 : Type(UnresolvedUsing, QualType(), true, true, false,
3337 /*ContainsUnexpandedParameterPack=*/false),
3338 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3339 friend class ASTContext; // ASTContext creates these.
3342 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3344 bool isSugared() const { return false; }
3345 QualType desugar() const { return QualType(this, 0); }
3347 static bool classof(const Type *T) {
3348 return T->getTypeClass() == UnresolvedUsing;
3351 void Profile(llvm::FoldingSetNodeID &ID) {
3352 return Profile(ID, Decl);
3354 static void Profile(llvm::FoldingSetNodeID &ID,
3355 UnresolvedUsingTypenameDecl *D) {
3361 class TypedefType : public Type {
3362 TypedefNameDecl *Decl;
3364 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3365 : Type(tc, can, can->isDependentType(),
3366 can->isInstantiationDependentType(),
3367 can->isVariablyModifiedType(),
3368 /*ContainsUnexpandedParameterPack=*/false),
3369 Decl(const_cast<TypedefNameDecl*>(D)) {
3370 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3372 friend class ASTContext; // ASTContext creates these.
3375 TypedefNameDecl *getDecl() const { return Decl; }
3377 bool isSugared() const { return true; }
3378 QualType desugar() const;
3380 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3383 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3384 class TypeOfExprType : public Type {
3388 TypeOfExprType(Expr *E, QualType can = QualType());
3389 friend class ASTContext; // ASTContext creates these.
3391 Expr *getUnderlyingExpr() const { return TOExpr; }
3393 /// \brief Remove a single level of sugar.
3394 QualType desugar() const;
3396 /// \brief Returns whether this type directly provides sugar.
3397 bool isSugared() const;
3399 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3402 /// \brief Internal representation of canonical, dependent
3403 /// `typeof(expr)` types.
3405 /// This class is used internally by the ASTContext to manage
3406 /// canonical, dependent types, only. Clients will only see instances
3407 /// of this class via TypeOfExprType nodes.
3408 class DependentTypeOfExprType
3409 : public TypeOfExprType, public llvm::FoldingSetNode {
3410 const ASTContext &Context;
3413 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3414 : TypeOfExprType(E), Context(Context) { }
3416 void Profile(llvm::FoldingSetNodeID &ID) {
3417 Profile(ID, Context, getUnderlyingExpr());
3420 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3424 /// Represents `typeof(type)`, a GCC extension.
3425 class TypeOfType : public Type {
3427 TypeOfType(QualType T, QualType can)
3428 : Type(TypeOf, can, T->isDependentType(),
3429 T->isInstantiationDependentType(),
3430 T->isVariablyModifiedType(),
3431 T->containsUnexpandedParameterPack()),
3433 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3435 friend class ASTContext; // ASTContext creates these.
3437 QualType getUnderlyingType() const { return TOType; }
3439 /// \brief Remove a single level of sugar.
3440 QualType desugar() const { return getUnderlyingType(); }
3442 /// \brief Returns whether this type directly provides sugar.
3443 bool isSugared() const { return true; }
3445 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3448 /// Represents the type `decltype(expr)` (C++11).
3449 class DecltypeType : public Type {
3451 QualType UnderlyingType;
3454 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3455 friend class ASTContext; // ASTContext creates these.
3457 Expr *getUnderlyingExpr() const { return E; }
3458 QualType getUnderlyingType() const { return UnderlyingType; }
3460 /// \brief Remove a single level of sugar.
3461 QualType desugar() const;
3463 /// \brief Returns whether this type directly provides sugar.
3464 bool isSugared() const;
3466 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3469 /// \brief Internal representation of canonical, dependent
3470 /// decltype(expr) types.
3472 /// This class is used internally by the ASTContext to manage
3473 /// canonical, dependent types, only. Clients will only see instances
3474 /// of this class via DecltypeType nodes.
3475 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3476 const ASTContext &Context;
3479 DependentDecltypeType(const ASTContext &Context, Expr *E);
3481 void Profile(llvm::FoldingSetNodeID &ID) {
3482 Profile(ID, Context, getUnderlyingExpr());
3485 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3489 /// A unary type transform, which is a type constructed from another.
3490 class UnaryTransformType : public Type {
3497 /// The untransformed type.
3499 /// The transformed type if not dependent, otherwise the same as BaseType.
3500 QualType UnderlyingType;
3504 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3505 QualType CanonicalTy);
3506 friend class ASTContext;
3508 bool isSugared() const { return !isDependentType(); }
3509 QualType desugar() const { return UnderlyingType; }
3511 QualType getUnderlyingType() const { return UnderlyingType; }
3512 QualType getBaseType() const { return BaseType; }
3514 UTTKind getUTTKind() const { return UKind; }
3516 static bool classof(const Type *T) {
3517 return T->getTypeClass() == UnaryTransform;
3521 class TagType : public Type {
3522 /// Stores the TagDecl associated with this type. The decl may point to any
3523 /// TagDecl that declares the entity.
3526 friend class ASTReader;
3529 TagType(TypeClass TC, const TagDecl *D, QualType can);
3532 TagDecl *getDecl() const;
3534 /// Determines whether this type is in the process of being defined.
3535 bool isBeingDefined() const;
3537 static bool classof(const Type *T) {
3538 return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3542 /// A helper class that allows the use of isa/cast/dyncast
3543 /// to detect TagType objects of structs/unions/classes.
3544 class RecordType : public TagType {
3546 explicit RecordType(const RecordDecl *D)
3547 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3548 explicit RecordType(TypeClass TC, RecordDecl *D)
3549 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3550 friend class ASTContext; // ASTContext creates these.
3553 RecordDecl *getDecl() const {
3554 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3557 // FIXME: This predicate is a helper to QualType/Type. It needs to
3558 // recursively check all fields for const-ness. If any field is declared
3559 // const, it needs to return false.
3560 bool hasConstFields() const { return false; }
3562 bool isSugared() const { return false; }
3563 QualType desugar() const { return QualType(this, 0); }
3565 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3568 /// A helper class that allows the use of isa/cast/dyncast
3569 /// to detect TagType objects of enums.
3570 class EnumType : public TagType {
3571 explicit EnumType(const EnumDecl *D)
3572 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3573 friend class ASTContext; // ASTContext creates these.
3576 EnumDecl *getDecl() const {
3577 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3580 bool isSugared() const { return false; }
3581 QualType desugar() const { return QualType(this, 0); }
3583 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3586 /// An attributed type is a type to which a type attribute has been applied.
3588 /// The "modified type" is the fully-sugared type to which the attributed
3589 /// type was applied; generally it is not canonically equivalent to the
3590 /// attributed type. The "equivalent type" is the minimally-desugared type
3591 /// which the type is canonically equivalent to.
3593 /// For example, in the following attributed type:
3594 /// int32_t __attribute__((vector_size(16)))
3595 /// - the modified type is the TypedefType for int32_t
3596 /// - the equivalent type is VectorType(16, int32_t)
3597 /// - the canonical type is VectorType(16, int)
3598 class AttributedType : public Type, public llvm::FoldingSetNode {
3600 // It is really silly to have yet another attribute-kind enum, but
3601 // clang::attr::Kind doesn't currently cover the pure type attrs.
3603 // Expression operand.
3607 attr_neon_vector_type,
3608 attr_neon_polyvector_type,
3610 FirstExprOperandKind = attr_address_space,
3611 LastExprOperandKind = attr_neon_polyvector_type,
3613 // Enumerated operand (string or keyword).
3615 attr_objc_ownership,
3619 FirstEnumOperandKind = attr_objc_gc,
3620 LastEnumOperandKind = attr_pcs_vfp,
3639 attr_null_unspecified,
3641 attr_objc_inert_unsafe_unretained,
3645 QualType ModifiedType;
3646 QualType EquivalentType;
3648 friend class ASTContext; // creates these
3650 AttributedType(QualType canon, Kind attrKind,
3651 QualType modified, QualType equivalent)
3652 : Type(Attributed, canon, canon->isDependentType(),
3653 canon->isInstantiationDependentType(),
3654 canon->isVariablyModifiedType(),
3655 canon->containsUnexpandedParameterPack()),
3656 ModifiedType(modified), EquivalentType(equivalent) {
3657 AttributedTypeBits.AttrKind = attrKind;
3661 Kind getAttrKind() const {
3662 return static_cast<Kind>(AttributedTypeBits.AttrKind);
3665 QualType getModifiedType() const { return ModifiedType; }
3666 QualType getEquivalentType() const { return EquivalentType; }
3668 bool isSugared() const { return true; }
3669 QualType desugar() const { return getEquivalentType(); }
3671 /// Does this attribute behave like a type qualifier?
3673 /// A type qualifier adjusts a type to provide specialized rules for
3674 /// a specific object, like the standard const and volatile qualifiers.
3675 /// This includes attributes controlling things like nullability,
3676 /// address spaces, and ARC ownership. The value of the object is still
3677 /// largely described by the modified type.
3679 /// In contrast, many type attributes "rewrite" their modified type to
3680 /// produce a fundamentally different type, not necessarily related in any
3681 /// formalizable way to the original type. For example, calling convention
3682 /// and vector attributes are not simple type qualifiers.
3684 /// Type qualifiers are often, but not always, reflected in the canonical
3686 bool isQualifier() const;
3688 bool isMSTypeSpec() const;
3690 bool isCallingConv() const;
3692 llvm::Optional<NullabilityKind> getImmediateNullability() const;
3694 /// Retrieve the attribute kind corresponding to the given
3695 /// nullability kind.
3696 static Kind getNullabilityAttrKind(NullabilityKind kind) {
3698 case NullabilityKind::NonNull:
3699 return attr_nonnull;
3701 case NullabilityKind::Nullable:
3702 return attr_nullable;
3704 case NullabilityKind::Unspecified:
3705 return attr_null_unspecified;
3707 llvm_unreachable("Unknown nullability kind.");
3710 /// Strip off the top-level nullability annotation on the given
3711 /// type, if it's there.
3713 /// \param T The type to strip. If the type is exactly an
3714 /// AttributedType specifying nullability (without looking through
3715 /// type sugar), the nullability is returned and this type changed
3716 /// to the underlying modified type.
3718 /// \returns the top-level nullability, if present.
3719 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
3721 void Profile(llvm::FoldingSetNodeID &ID) {
3722 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3725 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3726 QualType modified, QualType equivalent) {
3727 ID.AddInteger(attrKind);
3728 ID.AddPointer(modified.getAsOpaquePtr());
3729 ID.AddPointer(equivalent.getAsOpaquePtr());
3732 static bool classof(const Type *T) {
3733 return T->getTypeClass() == Attributed;
3737 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3738 // Helper data collector for canonical types.
3739 struct CanonicalTTPTInfo {
3740 unsigned Depth : 15;
3741 unsigned ParameterPack : 1;
3742 unsigned Index : 16;
3746 // Info for the canonical type.
3747 CanonicalTTPTInfo CanTTPTInfo;
3748 // Info for the non-canonical type.
3749 TemplateTypeParmDecl *TTPDecl;
3752 /// Build a non-canonical type.
3753 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3754 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3755 /*InstantiationDependent=*/true,
3756 /*VariablyModified=*/false,
3757 Canon->containsUnexpandedParameterPack()),
3758 TTPDecl(TTPDecl) { }
3760 /// Build the canonical type.
3761 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3762 : Type(TemplateTypeParm, QualType(this, 0),
3764 /*InstantiationDependent=*/true,
3765 /*VariablyModified=*/false, PP) {
3766 CanTTPTInfo.Depth = D;
3767 CanTTPTInfo.Index = I;
3768 CanTTPTInfo.ParameterPack = PP;
3771 friend class ASTContext; // ASTContext creates these
3773 const CanonicalTTPTInfo& getCanTTPTInfo() const {
3774 QualType Can = getCanonicalTypeInternal();
3775 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3779 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3780 unsigned getIndex() const { return getCanTTPTInfo().Index; }
3781 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3783 TemplateTypeParmDecl *getDecl() const {
3784 return isCanonicalUnqualified() ? nullptr : TTPDecl;
3787 IdentifierInfo *getIdentifier() const;
3789 bool isSugared() const { return false; }
3790 QualType desugar() const { return QualType(this, 0); }
3792 void Profile(llvm::FoldingSetNodeID &ID) {
3793 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3796 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3797 unsigned Index, bool ParameterPack,
3798 TemplateTypeParmDecl *TTPDecl) {
3799 ID.AddInteger(Depth);
3800 ID.AddInteger(Index);
3801 ID.AddBoolean(ParameterPack);
3802 ID.AddPointer(TTPDecl);
3805 static bool classof(const Type *T) {
3806 return T->getTypeClass() == TemplateTypeParm;
3810 /// \brief Represents the result of substituting a type for a template
3813 /// Within an instantiated template, all template type parameters have
3814 /// been replaced with these. They are used solely to record that a
3815 /// type was originally written as a template type parameter;
3816 /// therefore they are never canonical.
3817 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3818 // The original type parameter.
3819 const TemplateTypeParmType *Replaced;
3821 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3822 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3823 Canon->isInstantiationDependentType(),
3824 Canon->isVariablyModifiedType(),
3825 Canon->containsUnexpandedParameterPack()),
3828 friend class ASTContext;
3831 /// Gets the template parameter that was substituted for.
3832 const TemplateTypeParmType *getReplacedParameter() const {
3836 /// Gets the type that was substituted for the template
3838 QualType getReplacementType() const {
3839 return getCanonicalTypeInternal();
3842 bool isSugared() const { return true; }
3843 QualType desugar() const { return getReplacementType(); }
3845 void Profile(llvm::FoldingSetNodeID &ID) {
3846 Profile(ID, getReplacedParameter(), getReplacementType());
3848 static void Profile(llvm::FoldingSetNodeID &ID,
3849 const TemplateTypeParmType *Replaced,
3850 QualType Replacement) {
3851 ID.AddPointer(Replaced);
3852 ID.AddPointer(Replacement.getAsOpaquePtr());
3855 static bool classof(const Type *T) {
3856 return T->getTypeClass() == SubstTemplateTypeParm;
3860 /// \brief Represents the result of substituting a set of types for a template
3861 /// type parameter pack.
3863 /// When a pack expansion in the source code contains multiple parameter packs
3864 /// and those parameter packs correspond to different levels of template
3865 /// parameter lists, this type node is used to represent a template type
3866 /// parameter pack from an outer level, which has already had its argument pack
3867 /// substituted but that still lives within a pack expansion that itself
3868 /// could not be instantiated. When actually performing a substitution into
3869 /// that pack expansion (e.g., when all template parameters have corresponding
3870 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3871 /// at the current pack substitution index.
3872 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3873 /// \brief The original type parameter.
3874 const TemplateTypeParmType *Replaced;
3876 /// \brief A pointer to the set of template arguments that this
3877 /// parameter pack is instantiated with.
3878 const TemplateArgument *Arguments;
3880 /// \brief The number of template arguments in \c Arguments.
3881 unsigned NumArguments;
3883 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3885 const TemplateArgument &ArgPack);
3887 friend class ASTContext;
3890 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3892 /// Gets the template parameter that was substituted for.
3893 const TemplateTypeParmType *getReplacedParameter() const {
3897 bool isSugared() const { return false; }
3898 QualType desugar() const { return QualType(this, 0); }
3900 TemplateArgument getArgumentPack() const;
3902 void Profile(llvm::FoldingSetNodeID &ID);
3903 static void Profile(llvm::FoldingSetNodeID &ID,
3904 const TemplateTypeParmType *Replaced,
3905 const TemplateArgument &ArgPack);
3907 static bool classof(const Type *T) {
3908 return T->getTypeClass() == SubstTemplateTypeParmPack;
3912 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
3914 /// These types are usually a placeholder for a deduced type. However, before
3915 /// the initializer is attached, or if the initializer is type-dependent, there
3916 /// is no deduced type and an auto type is canonical. In the latter case, it is
3917 /// also a dependent type.
3918 class AutoType : public Type, public llvm::FoldingSetNode {
3919 AutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent)
3920 : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3921 /*Dependent=*/IsDependent, /*InstantiationDependent=*/IsDependent,
3922 /*VariablyModified=*/false,
3923 /*ContainsParameterPack=*/DeducedType.isNull()
3924 ? false : DeducedType->containsUnexpandedParameterPack()) {
3925 assert((DeducedType.isNull() || !IsDependent) &&
3926 "auto deduced to dependent type");
3927 AutoTypeBits.Keyword = (unsigned)Keyword;
3930 friend class ASTContext; // ASTContext creates these
3933 bool isDecltypeAuto() const {
3934 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
3936 AutoTypeKeyword getKeyword() const {
3937 return (AutoTypeKeyword)AutoTypeBits.Keyword;
3940 bool isSugared() const { return !isCanonicalUnqualified(); }
3941 QualType desugar() const { return getCanonicalTypeInternal(); }
3943 /// \brief Get the type deduced for this auto type, or null if it's either
3944 /// not been deduced or was deduced to a dependent type.
3945 QualType getDeducedType() const {
3946 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
3948 bool isDeduced() const {
3949 return !isCanonicalUnqualified() || isDependentType();
3952 void Profile(llvm::FoldingSetNodeID &ID) {
3953 Profile(ID, getDeducedType(), getKeyword(), isDependentType());
3956 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
3957 AutoTypeKeyword Keyword, bool IsDependent) {
3958 ID.AddPointer(Deduced.getAsOpaquePtr());
3959 ID.AddInteger((unsigned)Keyword);
3960 ID.AddBoolean(IsDependent);
3963 static bool classof(const Type *T) {
3964 return T->getTypeClass() == Auto;
3968 /// \brief Represents a type template specialization; the template
3969 /// must be a class template, a type alias template, or a template
3970 /// template parameter. A template which cannot be resolved to one of
3971 /// these, e.g. because it is written with a dependent scope
3972 /// specifier, is instead represented as a
3973 /// @c DependentTemplateSpecializationType.
3975 /// A non-dependent template specialization type is always "sugar",
3976 /// typically for a \c RecordType. For example, a class template
3977 /// specialization type of \c vector<int> will refer to a tag type for
3978 /// the instantiation \c std::vector<int, std::allocator<int>>
3980 /// Template specializations are dependent if either the template or
3981 /// any of the template arguments are dependent, in which case the
3982 /// type may also be canonical.
3984 /// Instances of this type are allocated with a trailing array of
3985 /// TemplateArguments, followed by a QualType representing the
3986 /// non-canonical aliased type when the template is a type alias
3988 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
3990 public llvm::FoldingSetNode {
3991 /// The name of the template being specialized. This is
3992 /// either a TemplateName::Template (in which case it is a
3993 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
3994 /// TypeAliasTemplateDecl*), a
3995 /// TemplateName::SubstTemplateTemplateParmPack, or a
3996 /// TemplateName::SubstTemplateTemplateParm (in which case the
3997 /// replacement must, recursively, be one of these).
3998 TemplateName Template;
4000 /// The number of template arguments named in this class template
4002 unsigned NumArgs : 31;
4004 /// Whether this template specialization type is a substituted type alias.
4007 TemplateSpecializationType(TemplateName T,
4008 const TemplateArgument *Args,
4009 unsigned NumArgs, QualType Canon,
4012 friend class ASTContext; // ASTContext creates these
4015 /// Determine whether any of the given template arguments are dependent.
4016 static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
4018 bool &InstantiationDependent);
4020 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4021 bool &InstantiationDependent);
4023 /// \brief Print a template argument list, including the '<' and '>'
4024 /// enclosing the template arguments.
4025 static void PrintTemplateArgumentList(raw_ostream &OS,
4026 const TemplateArgument *Args,
4028 const PrintingPolicy &Policy,
4029 bool SkipBrackets = false);
4031 static void PrintTemplateArgumentList(raw_ostream &OS,
4032 const TemplateArgumentLoc *Args,
4034 const PrintingPolicy &Policy);
4036 static void PrintTemplateArgumentList(raw_ostream &OS,
4037 const TemplateArgumentListInfo &,
4038 const PrintingPolicy &Policy);
4040 /// True if this template specialization type matches a current
4041 /// instantiation in the context in which it is found.
4042 bool isCurrentInstantiation() const {
4043 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4046 /// \brief Determine if this template specialization type is for a type alias
4047 /// template that has been substituted.
4049 /// Nearly every template specialization type whose template is an alias
4050 /// template will be substituted. However, this is not the case when
4051 /// the specialization contains a pack expansion but the template alias
4052 /// does not have a corresponding parameter pack, e.g.,
4055 /// template<typename T, typename U, typename V> struct S;
4056 /// template<typename T, typename U> using A = S<T, int, U>;
4057 /// template<typename... Ts> struct X {
4058 /// typedef A<Ts...> type; // not a type alias
4061 bool isTypeAlias() const { return TypeAlias; }
4063 /// Get the aliased type, if this is a specialization of a type alias
4065 QualType getAliasedType() const {
4066 assert(isTypeAlias() && "not a type alias template specialization");
4067 return *reinterpret_cast<const QualType*>(end());
4070 typedef const TemplateArgument * iterator;
4072 iterator begin() const { return getArgs(); }
4073 iterator end() const; // defined inline in TemplateBase.h
4075 /// Retrieve the name of the template that we are specializing.
4076 TemplateName getTemplateName() const { return Template; }
4078 /// Retrieve the template arguments.
4079 const TemplateArgument *getArgs() const {
4080 return reinterpret_cast<const TemplateArgument *>(this + 1);
4083 /// Retrieve the number of template arguments.
4084 unsigned getNumArgs() const { return NumArgs; }
4086 /// Retrieve a specific template argument as a type.
4087 /// \pre \c isArgType(Arg)
4088 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4090 bool isSugared() const {
4091 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4093 QualType desugar() const { return getCanonicalTypeInternal(); }
4095 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4096 Profile(ID, Template, getArgs(), NumArgs, Ctx);
4098 getAliasedType().Profile(ID);
4101 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4102 const TemplateArgument *Args,
4104 const ASTContext &Context);
4106 static bool classof(const Type *T) {
4107 return T->getTypeClass() == TemplateSpecialization;
4111 /// The injected class name of a C++ class template or class
4112 /// template partial specialization. Used to record that a type was
4113 /// spelled with a bare identifier rather than as a template-id; the
4114 /// equivalent for non-templated classes is just RecordType.
4116 /// Injected class name types are always dependent. Template
4117 /// instantiation turns these into RecordTypes.
4119 /// Injected class name types are always canonical. This works
4120 /// because it is impossible to compare an injected class name type
4121 /// with the corresponding non-injected template type, for the same
4122 /// reason that it is impossible to directly compare template
4123 /// parameters from different dependent contexts: injected class name
4124 /// types can only occur within the scope of a particular templated
4125 /// declaration, and within that scope every template specialization
4126 /// will canonicalize to the injected class name (when appropriate
4127 /// according to the rules of the language).
4128 class InjectedClassNameType : public Type {
4129 CXXRecordDecl *Decl;
4131 /// The template specialization which this type represents.
4133 /// template <class T> class A { ... };
4134 /// this is A<T>, whereas in
4135 /// template <class X, class Y> class A<B<X,Y> > { ... };
4136 /// this is A<B<X,Y> >.
4138 /// It is always unqualified, always a template specialization type,
4139 /// and always dependent.
4140 QualType InjectedType;
4142 friend class ASTContext; // ASTContext creates these.
4143 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4144 // currently suitable for AST reading, too much
4145 // interdependencies.
4146 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4147 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4148 /*InstantiationDependent=*/true,
4149 /*VariablyModified=*/false,
4150 /*ContainsUnexpandedParameterPack=*/false),
4151 Decl(D), InjectedType(TST) {
4152 assert(isa<TemplateSpecializationType>(TST));
4153 assert(!TST.hasQualifiers());
4154 assert(TST->isDependentType());
4158 QualType getInjectedSpecializationType() const { return InjectedType; }
4159 const TemplateSpecializationType *getInjectedTST() const {
4160 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4163 CXXRecordDecl *getDecl() const;
4165 bool isSugared() const { return false; }
4166 QualType desugar() const { return QualType(this, 0); }
4168 static bool classof(const Type *T) {
4169 return T->getTypeClass() == InjectedClassName;
4173 /// \brief The kind of a tag type.
4175 /// \brief The "struct" keyword.
4177 /// \brief The "__interface" keyword.
4179 /// \brief The "union" keyword.
4181 /// \brief The "class" keyword.
4183 /// \brief The "enum" keyword.
4187 /// \brief The elaboration keyword that precedes a qualified type name or
4188 /// introduces an elaborated-type-specifier.
4189 enum ElaboratedTypeKeyword {
4190 /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4192 /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4194 /// \brief The "union" keyword introduces the elaborated-type-specifier.
4196 /// \brief The "class" keyword introduces the elaborated-type-specifier.
4198 /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4200 /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4201 /// \c typename T::type.
4203 /// \brief No keyword precedes the qualified type name.
4207 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4208 /// The keyword in stored in the free bits of the base class.
4209 /// Also provides a few static helpers for converting and printing
4210 /// elaborated type keyword and tag type kind enumerations.
4211 class TypeWithKeyword : public Type {
4213 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4214 QualType Canonical, bool Dependent,
4215 bool InstantiationDependent, bool VariablyModified,
4216 bool ContainsUnexpandedParameterPack)
4217 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4218 ContainsUnexpandedParameterPack) {
4219 TypeWithKeywordBits.Keyword = Keyword;
4223 ElaboratedTypeKeyword getKeyword() const {
4224 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4227 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4228 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4230 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4231 /// It is an error to provide a type specifier which *isn't* a tag kind here.
4232 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4234 /// Converts a TagTypeKind into an elaborated type keyword.
4235 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4237 /// Converts an elaborated type keyword into a TagTypeKind.
4238 /// It is an error to provide an elaborated type keyword
4239 /// which *isn't* a tag kind here.
4240 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4242 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4244 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4246 static StringRef getTagTypeKindName(TagTypeKind Kind) {
4247 return getKeywordName(getKeywordForTagTypeKind(Kind));
4250 class CannotCastToThisType {};
4251 static CannotCastToThisType classof(const Type *);
4254 /// \brief Represents a type that was referred to using an elaborated type
4255 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4258 /// This type is used to keep track of a type name as written in the
4259 /// source code, including tag keywords and any nested-name-specifiers.
4260 /// The type itself is always "sugar", used to express what was written
4261 /// in the source code but containing no additional semantic information.
4262 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4264 /// The nested name specifier containing the qualifier.
4265 NestedNameSpecifier *NNS;
4267 /// The type that this qualified name refers to.
4270 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4271 QualType NamedType, QualType CanonType)
4272 : TypeWithKeyword(Keyword, Elaborated, CanonType,
4273 NamedType->isDependentType(),
4274 NamedType->isInstantiationDependentType(),
4275 NamedType->isVariablyModifiedType(),
4276 NamedType->containsUnexpandedParameterPack()),
4277 NNS(NNS), NamedType(NamedType) {
4278 assert(!(Keyword == ETK_None && NNS == nullptr) &&
4279 "ElaboratedType cannot have elaborated type keyword "
4280 "and name qualifier both null.");
4283 friend class ASTContext; // ASTContext creates these
4288 /// Retrieve the qualification on this type.
4289 NestedNameSpecifier *getQualifier() const { return NNS; }
4291 /// Retrieve the type named by the qualified-id.
4292 QualType getNamedType() const { return NamedType; }
4294 /// Remove a single level of sugar.
4295 QualType desugar() const { return getNamedType(); }
4297 /// Returns whether this type directly provides sugar.
4298 bool isSugared() const { return true; }
4300 void Profile(llvm::FoldingSetNodeID &ID) {
4301 Profile(ID, getKeyword(), NNS, NamedType);
4304 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4305 NestedNameSpecifier *NNS, QualType NamedType) {
4306 ID.AddInteger(Keyword);
4308 NamedType.Profile(ID);
4311 static bool classof(const Type *T) {
4312 return T->getTypeClass() == Elaborated;
4316 /// \brief Represents a qualified type name for which the type name is
4319 /// DependentNameType represents a class of dependent types that involve a
4320 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4321 /// name of a type. The DependentNameType may start with a "typename" (for a
4322 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4323 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4324 /// know that we must be referring to a type, e.g., in a base class specifier).
4325 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4326 /// mode, this type is used with non-dependent names to delay name lookup until
4328 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4330 /// \brief The nested name specifier containing the qualifier.
4331 NestedNameSpecifier *NNS;
4333 /// \brief The type that this typename specifier refers to.
4334 const IdentifierInfo *Name;
4336 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4337 const IdentifierInfo *Name, QualType CanonType)
4338 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4339 /*InstantiationDependent=*/true,
4340 /*VariablyModified=*/false,
4341 NNS->containsUnexpandedParameterPack()),
4342 NNS(NNS), Name(Name) {}
4344 friend class ASTContext; // ASTContext creates these
4347 /// Retrieve the qualification on this type.
4348 NestedNameSpecifier *getQualifier() const { return NNS; }
4350 /// Retrieve the type named by the typename specifier as an identifier.
4352 /// This routine will return a non-NULL identifier pointer when the
4353 /// form of the original typename was terminated by an identifier,
4354 /// e.g., "typename T::type".
4355 const IdentifierInfo *getIdentifier() const {
4359 bool isSugared() const { return false; }
4360 QualType desugar() const { return QualType(this, 0); }
4362 void Profile(llvm::FoldingSetNodeID &ID) {
4363 Profile(ID, getKeyword(), NNS, Name);
4366 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4367 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4368 ID.AddInteger(Keyword);
4370 ID.AddPointer(Name);
4373 static bool classof(const Type *T) {
4374 return T->getTypeClass() == DependentName;
4378 /// Represents a template specialization type whose template cannot be
4380 /// A<T>::template B<T>
4381 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4382 : public TypeWithKeyword,
4383 public llvm::FoldingSetNode {
4385 /// The nested name specifier containing the qualifier.
4386 NestedNameSpecifier *NNS;
4388 /// The identifier of the template.
4389 const IdentifierInfo *Name;
4391 /// \brief The number of template arguments named in this class template
4395 const TemplateArgument *getArgBuffer() const {
4396 return reinterpret_cast<const TemplateArgument*>(this+1);
4398 TemplateArgument *getArgBuffer() {
4399 return reinterpret_cast<TemplateArgument*>(this+1);
4402 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4403 NestedNameSpecifier *NNS,
4404 const IdentifierInfo *Name,
4406 const TemplateArgument *Args,
4409 friend class ASTContext; // ASTContext creates these
4412 NestedNameSpecifier *getQualifier() const { return NNS; }
4413 const IdentifierInfo *getIdentifier() const { return Name; }
4415 /// \brief Retrieve the template arguments.
4416 const TemplateArgument *getArgs() const {
4417 return getArgBuffer();
4420 /// \brief Retrieve the number of template arguments.
4421 unsigned getNumArgs() const { return NumArgs; }
4423 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4425 typedef const TemplateArgument * iterator;
4426 iterator begin() const { return getArgs(); }
4427 iterator end() const; // inline in TemplateBase.h
4429 bool isSugared() const { return false; }
4430 QualType desugar() const { return QualType(this, 0); }
4432 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4433 Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
4436 static void Profile(llvm::FoldingSetNodeID &ID,
4437 const ASTContext &Context,
4438 ElaboratedTypeKeyword Keyword,
4439 NestedNameSpecifier *Qualifier,
4440 const IdentifierInfo *Name,
4442 const TemplateArgument *Args);
4444 static bool classof(const Type *T) {
4445 return T->getTypeClass() == DependentTemplateSpecialization;
4449 /// \brief Represents a pack expansion of types.
4451 /// Pack expansions are part of C++11 variadic templates. A pack
4452 /// expansion contains a pattern, which itself contains one or more
4453 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4454 /// produces a series of types, each instantiated from the pattern of
4455 /// the expansion, where the Ith instantiation of the pattern uses the
4456 /// Ith arguments bound to each of the unexpanded parameter packs. The
4457 /// pack expansion is considered to "expand" these unexpanded
4458 /// parameter packs.
4461 /// template<typename ...Types> struct tuple;
4463 /// template<typename ...Types>
4464 /// struct tuple_of_references {
4465 /// typedef tuple<Types&...> type;
4469 /// Here, the pack expansion \c Types&... is represented via a
4470 /// PackExpansionType whose pattern is Types&.
4471 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4472 /// \brief The pattern of the pack expansion.
4475 /// \brief The number of expansions that this pack expansion will
4476 /// generate when substituted (+1), or indicates that
4478 /// This field will only have a non-zero value when some of the parameter
4479 /// packs that occur within the pattern have been substituted but others have
4481 unsigned NumExpansions;
4483 PackExpansionType(QualType Pattern, QualType Canon,
4484 Optional<unsigned> NumExpansions)
4485 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4486 /*InstantiationDependent=*/true,
4487 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4488 /*ContainsUnexpandedParameterPack=*/false),
4490 NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4492 friend class ASTContext; // ASTContext creates these
4495 /// \brief Retrieve the pattern of this pack expansion, which is the
4496 /// type that will be repeatedly instantiated when instantiating the
4497 /// pack expansion itself.
4498 QualType getPattern() const { return Pattern; }
4500 /// \brief Retrieve the number of expansions that this pack expansion will
4501 /// generate, if known.
4502 Optional<unsigned> getNumExpansions() const {
4504 return NumExpansions - 1;
4509 bool isSugared() const { return !Pattern->isDependentType(); }
4510 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4512 void Profile(llvm::FoldingSetNodeID &ID) {
4513 Profile(ID, getPattern(), getNumExpansions());
4516 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4517 Optional<unsigned> NumExpansions) {
4518 ID.AddPointer(Pattern.getAsOpaquePtr());
4519 ID.AddBoolean(NumExpansions.hasValue());
4521 ID.AddInteger(*NumExpansions);
4524 static bool classof(const Type *T) {
4525 return T->getTypeClass() == PackExpansion;
4529 /// Represents a class type in Objective C.
4531 /// Every Objective C type is a combination of a base type, a set of
4532 /// type arguments (optional, for parameterized classes) and a list of
4535 /// Given the following declarations:
4541 /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
4542 /// with base C and no protocols.
4544 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
4545 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
4547 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
4548 /// and protocol list [P].
4550 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4551 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4552 /// and no protocols.
4554 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4555 /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
4556 /// this should get its own sugar class to better represent the source.
4557 class ObjCObjectType : public Type {
4558 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
4559 // after the ObjCObjectPointerType node.
4560 // ObjCObjectType.NumProtocols - the number of protocols stored
4561 // after the type arguments of ObjCObjectPointerType node.
4563 // These protocols are those written directly on the type. If
4564 // protocol qualifiers ever become additive, the iterators will need
4565 // to get kindof complicated.
4567 // In the canonical object type, these are sorted alphabetically
4570 /// Either a BuiltinType or an InterfaceType or sugar for either.
4573 /// Cached superclass type.
4574 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
4575 CachedSuperClassType;
4577 ObjCProtocolDecl * const *getProtocolStorage() const {
4578 return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
4581 QualType *getTypeArgStorage();
4582 const QualType *getTypeArgStorage() const {
4583 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
4586 ObjCProtocolDecl **getProtocolStorage();
4589 ObjCObjectType(QualType Canonical, QualType Base,
4590 ArrayRef<QualType> typeArgs,
4591 ArrayRef<ObjCProtocolDecl *> protocols,
4594 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4595 ObjCObjectType(enum Nonce_ObjCInterface)
4596 : Type(ObjCInterface, QualType(), false, false, false, false),
4597 BaseType(QualType(this_(), 0)) {
4598 ObjCObjectTypeBits.NumProtocols = 0;
4599 ObjCObjectTypeBits.NumTypeArgs = 0;
4600 ObjCObjectTypeBits.IsKindOf = 0;
4603 void computeSuperClassTypeSlow() const;
4606 /// Gets the base type of this object type. This is always (possibly
4607 /// sugar for) one of:
4608 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
4609 /// user, which is a typedef for an ObjCObjectPointerType)
4610 /// - the 'Class' builtin type (same caveat)
4611 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
4612 QualType getBaseType() const { return BaseType; }
4614 bool isObjCId() const {
4615 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
4617 bool isObjCClass() const {
4618 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
4620 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
4621 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
4622 bool isObjCUnqualifiedIdOrClass() const {
4623 if (!qual_empty()) return false;
4624 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
4625 return T->getKind() == BuiltinType::ObjCId ||
4626 T->getKind() == BuiltinType::ObjCClass;
4629 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
4630 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
4632 /// Gets the interface declaration for this object type, if the base type
4633 /// really is an interface.
4634 ObjCInterfaceDecl *getInterface() const;
4636 /// Determine whether this object type is "specialized", meaning
4637 /// that it has type arguments.
4638 bool isSpecialized() const;
4640 /// Determine whether this object type was written with type arguments.
4641 bool isSpecializedAsWritten() const {
4642 return ObjCObjectTypeBits.NumTypeArgs > 0;
4645 /// Determine whether this object type is "unspecialized", meaning
4646 /// that it has no type arguments.
4647 bool isUnspecialized() const { return !isSpecialized(); }
4649 /// Determine whether this object type is "unspecialized" as
4650 /// written, meaning that it has no type arguments.
4651 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4653 /// Retrieve the type arguments of this object type (semantically).
4654 ArrayRef<QualType> getTypeArgs() const;
4656 /// Retrieve the type arguments of this object type as they were
4658 ArrayRef<QualType> getTypeArgsAsWritten() const {
4659 return llvm::makeArrayRef(getTypeArgStorage(),
4660 ObjCObjectTypeBits.NumTypeArgs);
4663 typedef ObjCProtocolDecl * const *qual_iterator;
4664 typedef llvm::iterator_range<qual_iterator> qual_range;
4666 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4667 qual_iterator qual_begin() const { return getProtocolStorage(); }
4668 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4670 bool qual_empty() const { return getNumProtocols() == 0; }
4672 /// Return the number of qualifying protocols in this interface type,
4673 /// or 0 if there are none.
4674 unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
4676 /// Fetch a protocol by index.
4677 ObjCProtocolDecl *getProtocol(unsigned I) const {
4678 assert(I < getNumProtocols() && "Out-of-range protocol access");
4679 return qual_begin()[I];
4682 /// Retrieve all of the protocol qualifiers.
4683 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
4684 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
4687 /// Whether this is a "__kindof" type as written.
4688 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
4690 /// Whether this ia a "__kindof" type (semantically).
4691 bool isKindOfType() const;
4693 /// Retrieve the type of the superclass of this object type.
4695 /// This operation substitutes any type arguments into the
4696 /// superclass of the current class type, potentially producing a
4697 /// specialization of the superclass type. Produces a null type if
4698 /// there is no superclass.
4699 QualType getSuperClassType() const {
4700 if (!CachedSuperClassType.getInt())
4701 computeSuperClassTypeSlow();
4703 assert(CachedSuperClassType.getInt() && "Superclass not set?");
4704 return QualType(CachedSuperClassType.getPointer(), 0);
4707 /// Strip off the Objective-C "kindof" type and (with it) any
4708 /// protocol qualifiers.
4709 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
4711 bool isSugared() const { return false; }
4712 QualType desugar() const { return QualType(this, 0); }
4714 static bool classof(const Type *T) {
4715 return T->getTypeClass() == ObjCObject ||
4716 T->getTypeClass() == ObjCInterface;
4720 /// A class providing a concrete implementation
4721 /// of ObjCObjectType, so as to not increase the footprint of
4722 /// ObjCInterfaceType. Code outside of ASTContext and the core type
4723 /// system should not reference this type.
4724 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
4725 friend class ASTContext;
4727 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
4728 // will need to be modified.
4730 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
4731 ArrayRef<QualType> typeArgs,
4732 ArrayRef<ObjCProtocolDecl *> protocols,
4734 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
4737 void Profile(llvm::FoldingSetNodeID &ID);
4738 static void Profile(llvm::FoldingSetNodeID &ID,
4740 ArrayRef<QualType> typeArgs,
4741 ArrayRef<ObjCProtocolDecl *> protocols,
4745 inline QualType *ObjCObjectType::getTypeArgStorage() {
4746 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
4749 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
4750 return reinterpret_cast<ObjCProtocolDecl**>(
4751 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
4754 /// Interfaces are the core concept in Objective-C for object oriented design.
4755 /// They basically correspond to C++ classes. There are two kinds of interface
4756 /// types: normal interfaces like `NSString`, and qualified interfaces, which
4757 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
4759 /// ObjCInterfaceType guarantees the following properties when considered
4760 /// as a subtype of its superclass, ObjCObjectType:
4761 /// - There are no protocol qualifiers. To reinforce this, code which
4762 /// tries to invoke the protocol methods via an ObjCInterfaceType will
4763 /// fail to compile.
4764 /// - It is its own base type. That is, if T is an ObjCInterfaceType*,
4765 /// T->getBaseType() == QualType(T, 0).
4766 class ObjCInterfaceType : public ObjCObjectType {
4767 mutable ObjCInterfaceDecl *Decl;
4769 ObjCInterfaceType(const ObjCInterfaceDecl *D)
4770 : ObjCObjectType(Nonce_ObjCInterface),
4771 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
4772 friend class ASTContext; // ASTContext creates these.
4773 friend class ASTReader;
4774 friend class ObjCInterfaceDecl;
4777 /// Get the declaration of this interface.
4778 ObjCInterfaceDecl *getDecl() const { return Decl; }
4780 bool isSugared() const { return false; }
4781 QualType desugar() const { return QualType(this, 0); }
4783 static bool classof(const Type *T) {
4784 return T->getTypeClass() == ObjCInterface;
4787 // Nonsense to "hide" certain members of ObjCObjectType within this
4788 // class. People asking for protocols on an ObjCInterfaceType are
4789 // not going to get what they want: ObjCInterfaceTypes are
4790 // guaranteed to have no protocols.
4800 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
4801 QualType baseType = getBaseType();
4802 while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
4803 if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
4804 return T->getDecl();
4806 baseType = ObjT->getBaseType();
4812 /// Represents a pointer to an Objective C object.
4814 /// These are constructed from pointer declarators when the pointee type is
4815 /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
4816 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
4817 /// and 'Class<P>' are translated into these.
4819 /// Pointers to pointers to Objective C objects are still PointerTypes;
4820 /// only the first level of pointer gets it own type implementation.
4821 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
4822 QualType PointeeType;
4824 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
4825 : Type(ObjCObjectPointer, Canonical,
4826 Pointee->isDependentType(),
4827 Pointee->isInstantiationDependentType(),
4828 Pointee->isVariablyModifiedType(),
4829 Pointee->containsUnexpandedParameterPack()),
4830 PointeeType(Pointee) {}
4831 friend class ASTContext; // ASTContext creates these.
4834 /// Gets the type pointed to by this ObjC pointer.
4835 /// The result will always be an ObjCObjectType or sugar thereof.
4836 QualType getPointeeType() const { return PointeeType; }
4838 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
4840 /// This method is equivalent to getPointeeType() except that
4841 /// it discards any typedefs (or other sugar) between this
4842 /// type and the "outermost" object type. So for:
4844 /// \@class A; \@protocol P; \@protocol Q;
4845 /// typedef A<P> AP;
4847 /// typedef A1<P> A1P;
4848 /// typedef A1P<Q> A1PQ;
4850 /// For 'A*', getObjectType() will return 'A'.
4851 /// For 'A<P>*', getObjectType() will return 'A<P>'.
4852 /// For 'AP*', getObjectType() will return 'A<P>'.
4853 /// For 'A1*', getObjectType() will return 'A'.
4854 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4855 /// For 'A1P*', getObjectType() will return 'A1<P>'.
4856 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4857 /// adding protocols to a protocol-qualified base discards the
4858 /// old qualifiers (for now). But if it didn't, getObjectType()
4859 /// would return 'A1P<Q>' (and we'd have to make iterating over
4860 /// qualifiers more complicated).
4861 const ObjCObjectType *getObjectType() const {
4862 return PointeeType->castAs<ObjCObjectType>();
4865 /// If this pointer points to an Objective C
4866 /// \@interface type, gets the type for that interface. Any protocol
4867 /// qualifiers on the interface are ignored.
4869 /// \return null if the base type for this pointer is 'id' or 'Class'
4870 const ObjCInterfaceType *getInterfaceType() const;
4872 /// If this pointer points to an Objective \@interface
4873 /// type, gets the declaration for that interface.
4875 /// \return null if the base type for this pointer is 'id' or 'Class'
4876 ObjCInterfaceDecl *getInterfaceDecl() const {
4877 return getObjectType()->getInterface();
4880 /// True if this is equivalent to the 'id' type, i.e. if
4881 /// its object type is the primitive 'id' type with no protocols.
4882 bool isObjCIdType() const {
4883 return getObjectType()->isObjCUnqualifiedId();
4886 /// True if this is equivalent to the 'Class' type,
4887 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4888 bool isObjCClassType() const {
4889 return getObjectType()->isObjCUnqualifiedClass();
4892 /// True if this is equivalent to the 'id' or 'Class' type,
4893 bool isObjCIdOrClassType() const {
4894 return getObjectType()->isObjCUnqualifiedIdOrClass();
4897 /// True if this is equivalent to 'id<P>' for some non-empty set of
4899 bool isObjCQualifiedIdType() const {
4900 return getObjectType()->isObjCQualifiedId();
4903 /// True if this is equivalent to 'Class<P>' for some non-empty set of
4905 bool isObjCQualifiedClassType() const {
4906 return getObjectType()->isObjCQualifiedClass();
4909 /// Whether this is a "__kindof" type.
4910 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
4912 /// Whether this type is specialized, meaning that it has type arguments.
4913 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
4915 /// Whether this type is specialized, meaning that it has type arguments.
4916 bool isSpecializedAsWritten() const {
4917 return getObjectType()->isSpecializedAsWritten();
4920 /// Whether this type is unspecialized, meaning that is has no type arguments.
4921 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
4923 /// Determine whether this object type is "unspecialized" as
4924 /// written, meaning that it has no type arguments.
4925 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
4927 /// Retrieve the type arguments for this type.
4928 ArrayRef<QualType> getTypeArgs() const {
4929 return getObjectType()->getTypeArgs();
4932 /// Retrieve the type arguments for this type.
4933 ArrayRef<QualType> getTypeArgsAsWritten() const {
4934 return getObjectType()->getTypeArgsAsWritten();
4937 /// An iterator over the qualifiers on the object type. Provided
4938 /// for convenience. This will always iterate over the full set of
4939 /// protocols on a type, not just those provided directly.
4940 typedef ObjCObjectType::qual_iterator qual_iterator;
4941 typedef llvm::iterator_range<qual_iterator> qual_range;
4943 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4944 qual_iterator qual_begin() const {
4945 return getObjectType()->qual_begin();
4947 qual_iterator qual_end() const {
4948 return getObjectType()->qual_end();
4950 bool qual_empty() const { return getObjectType()->qual_empty(); }
4952 /// Return the number of qualifying protocols on the object type.
4953 unsigned getNumProtocols() const {
4954 return getObjectType()->getNumProtocols();
4957 /// Retrieve a qualifying protocol by index on the object type.
4958 ObjCProtocolDecl *getProtocol(unsigned I) const {
4959 return getObjectType()->getProtocol(I);
4962 bool isSugared() const { return false; }
4963 QualType desugar() const { return QualType(this, 0); }
4965 /// Retrieve the type of the superclass of this object pointer type.
4967 /// This operation substitutes any type arguments into the
4968 /// superclass of the current class type, potentially producing a
4969 /// pointer to a specialization of the superclass type. Produces a
4970 /// null type if there is no superclass.
4971 QualType getSuperClassType() const;
4973 /// Strip off the Objective-C "kindof" type and (with it) any
4974 /// protocol qualifiers.
4975 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
4976 const ASTContext &ctx) const;
4978 void Profile(llvm::FoldingSetNodeID &ID) {
4979 Profile(ID, getPointeeType());
4981 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4982 ID.AddPointer(T.getAsOpaquePtr());
4984 static bool classof(const Type *T) {
4985 return T->getTypeClass() == ObjCObjectPointer;
4989 class AtomicType : public Type, public llvm::FoldingSetNode {
4992 AtomicType(QualType ValTy, QualType Canonical)
4993 : Type(Atomic, Canonical, ValTy->isDependentType(),
4994 ValTy->isInstantiationDependentType(),
4995 ValTy->isVariablyModifiedType(),
4996 ValTy->containsUnexpandedParameterPack()),
4998 friend class ASTContext; // ASTContext creates these.
5001 /// Gets the type contained by this atomic type, i.e.
5002 /// the type returned by performing an atomic load of this atomic type.
5003 QualType getValueType() const { return ValueType; }
5005 bool isSugared() const { return false; }
5006 QualType desugar() const { return QualType(this, 0); }
5008 void Profile(llvm::FoldingSetNodeID &ID) {
5009 Profile(ID, getValueType());
5011 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5012 ID.AddPointer(T.getAsOpaquePtr());
5014 static bool classof(const Type *T) {
5015 return T->getTypeClass() == Atomic;
5019 /// PipeType - OpenCL20.
5020 class PipeType : public Type, public llvm::FoldingSetNode {
5021 QualType ElementType;
5023 PipeType(QualType elemType, QualType CanonicalPtr) :
5024 Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5025 elemType->isInstantiationDependentType(),
5026 elemType->isVariablyModifiedType(),
5027 elemType->containsUnexpandedParameterPack()),
5028 ElementType(elemType) {}
5029 friend class ASTContext; // ASTContext creates these.
5033 QualType getElementType() const { return ElementType; }
5035 bool isSugared() const { return false; }
5037 QualType desugar() const { return QualType(this, 0); }
5039 void Profile(llvm::FoldingSetNodeID &ID) {
5040 Profile(ID, getElementType());
5043 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5044 ID.AddPointer(T.getAsOpaquePtr());
5048 static bool classof(const Type *T) {
5049 return T->getTypeClass() == Pipe;
5054 /// A qualifier set is used to build a set of qualifiers.
5055 class QualifierCollector : public Qualifiers {
5057 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5059 /// Collect any qualifiers on the given type and return an
5060 /// unqualified type. The qualifiers are assumed to be consistent
5061 /// with those already in the type.
5062 const Type *strip(QualType type) {
5063 addFastQualifiers(type.getLocalFastQualifiers());
5064 if (!type.hasLocalNonFastQualifiers())
5065 return type.getTypePtrUnsafe();
5067 const ExtQuals *extQuals = type.getExtQualsUnsafe();
5068 addConsistentQualifiers(extQuals->getQualifiers());
5069 return extQuals->getBaseType();
5072 /// Apply the collected qualifiers to the given type.
5073 QualType apply(const ASTContext &Context, QualType QT) const;
5075 /// Apply the collected qualifiers to the given type.
5076 QualType apply(const ASTContext &Context, const Type* T) const;
5080 // Inline function definitions.
5082 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5083 SplitQualType desugar =
5084 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5085 desugar.Quals.addConsistentQualifiers(Quals);
5089 inline const Type *QualType::getTypePtr() const {
5090 return getCommonPtr()->BaseType;
5093 inline const Type *QualType::getTypePtrOrNull() const {
5094 return (isNull() ? nullptr : getCommonPtr()->BaseType);
5097 inline SplitQualType QualType::split() const {
5098 if (!hasLocalNonFastQualifiers())
5099 return SplitQualType(getTypePtrUnsafe(),
5100 Qualifiers::fromFastMask(getLocalFastQualifiers()));
5102 const ExtQuals *eq = getExtQualsUnsafe();
5103 Qualifiers qs = eq->getQualifiers();
5104 qs.addFastQualifiers(getLocalFastQualifiers());
5105 return SplitQualType(eq->getBaseType(), qs);
5108 inline Qualifiers QualType::getLocalQualifiers() const {
5110 if (hasLocalNonFastQualifiers())
5111 Quals = getExtQualsUnsafe()->getQualifiers();
5112 Quals.addFastQualifiers(getLocalFastQualifiers());
5116 inline Qualifiers QualType::getQualifiers() const {
5117 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5118 quals.addFastQualifiers(getLocalFastQualifiers());
5122 inline unsigned QualType::getCVRQualifiers() const {
5123 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5124 cvr |= getLocalCVRQualifiers();
5128 inline QualType QualType::getCanonicalType() const {
5129 QualType canon = getCommonPtr()->CanonicalType;
5130 return canon.withFastQualifiers(getLocalFastQualifiers());
5133 inline bool QualType::isCanonical() const {
5134 return getTypePtr()->isCanonicalUnqualified();
5137 inline bool QualType::isCanonicalAsParam() const {
5138 if (!isCanonical()) return false;
5139 if (hasLocalQualifiers()) return false;
5141 const Type *T = getTypePtr();
5142 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5145 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5148 inline bool QualType::isConstQualified() const {
5149 return isLocalConstQualified() ||
5150 getCommonPtr()->CanonicalType.isLocalConstQualified();
5153 inline bool QualType::isRestrictQualified() const {
5154 return isLocalRestrictQualified() ||
5155 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5159 inline bool QualType::isVolatileQualified() const {
5160 return isLocalVolatileQualified() ||
5161 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5164 inline bool QualType::hasQualifiers() const {
5165 return hasLocalQualifiers() ||
5166 getCommonPtr()->CanonicalType.hasLocalQualifiers();
5169 inline QualType QualType::getUnqualifiedType() const {
5170 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5171 return QualType(getTypePtr(), 0);
5173 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5176 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5177 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5180 return getSplitUnqualifiedTypeImpl(*this);
5183 inline void QualType::removeLocalConst() {
5184 removeLocalFastQualifiers(Qualifiers::Const);
5187 inline void QualType::removeLocalRestrict() {
5188 removeLocalFastQualifiers(Qualifiers::Restrict);
5191 inline void QualType::removeLocalVolatile() {
5192 removeLocalFastQualifiers(Qualifiers::Volatile);
5195 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5196 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5197 assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
5199 // Fast path: we don't need to touch the slow qualifiers.
5200 removeLocalFastQualifiers(Mask);
5203 /// Return the address space of this type.
5204 inline unsigned QualType::getAddressSpace() const {
5205 return getQualifiers().getAddressSpace();
5208 /// Return the gc attribute of this type.
5209 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5210 return getQualifiers().getObjCGCAttr();
5213 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5214 if (const PointerType *PT = t.getAs<PointerType>()) {
5215 if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5216 return FT->getExtInfo();
5217 } else if (const FunctionType *FT = t.getAs<FunctionType>())
5218 return FT->getExtInfo();
5220 return FunctionType::ExtInfo();
5223 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5224 return getFunctionExtInfo(*t);
5227 /// Determine whether this type is more
5228 /// qualified than the Other type. For example, "const volatile int"
5229 /// is more qualified than "const int", "volatile int", and
5230 /// "int". However, it is not more qualified than "const volatile
5232 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5233 Qualifiers myQuals = getQualifiers();
5234 Qualifiers otherQuals = other.getQualifiers();
5235 return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
5238 /// Determine whether this type is at last
5239 /// as qualified as the Other type. For example, "const volatile
5240 /// int" is at least as qualified as "const int", "volatile int",
5241 /// "int", and "const volatile int".
5242 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5243 return getQualifiers().compatiblyIncludes(other.getQualifiers());
5246 /// If Type is a reference type (e.g., const
5247 /// int&), returns the type that the reference refers to ("const
5248 /// int"). Otherwise, returns the type itself. This routine is used
5249 /// throughout Sema to implement C++ 5p6:
5251 /// If an expression initially has the type "reference to T" (8.3.2,
5252 /// 8.5.3), the type is adjusted to "T" prior to any further
5253 /// analysis, the expression designates the object or function
5254 /// denoted by the reference, and the expression is an lvalue.
5255 inline QualType QualType::getNonReferenceType() const {
5256 if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5257 return RefType->getPointeeType();
5262 inline bool QualType::isCForbiddenLValueType() const {
5263 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5264 getTypePtr()->isFunctionType());
5267 /// Tests whether the type is categorized as a fundamental type.
5269 /// \returns True for types specified in C++0x [basic.fundamental].
5270 inline bool Type::isFundamentalType() const {
5271 return isVoidType() ||
5272 // FIXME: It's really annoying that we don't have an
5273 // 'isArithmeticType()' which agrees with the standard definition.
5274 (isArithmeticType() && !isEnumeralType());
5277 /// Tests whether the type is categorized as a compound type.
5279 /// \returns True for types specified in C++0x [basic.compound].
5280 inline bool Type::isCompoundType() const {
5281 // C++0x [basic.compound]p1:
5282 // Compound types can be constructed in the following ways:
5283 // -- arrays of objects of a given type [...];
5284 return isArrayType() ||
5285 // -- functions, which have parameters of given types [...];
5287 // -- pointers to void or objects or functions [...];
5289 // -- references to objects or functions of a given type. [...]
5290 isReferenceType() ||
5291 // -- classes containing a sequence of objects of various types, [...];
5293 // -- unions, which are classes capable of containing objects of different
5294 // types at different times;
5296 // -- enumerations, which comprise a set of named constant values. [...];
5298 // -- pointers to non-static class members, [...].
5299 isMemberPointerType();
5302 inline bool Type::isFunctionType() const {
5303 return isa<FunctionType>(CanonicalType);
5305 inline bool Type::isPointerType() const {
5306 return isa<PointerType>(CanonicalType);
5308 inline bool Type::isAnyPointerType() const {
5309 return isPointerType() || isObjCObjectPointerType();
5311 inline bool Type::isBlockPointerType() const {
5312 return isa<BlockPointerType>(CanonicalType);
5314 inline bool Type::isReferenceType() const {
5315 return isa<ReferenceType>(CanonicalType);
5317 inline bool Type::isLValueReferenceType() const {
5318 return isa<LValueReferenceType>(CanonicalType);
5320 inline bool Type::isRValueReferenceType() const {
5321 return isa<RValueReferenceType>(CanonicalType);
5323 inline bool Type::isFunctionPointerType() const {
5324 if (const PointerType *T = getAs<PointerType>())
5325 return T->getPointeeType()->isFunctionType();
5329 inline bool Type::isMemberPointerType() const {
5330 return isa<MemberPointerType>(CanonicalType);
5332 inline bool Type::isMemberFunctionPointerType() const {
5333 if (const MemberPointerType* T = getAs<MemberPointerType>())
5334 return T->isMemberFunctionPointer();
5338 inline bool Type::isMemberDataPointerType() const {
5339 if (const MemberPointerType* T = getAs<MemberPointerType>())
5340 return T->isMemberDataPointer();
5344 inline bool Type::isArrayType() const {
5345 return isa<ArrayType>(CanonicalType);
5347 inline bool Type::isConstantArrayType() const {
5348 return isa<ConstantArrayType>(CanonicalType);
5350 inline bool Type::isIncompleteArrayType() const {
5351 return isa<IncompleteArrayType>(CanonicalType);
5353 inline bool Type::isVariableArrayType() const {
5354 return isa<VariableArrayType>(CanonicalType);
5356 inline bool Type::isDependentSizedArrayType() const {
5357 return isa<DependentSizedArrayType>(CanonicalType);
5359 inline bool Type::isBuiltinType() const {
5360 return isa<BuiltinType>(CanonicalType);
5362 inline bool Type::isRecordType() const {
5363 return isa<RecordType>(CanonicalType);
5365 inline bool Type::isEnumeralType() const {
5366 return isa<EnumType>(CanonicalType);
5368 inline bool Type::isAnyComplexType() const {
5369 return isa<ComplexType>(CanonicalType);
5371 inline bool Type::isVectorType() const {
5372 return isa<VectorType>(CanonicalType);
5374 inline bool Type::isExtVectorType() const {
5375 return isa<ExtVectorType>(CanonicalType);
5377 inline bool Type::isObjCObjectPointerType() const {
5378 return isa<ObjCObjectPointerType>(CanonicalType);
5380 inline bool Type::isObjCObjectType() const {
5381 return isa<ObjCObjectType>(CanonicalType);
5383 inline bool Type::isObjCObjectOrInterfaceType() const {
5384 return isa<ObjCInterfaceType>(CanonicalType) ||
5385 isa<ObjCObjectType>(CanonicalType);
5387 inline bool Type::isAtomicType() const {
5388 return isa<AtomicType>(CanonicalType);
5391 inline bool Type::isObjCQualifiedIdType() const {
5392 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5393 return OPT->isObjCQualifiedIdType();
5396 inline bool Type::isObjCQualifiedClassType() const {
5397 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5398 return OPT->isObjCQualifiedClassType();
5401 inline bool Type::isObjCIdType() const {
5402 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5403 return OPT->isObjCIdType();
5406 inline bool Type::isObjCClassType() const {
5407 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5408 return OPT->isObjCClassType();
5411 inline bool Type::isObjCSelType() const {
5412 if (const PointerType *OPT = getAs<PointerType>())
5413 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5416 inline bool Type::isObjCBuiltinType() const {
5417 return isObjCIdType() || isObjCClassType() || isObjCSelType();
5420 inline bool Type::isImage1dT() const {
5421 return isSpecificBuiltinType(BuiltinType::OCLImage1d);
5424 inline bool Type::isImage1dArrayT() const {
5425 return isSpecificBuiltinType(BuiltinType::OCLImage1dArray);
5428 inline bool Type::isImage1dBufferT() const {
5429 return isSpecificBuiltinType(BuiltinType::OCLImage1dBuffer);
5432 inline bool Type::isImage2dT() const {
5433 return isSpecificBuiltinType(BuiltinType::OCLImage2d);
5436 inline bool Type::isImage2dArrayT() const {
5437 return isSpecificBuiltinType(BuiltinType::OCLImage2dArray);
5440 inline bool Type::isImage2dDepthT() const {
5441 return isSpecificBuiltinType(BuiltinType::OCLImage2dDepth);
5444 inline bool Type::isImage2dArrayDepthT() const {
5445 return isSpecificBuiltinType(BuiltinType::OCLImage2dArrayDepth);
5448 inline bool Type::isImage2dMSAAT() const {
5449 return isSpecificBuiltinType(BuiltinType::OCLImage2dMSAA);
5452 inline bool Type::isImage2dArrayMSAAT() const {
5453 return isSpecificBuiltinType(BuiltinType::OCLImage2dArrayMSAA);
5456 inline bool Type::isImage2dMSAATDepth() const {
5457 return isSpecificBuiltinType(BuiltinType::OCLImage2dMSAADepth);
5460 inline bool Type::isImage2dArrayMSAATDepth() const {
5461 return isSpecificBuiltinType(BuiltinType::OCLImage2dArrayMSAADepth);
5464 inline bool Type::isImage3dT() const {
5465 return isSpecificBuiltinType(BuiltinType::OCLImage3d);
5468 inline bool Type::isSamplerT() const {
5469 return isSpecificBuiltinType(BuiltinType::OCLSampler);
5472 inline bool Type::isEventT() const {
5473 return isSpecificBuiltinType(BuiltinType::OCLEvent);
5476 inline bool Type::isClkEventT() const {
5477 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
5480 inline bool Type::isQueueT() const {
5481 return isSpecificBuiltinType(BuiltinType::OCLQueue);
5484 inline bool Type::isNDRangeT() const {
5485 return isSpecificBuiltinType(BuiltinType::OCLNDRange);
5488 inline bool Type::isReserveIDT() const {
5489 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
5492 inline bool Type::isImageType() const {
5493 return isImage3dT() || isImage2dT() || isImage2dArrayT() ||
5494 isImage2dDepthT() || isImage2dArrayDepthT() || isImage2dMSAAT() ||
5495 isImage2dArrayMSAAT() || isImage2dMSAATDepth() ||
5496 isImage2dArrayMSAATDepth() || isImage1dT() || isImage1dArrayT() ||
5500 inline bool Type::isPipeType() const {
5501 return isa<PipeType>(CanonicalType);
5504 inline bool Type::isOpenCLSpecificType() const {
5505 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
5506 isQueueT() || isNDRangeT() || isReserveIDT() || isPipeType();
5509 inline bool Type::isTemplateTypeParmType() const {
5510 return isa<TemplateTypeParmType>(CanonicalType);
5513 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5514 if (const BuiltinType *BT = getAs<BuiltinType>())
5515 if (BT->getKind() == (BuiltinType::Kind) K)
5520 inline bool Type::isPlaceholderType() const {
5521 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5522 return BT->isPlaceholderType();
5526 inline const BuiltinType *Type::getAsPlaceholderType() const {
5527 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5528 if (BT->isPlaceholderType())
5533 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5534 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5535 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5536 return (BT->getKind() == (BuiltinType::Kind) K);
5540 inline bool Type::isNonOverloadPlaceholderType() const {
5541 if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5542 return BT->isNonOverloadPlaceholderType();
5546 inline bool Type::isVoidType() const {
5547 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5548 return BT->getKind() == BuiltinType::Void;
5552 inline bool Type::isHalfType() const {
5553 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5554 return BT->getKind() == BuiltinType::Half;
5555 // FIXME: Should we allow complex __fp16? Probably not.
5559 inline bool Type::isNullPtrType() const {
5560 if (const BuiltinType *BT = getAs<BuiltinType>())
5561 return BT->getKind() == BuiltinType::NullPtr;
5565 extern bool IsEnumDeclComplete(EnumDecl *);
5566 extern bool IsEnumDeclScoped(EnumDecl *);
5568 inline bool Type::isIntegerType() const {
5569 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5570 return BT->getKind() >= BuiltinType::Bool &&
5571 BT->getKind() <= BuiltinType::Int128;
5572 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5573 // Incomplete enum types are not treated as integer types.
5574 // FIXME: In C++, enum types are never integer types.
5575 return IsEnumDeclComplete(ET->getDecl()) &&
5576 !IsEnumDeclScoped(ET->getDecl());
5581 inline bool Type::isScalarType() const {
5582 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5583 return BT->getKind() > BuiltinType::Void &&
5584 BT->getKind() <= BuiltinType::NullPtr;
5585 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5586 // Enums are scalar types, but only if they are defined. Incomplete enums
5587 // are not treated as scalar types.
5588 return IsEnumDeclComplete(ET->getDecl());
5589 return isa<PointerType>(CanonicalType) ||
5590 isa<BlockPointerType>(CanonicalType) ||
5591 isa<MemberPointerType>(CanonicalType) ||
5592 isa<ComplexType>(CanonicalType) ||
5593 isa<ObjCObjectPointerType>(CanonicalType);
5596 inline bool Type::isIntegralOrEnumerationType() const {
5597 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5598 return BT->getKind() >= BuiltinType::Bool &&
5599 BT->getKind() <= BuiltinType::Int128;
5601 // Check for a complete enum type; incomplete enum types are not properly an
5602 // enumeration type in the sense required here.
5603 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5604 return IsEnumDeclComplete(ET->getDecl());
5609 inline bool Type::isBooleanType() const {
5610 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5611 return BT->getKind() == BuiltinType::Bool;
5615 inline bool Type::isUndeducedType() const {
5616 const AutoType *AT = getContainedAutoType();
5617 return AT && !AT->isDeduced();
5620 /// \brief Determines whether this is a type for which one can define
5621 /// an overloaded operator.
5622 inline bool Type::isOverloadableType() const {
5623 return isDependentType() || isRecordType() || isEnumeralType();
5626 /// \brief Determines whether this type can decay to a pointer type.
5627 inline bool Type::canDecayToPointerType() const {
5628 return isFunctionType() || isArrayType();
5631 inline bool Type::hasPointerRepresentation() const {
5632 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5633 isObjCObjectPointerType() || isNullPtrType());
5636 inline bool Type::hasObjCPointerRepresentation() const {
5637 return isObjCObjectPointerType();
5640 inline const Type *Type::getBaseElementTypeUnsafe() const {
5641 const Type *type = this;
5642 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5643 type = arrayType->getElementType().getTypePtr();
5647 /// Insertion operator for diagnostics. This allows sending QualType's into a
5648 /// diagnostic with <<.
5649 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
5651 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5652 DiagnosticsEngine::ak_qualtype);
5656 /// Insertion operator for partial diagnostics. This allows sending QualType's
5657 /// into a diagnostic with <<.
5658 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
5660 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
5661 DiagnosticsEngine::ak_qualtype);
5665 // Helper class template that is used by Type::getAs to ensure that one does
5666 // not try to look through a qualified type to get to an array type.
5667 template <typename T, bool isArrayType = (std::is_same<T, ArrayType>::value ||
5668 std::is_base_of<ArrayType, T>::value)>
5669 struct ArrayType_cannot_be_used_with_getAs {};
5671 template<typename T>
5672 struct ArrayType_cannot_be_used_with_getAs<T, true>;
5674 // Member-template getAs<specific type>'.
5675 template <typename T> const T *Type::getAs() const {
5676 ArrayType_cannot_be_used_with_getAs<T> at;
5679 // If this is directly a T type, return it.
5680 if (const T *Ty = dyn_cast<T>(this))
5683 // If the canonical form of this type isn't the right kind, reject it.
5684 if (!isa<T>(CanonicalType))
5687 // If this is a typedef for the type, strip the typedef off without
5688 // losing all typedef information.
5689 return cast<T>(getUnqualifiedDesugaredType());
5692 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
5693 // If this is directly an array type, return it.
5694 if (const ArrayType *arr = dyn_cast<ArrayType>(this))
5697 // If the canonical form of this type isn't the right kind, reject it.
5698 if (!isa<ArrayType>(CanonicalType))
5701 // If this is a typedef for the type, strip the typedef off without
5702 // losing all typedef information.
5703 return cast<ArrayType>(getUnqualifiedDesugaredType());
5706 template <typename T> const T *Type::castAs() const {
5707 ArrayType_cannot_be_used_with_getAs<T> at;
5710 if (const T *ty = dyn_cast<T>(this)) return ty;
5711 assert(isa<T>(CanonicalType));
5712 return cast<T>(getUnqualifiedDesugaredType());
5715 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
5716 assert(isa<ArrayType>(CanonicalType));
5717 if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
5718 return cast<ArrayType>(getUnqualifiedDesugaredType());
5721 } // end namespace clang